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': 'Enumerate shares using valid credentials',
        'query': 'SELECT username,password,domain,host FROM pentestly_creds WHERE success="True"',
    }

    def module_run(self, creds):
        # Reduce creds if options are given
        output_shares = {}
        shares = None
        for username, password, domain, host in creds:
            if username == None:
                username = ''
            if password == None:
                password = ''
            self.smb.hosts[host] = {'user':username, 'passwd':password, 'domain':domain, 'port': 445}
            success = self.smb.login(host, username, password, domain)
            self.output("Execution creds: {}\{}:{}@{}".format(domain, username, password, host))
            if success:
                try:
                    shares = self.smb.output_shares(host, lsshare=False, lspath=False, verbose=False)
                except Exception as e:
                    if 'ACCESS_DENIED' in str(e):
                        continue
                    self.error(str(e))
                if not shares:
                    continue
                print(shares)
                readonly = ','.join(shares.get('readonly',''))
                noaccess = ','.join(shares.get('noaccess', ''))
                self.add_pentestly_shares(host, username=username, readonly=readonly, noaccess=noaccess)
            else:
                self.error("Bad login")
