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 nbtstat',
        'author': 'Cory Duplantis (@ctfhacker)',
        'description': 'Run "nbtstat -A" in order to determine where domain admins are logged in.',
        'query': 'SELECT username,password,domain,host FROM pentestly_creds WHERE success="True" AND execute!="False"',
    }

    def module_run(self, creds):
        share = 'C$'
        username, password, domain, host = creds[0]
        hosts = [h[0] for h in self.query("select ip_address from ports where port='445'")]
        domain_admins = self.get_domain_admins()
        for curr_host in hosts:
            command = 'nbtstat -A {}'.format(curr_host)
            result = self.wmi_execute(username, password, domain, host, command)

            for item in result.split('\n'):
                if '<03>' not in item:
                    continue

                item = item.split()
                try:
                    curr_user = self.to_unicode(item[7].lower())
                except IndexError:
                    continue

                if curr_user not in domain_admins:
                    continue

                item = item[0]
                self.alert("[{}] Item found: {}:{}".format(host, curr_user, item))

                password = self.query('SELECT password FROM pentestly_creds WHERE username="{}" and domain="{}"'.format(username, domain.lower()))
                password = password[0][0]
                self.add_pentestly_creds(host=host, username=username, password=password, domain=domain, logged_in=True)
