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

from collections import defaultdict

class Module(PentestlyModule):

    meta = {
        'name': 'Enumshares',
        'author': 'Cory Duplantis (@ctfhacker)',
        'description': 'Identify interesting files from network shares using valid credentials',
        'query': 'SELECT host,username,readonly,readwrite FROM pentestly_shares',
        'options': (
            ('pattern', '(Groups.xml|Services.xml|Printers.xml|Drives.xml|DataSources.xml|ScheduledTasks.xml|unattend|important|passw).*[^dll][^exe]$',\
                         False, 'File pattern to search for in open shares.'),
        ),
    }

    def module_run(self, shares):
        pattern = self.options['pattern']
        for host, username, readonly, readwrite in shares:
            curr_shares = []

            if readonly:
                curr_shares = readonly.split(',')

            if not curr_shares:
                continue

            curr_shares = set(curr_shares)

            self.output(username)
            if not username:
                username = ''
                password = ''
                domain = 'workgroup'
            else:
                password, domain = self.query('SELECT password,domain from pentestly_creds where username="{}" and host="{}"'.format(
                                                username, host))[0]
            self.smb.hosts[host] = {'user':username, 'passwd':password, 'domain':domain, 'port': 445}
            success = self.smb.login(host, username, password, domain)
            for curr_share in curr_shares:
                self.output("Execution creds: {} {}\{}:{}@{}".format(curr_share, domain, username, password, host))
                if success:
                    self.smb.list_path_recursive(host, curr_share, '/', '*', {}, pattern, False)
                else:
                    self.error("Bad login")
