from __future__ import print_function
from recon.core.module import BaseModule

import os
import subprocess

from libs.pentestlymodule import PentestlyModule
from libs.misc import parse_mimikatz

class Module(PentestlyModule):

    meta = {
        'name': 'Discover Domain Admin via Tasklist',
        'author': 'Cory Duplantis (@ctfhacker)',
        'description': 'Run "tasklist /V" in order to determine DA processes.',
        'query': 'SELECT username,password,domain,host FROM pentestly_creds WHERE success="True" AND execute!="False"',
    }

    def module_run(self, creds):
        share = 'C$'
        command = 'tasklist /V'

        domain_admins = self.query('SELECT domain, username FROM pentestly_creds WHERE access = "Domain Admin"')
        domain_admins = ['\\'.join([domain,username]).lower() for domain,username in domain_admins]

        # Reduce creds if options are given
        for username, password, domain, host in creds:
            self.smb.hosts[host] = {'user':username, 'passwd':password, 'domain':domain, 'port': 445}
            result = self.wmi_execute(username, password, domain, host, command)

            for process in result.split('\n'):
                process = process.split()
                try:
                    curr_user = self.to_unicode(process[7])
                except IndexError:
                    continue

                if curr_user.lower() not in domain_admins:
                    continue

                curr_domain, curr_username = curr_user.split('\\')
                proc = process[0]
                self.alert("[{}] Process found: {}:{}".format(host, curr_user, proc))
                password = self.query('SELECT password FROM pentestly_creds WHERE username="{}" and domain="{}"'.format(curr_username, curr_domain.lower()))
                password = password[0][0]
                # self.output("Password: {}".format(password))
                self.pentestly_update(new_vals={'process':proc}, conditions={'host':host, 
                                                                       'username':curr_username, 
                                                                       'password':password,
                                                                       'domain':curr_domain.lower()})
