Esempio n. 1
0
def smbServer(HOST="127.0.0.1",
              PORT="445",
              USER="******",
              PASS="******",
              SHAREPATH="/opt/oscpPWN/db/shares"):

    signal.signal(signal.SIGINT, signal_handler)
    server = smbserver.SimpleSMBServer(HOST, int(PORT))

    server.addShare("shares", SHAREPATH, "")
    server.setSMB2Support(True)

    # If a user was specified, let's add it to the credentials for the SMBServer. If no user is specified, anonymous
    # connections will be allowed
    lmhash = compute_lmhash(PASS)
    nthash = compute_nthash(PASS)

    #server.addCredential(USER, 0, lmhash, nthash)

    # Here you can set a custom SMB challenge in hex format
    # If empty defaults to '4141414141414141'
    # (remember: must be 16 hex bytes long)
    # e.g. server.setSMBChallenge('12345678abcdef00')
    server.setSMBChallenge('')

    # If you don't want log to stdout, comment the following line
    # If you want log dumped to a file, enter the filename
    #server.setLogFile('')

    # Rock and roll
    server.start()
Esempio n. 2
0
    def __init__(self,
                 logger,
                 share_name,
                 share_path='/tmp/cme_hosted',
                 listen_address='0.0.0.0',
                 listen_port=445,
                 verbose=False):
        try:
            threading.Thread.__init__(self)

            self.server = smbserver.SimpleSMBServer(listen_address,
                                                    listen_port)
            self.server.addShare(share_name.upper(), share_path)
            if verbose: self.server.setLogFile('')
            self.server.setSMB2Support(True)
            self.server.setSMBChallenge('')
        except Exception as e:
            errno, message = e.args
            if errno == 98 and message == 'Address already in use':
                logger.error(
                    'Error starting SMB server on port 445: the port is already in use'
                )
            else:
                logger.error(
                    'Error starting SMB server on port 445: {}'.format(
                        message))
                exit(1)
Esempio n. 3
0
    def serve(self):
        try:

            # Current directory
            exfil_directory = os.path.join(os.getcwd(), 'transfer')
            loot_path = exfil_directory + "/"

            # Check to make sure the agent directory exists, and a loot
            # directory for the agent. If not, create them
            if not os.path.isdir(loot_path):
                os.makedirs(loot_path)

            server = smbserver.SimpleSMBServer('0.0.0.0', self.port)
            server.setSMB2Support(self.smb2support)

            if self.username and self.password:
                server.addCredential(self.username, 0, self.lmhash,
                                     self.nthash)

            server.addShare("TRANSFER", "transfer/",
                            "Egress-Assess transfer share")

            # If you don't want log to stdout, comment the following line
            # If you want log dumped to a file, enter the filename
            server.setLogFile('')

            print(f'[*] SMB server is currently running on {self.port}.')
            print('[*] Note: port 445 is blocked by some ISPs.')

            # Rock and roll
            server.start()
        # Handle keyboard interrupts
        except KeyboardInterrupt:
            print('Stopping the SMB server.')
Esempio n. 4
0
    def negotiatedServe(self):
        try:
            # current directory
            exfil_directory = os.path.join(os.getcwd(), "data")
            loot_path = exfil_directory + "/"

            # Check to make sure the agent directory exists, and a loot
            # directory for the agent.  If not, make them
            if not os.path.isdir(loot_path):
                os.makedirs(loot_path)

            server = smbserver.SimpleSMBServer('0.0.0.0', self.port)
            if self.smb2support:
                server.setSMB2Support(self.smb2support)

            if self.username != "null" and self.password != "null":
                self.lmhash = compute_lmhash(self.password)
                self.nthash = compute_nthash(self.password)
                server.addCredential(self.username, 0, self.lmhash,
                                     self.nthash)

            server.addShare("DATA", "data/", "Egress-Assess data share")

            # Rock and roll
            server.start()
        # handle keyboard interrupts
        except KeyboardInterrupt:
            print "[!] Rage quiting, and stopping the smb server!"
            sys.exit(0)

        return
Esempio n. 5
0
    def __init__(self, logger, share_name, share_path=str(cfg.TMP_PATH), listen_address='0.0.0.0', listen_port=445, verbose=False, username='', password='', hashes=''):
        try:
            threading.Thread.__init__(self)

            self.server = smbserver.SimpleSMBServer(listen_address, listen_port)
            self.server.addShare(share_name.upper(), share_path)
            if verbose: self.server.setLogFile('')
            self.server.setSMB2Support(True)   #TODO: This needs a check on what version the login used.

            # adding credentials incase the org has disabled anon smb access
            # password can be a list of passwords, we only gonna make this work if you pass 1 password for now...
            if password is not '':
                lmhash = compute_lmhash(password[0])
                nthash = compute_nthash(password[0])
            else:
                lmhash, nthash = hashes.split(':')
            
            # username can be a list of users, we only gonna make this work if you pass 1 user for now...
            self.server.addCredential(username[0], 0, lmhash, nthash)

            # Here you can set a custom SMB challenge in hex format, If empty defaults to '4141414141414141'
            # e.g. server.setSMBChallenge('12345678abcdef00')
            #self.server.setSMBChallenge('') 

        except Exception as e:
            errno, message = e.args
            if errno == 98 and message == 'Address already in use':
                logger.error('Error starting SMB server on port 445: the port is already in use')
            else:
                logger.error('Error starting SMB server on port 445: {}'.format(message))
                exit(1)
Esempio n. 6
0
def main():
	parser = argparse.ArgumentParser(description="SMB Spider for PS1 Scripts")
	parser.add_argument('-ip','--ipaddress',help='Target IP',required=True)
	parser.add_argument('-u','--user',help='user',required=True)
	parser.add_argument('-p','--pwd',help='password',required=True)
	parser.add_argument('-d','--domain',help='domain',required=True)
	parser.add_argument('-s','--share',help='SMB Share', required=True)
	parser.add_argument('-f','--subfolder',help='SMB Subfolder to drop SCF file onto.', required=False)
	parser.add_argument('-o','--outfile',help='Outfile to log hashes',required=False)
	parser.add_argument('--cleanup',action='store_true',help='Remove SCF file from Share, MUST be ran with switches used previously', required=False)

	args = parser.parse_args()

	if args.cleanup:
		clean_up(args.ipaddress, args.share, args.subfolder, args.user, args.pwd, args.domain)
		exit()
	else:
		drop_it_like_its_hot(args.ipaddress, args.share, args.subfolder, args.user, args.pwd, args.domain)

		print (Fore.GREEN+"[+] Done Dropping SCF's...  Launching SMBServer To Catch Creds...\r\n" + Style.RESET_ALL)

		ni.ifaddresses('eth0')
	        ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']

		server = smbserver.SimpleSMBServer(listenAddress=ip, listenPort=445)
		server.addShare("SHARE", ".", '')
		server.setSMB2Support(True)

		server.setSMBChallenge('')
		if args.outfile:
			server.setLogFile(args.outfile)
		else:
			server.setLogFile('')

		server.start()
Esempio n. 7
0
    def serve(self):
        try:

            # current directory
            exfil_directory = os.path.join(os.getcwd(), "data")
            loot_path = exfil_directory + "/"

            # Check to make sure the agent directory exists, and a loot
            # directory for the agent.  If not, make them
            if not os.path.isdir(loot_path):
                os.makedirs(loot_path)

            server = smbserver.SimpleSMBServer('0.0.0.0', self.port)
            if self.smb2support:
                server.setSMB2Support(self.smb2support)

            if self.username and self.password:
                server.addCredential(self.username, 0, self.lmhash,
                                     self.nthash)

            server.addShare("DATA", "data/", "Egress-Assess data share")

            # If you don't want log to stdout, comment the following line
            # If you want log dumped to a file, enter the filename
            server.setLogFile('')

            print "[*] SMB server is currently running..."

            # Rock and roll
            server.start()
        # handle keyboard interrupts
        except KeyboardInterrupt:
            print "[!] Rage quiting, and stopping the smb server!"
        return
Esempio n. 8
0
def main():
    logger.init()
    logging.getLogger().setLevel(logging.DEBUG)

    server = smbserver.SimpleSMBServer(listenAddress="0.0.0.0", listenPort=445)
    server.setSMB2Support(True)
    server.setSMBChallenge('')

    print "Starting server:"
    server.start()
def hostPayload(lhost, outputDir, shareName):   
    server = smbserver.SimpleSMBServer(listenAddress=lhost, listenPort=445)
    server.addShare(shareName, outputDir)   
    # If the host you're talking to doesnt support SMBv1 this can be uncommented to enable it.  This is an experimental impacket feature.
    #server.setSMB2Support(True)
    server.setSMBChallenge('')
    print(event + "Hosting payload at [\\\\{}\{}]".format(lhost, shareName))
    server.start()
    time.sleep(5)
    server.stop()
Esempio n. 10
0
    def smb_server_main(self):
        _q_s = self

        class Logger(object):
            def write(self, message):
                #sys.stdout.write(str(">>>>" + message))
                # sys.stdout.flush()
                try:
                    if "Incoming connection" in message.strip(
                    ) or "AUTHENTICATE_MESSAGE" in message.strip(
                    ) or "authenticated successfully" in message.strip():
                        _q_s.logs.info([
                            "servers", {
                                'server': 'smb_server',
                                'action': 'connection',
                                'msg': message.strip()
                            }
                        ])
                    elif ":4141414141414141:" in message.strip():
                        parsed = message.strip().split(":")
                        if len(parsed) > 2:
                            _q_s.logs.info([
                                "servers", {
                                    'server': 'smb_server',
                                    'action': 'login',
                                    'workstation': parsed[0],
                                    'test': parsed[1]
                                }
                            ])
                except Exception as e:
                    _q_s.logs.error([
                        "errors", {
                            'server': 'smb_server',
                            'error': 'write',
                            "type": "error -> " + repr(e)
                        }
                    ])

        handler = StreamHandler(Logger())
        getLogger("impacket").addHandler(handler)
        getLogger("impacket").setLevel(DEBUG)

        dirpath = mkdtemp()
        server = smbserver.SimpleSMBServer(listenAddress=self.ip,
                                           listenPort=self.port)
        # server.removeShare("IPC$")
        server.addShare('C$', dirpath, '', readOnly='yes')
        server.setSMB2Support(True)
        server.addCredential(self.username, 0, compute_lmhash(self.password),
                             compute_nthash(self.password))
        server.setSMBChallenge('')
        server.start()
        rmtree(dirpath)
Esempio n. 11
0
    def __init__(self, listenAddress='0.0.0.0', listenPort=445, configFile=''):

        try:
            self.server = smbserver.SimpleSMBServer(listenAddress, listenPort,
                                                    configFile)
            self.server.setSMBChallenge(
                self.config["MITMf"]["SMB"]["Challenge"])
        except socketerror as e:
            if "Address already in use" in e:
                shutdown(
                    "\n[-] Unable to start SMB server on port 445: port already in use"
                )
Esempio n. 12
0
def execute():
    host = raw_input(info + ' Enter the connect back IP addr: ')
    payload_check = False
    while payload_check == False:
        payload = raw_input(info + ' Payload: ' + reset)
        if check(payload) == True: payload_check = True
        else:
            print(neg + " [-] The specified file doesn\'t exist. Try agains" +
                  reset)
    f = open('modules/smb_vec.ino', 'r')
    code = f.read()
    f.close()
    shutil.copy(payload, 'server/')
    os.chdir('server/')

    try:
        mal = payload.split('/')[-1]

    except:
        pass
    '''
        if '/' in payload:
            os.rename(payload, os.getcwd() +'/' + mal)
        else:
            os.rename('../' + mal, os.getcwd()+ '/' + mal)
        '''
    code = code.replace('|host|', host)
    code = code.replace('|mal|', mal)
    #print code
    ino_name = 'smb_vec' + str(time.ctime()).replace(' ', '-') + '.ino'
    ino = open(ino_name, 'w')
    ino.write(code)
    ino.close()
    print(blue + ' [+] Digispark code is saved to %s' % BOLD + UNDERLINE +
          os.getcwd() + '/' + ino_name + reset)
    print(info + " [!] Starting SMB server..." + reset)

    server = smbserver.SimpleSMBServer()
    server.addShare('MAL', os.getcwd())
    server.setSMB2Support(True)
    try:

        def server_():
            server.start()

        thread = threading.Thread(target=server_)
        thread.start()
        raw_input(' Server started.' + neg + ' Hit enter to stop.')
        kill()
    except Exception as e:
        print(neg + ' Error! %s ' % e)
Esempio n. 13
0
def setup_smb(path="/usr/share/windows-binaries"):
    try:
        if port_in_use(445):
            raise Exception("SMB-Server already running!")
        log.info("Starting SMB-Server...")
        server = smbserver.SimpleSMBServer(listenAddress=f"{get_ip('tun0')}",
                                           listenPort=445)
        server.addShare("share", path, "")
        server.setSMB2Support(True)
        server.start()
    except KeyboardInterrupt:
        pass
    except:
        raise Exception("Could not setup smb!")
Esempio n. 14
0
    def __init__(self,
                 logger,
                 share_name,
                 share_path='/tmp/.ar3/smb',
                 share_comment='',
                 username='',
                 password='',
                 listen_address='0.0.0.0',
                 listen_port=445,
                 verbose=False):
        self.logger = logger
        self.running = True
        self._smb2support = False
        self._share_path = share_path

        try:
            threading.Thread.__init__(self)

            # If suggested share_path not exist, create
            if not os.path.exists(share_path):
                os.makedirs(share_path)

            # Setup SMB Server
            self.server = smbserver.SimpleSMBServer(listen_address,
                                                    int(listen_port))
            self.server.addShare(share_name, share_path, share_comment)
            if verbose: self.server.setLogFile('')
            self.server.setSMB2Support(self._smb2support)
            self.server.setSMBChallenge('')

            if username:
                if password:
                    lmhash = compute_lmhash(password)
                    nthash = compute_nthash(password)
                self.server.addCredential(username, 0, lmhash, nthash)

        except Exception as e:
            errno, message = e.args
            if errno == 98 and message == 'Address already in use':
                self.logger.fail(
                    'Error starting SMB server on port 445: the port is already in use'
                )
            else:
                self.logger.fail(
                    'Error starting SMB server on port 445: {}'.format(
                        message))
                exit(1)
Esempio n. 15
0
    def __init__(self, logger, share_name, verbose=False):

        try:
            threading.Thread.__init__(self)

            self.server = smbserver.SimpleSMBServer()
            self.server.addShare(share_name.upper(),
                                 os.path.join('/tmp', 'cme_hosted'))
            if verbose: self.server.setLogFile('')
            self.server.setSMB2Support(False)
            self.server.setSMBChallenge('')

        except Exception as e:
            errno, message = e.args
            if errno == 98 and message == 'Address already in use':
                logger.error(
                    'Error starting SMB server: the port is already in use')
            else:
                logger.error('Error starting SMB server: {}'.format(message))

            sys.exit(1)
Esempio n. 16
0
    def __init__(self):
        # Setup logging
        handler = logging.StreamHandler(Logger())
        logging.getLogger().addHandler(handler)
        logging.getLogger().setLevel(logging.DEBUG)

        # Create a new SMB server
        server = smbserver.SimpleSMBServer()

        # Support SMBv2
        server.setSMB2Support(True)

        # Set a random SMB challenge
        challenge = ''.join(random.choice(string.digits) for i in range(16))
        server.setSMBChallenge(challenge)

        # Log SMB traffic to console
        server.setLogFile('')

        # Start the server
        server.start()
Esempio n. 17
0
    def parseConfig(self):
        server = None
        try:
            if self.server_type == 'normal':

                formatter = logging.Formatter("%(asctime)s [SMBserver] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
                self.configureLogging(formatter)

                server = smbserver.SimpleSMBServer(listenPort=self.smb_port)
                
                for share in self.config["MITMf"]["SMB"]["Shares"]:
                    path = self.config["MITMf"]["SMB"]["Shares"][share]['path']
                    readonly = self.config["MITMf"]["SMB"]["Shares"][share]['readonly'].lower()
                    server.addShare(share.upper(), path, readOnly=readonly)

                server.setSMBChallenge(self.smbchallenge)
                server.setLogFile('')

            elif self.server_type == 'karma':

                formatter = logging.Formatter("%(asctime)s [KarmaSMB] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
                self.configureLogging(formatter)

                server = KarmaSMBServer(self.smbchallenge, self.smb_port)
                server.defaultFile = self.config["MITMf"]["SMB"]["Karma"]["defaultfile"]
                
                for extension, path in self.config["MITMf"]["SMB"]["Karma"].iteritems():
                    server.extensions[extension.upper()] = os.path.normpath(path)

            else:
                shutdown("\n[-] Invalid SMB server type specified in config file!")

            return server
        
        except socketerror as e:
            if "Address already in use" in e:
                shutdown("\n[-] Unable to start SMB server on port {}: port already in use".format(listenPort))
Esempio n. 18
0
def start_server(type_):
    if 'server' in os.listdir(os.getcwd()):
        pass
    else:
        try:
            os.mkdir('server')
        except Exception as e:
            print(info + ' Error %s continuing...' % e)
            pass
    #os.system('mv %s server/' % mal)
    os.rename(mal, 'server/' + mal)
    os.chdir('server/')
    if type_ == 'SMB':
        create_ino(smbcode)
        print(info + ' Starting the Samba Server...')
        server = smbserver.SimpleSMBServer()
        server.addShare('MAL', os.getcwd())
        try:
            server.start()
        except Exception as e:
            print(neg + ' Error! %s ' % e)
    else:
        create_ino(httpcode)
        os.system('python -m SimpleHTTPServer 3456')
Esempio n. 19
0
        options = parser.parse_args()
    except Exception, e:
        logging.critical(str(e))
        sys.exit(1)

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    if options.comment is None:
        comment = ''
    else:
        comment = options.comment

    server = smbserver.SimpleSMBServer(listenAddress=options.interface_address)

    server.addShare(options.shareName.upper(), options.sharePath, comment)
    server.setSMB2Support(options.smb2support)

    # If a user was specified, let's add it to the credentials for the SMBServer. If no user is specified, anonymous
    # connections will be allowed
    if options.username is not None:
        # we either need a password or hashes, if not, ask
        if options.password is None and options.hashes is None:
            from getpass import getpass
            password = getpass("Password:")
            # Let's convert to hashes
            lmhash = compute_lmhash(password)
            nthash = compute_nthash(password)
        elif options.password is not None:
Esempio n. 20
0
       options = parser.parse_args()
    except Exception, e:
       logging.critical(str(e))
       sys.exit(1)

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    if options.comment is None:
        comment = ''
    else:
        comment = options.comment

    server = smbserver.SimpleSMBServer()

    server.addShare(options.shareName.upper(), options.sharePath, comment)
    server.setSMB2Support(options.smb2support)
   
    # Here you can set a custom SMB challenge in hex format
    # If empty defaults to '4141414141414141'
    # (remember: must be 16 hex bytes long)
    # e.g. server.setSMBChallenge('12345678abcdef00')
    server.setSMBChallenge('')

    # If you don't want log to stdout, comment the following line
    # If you want log dumped to a file, enter the filename
    server.setLogFile('')

    # Rock and roll
Esempio n. 21
0
 def __init__(self, listenAddress='0.0.0.0', listenPort=445, configFile=''):
     self._smbsrvr = smbserver.SimpleSMBServer(listenAddress=listenAddress, listenPort=listenPort, configFile=configFile)
     self._thread = None
     return
Esempio n. 22
0
       options = parser.parse_args()
    except Exception, e:
       logging.critical(str(e))
       sys.exit(1)

    if options.debug is True:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    if options.comment is None:
        comment = ''
    else:
        comment = options.comment

    server = smbserver.SimpleSMBServer(listenAddress=options.interface_address, listenPort=int(options.port))

    server.addShare(options.shareName.upper(), options.sharePath, comment)
    server.setSMB2Support(options.smb2support)

    # If a user was specified, let's add it to the credentials for the SMBServer. If no user is specified, anonymous
    # connections will be allowed
    if options.username is not None:
        # we either need a password or hashes, if not, ask
        if options.password is None and options.hashes is None:
            from getpass import getpass
            password = getpass("Password:")
            # Let's convert to hashes
            lmhash = compute_lmhash(password)
            nthash = compute_nthash(password)
        elif options.password is not None:
Esempio n. 23
0
import logging

from impacket.examples import logger
from impacket import smbserver

logger.init(True)
logging.getLogger().setLevel(logging.DEBUG)
server = smbserver.SimpleSMBServer(listenAddress="0.0.0.0", listenPort=445)
server.setSMB2Support(True)
server.addShare("test_share", "/nonexistent")
server.setSMBChallenge('')
server.start()
Esempio n. 24
0
def smb_server(lip):
    server = smbserver.SimpleSMBServer(listenAddress=lip, listenPort=445)
    server.addShare('LOLWAT', '.', '')
    server.setSMBChallenge('')
    server.setLogFile('/dev/null')
    server.start()