Repository: miketeo/pysmb Branch: dev-1.2.x Commit: 44c2ac9a3bbd Files: 254 Total size: 3.3 MB Directory structure: gitextract_0ims3cyo/ ├── .gitignore ├── .readthedocs.yaml ├── CHANGELOG ├── LICENSE ├── MANIFEST.in ├── README.md ├── README.txt ├── docs/ │ ├── doctrees/ │ │ ├── api/ │ │ │ ├── nmb_NBNSProtocol.doctree │ │ │ ├── nmb_NetBIOS.doctree │ │ │ ├── smb_SMBConnection.doctree │ │ │ ├── smb_SMBHandler.doctree │ │ │ ├── smb_SMBProtocolFactory.doctree │ │ │ ├── smb_SharedDevice.doctree │ │ │ ├── smb_SharedFile.doctree │ │ │ ├── smb_exceptions.doctree │ │ │ └── smb_security_descriptors.doctree │ │ ├── environment.pickle │ │ ├── extending.doctree │ │ ├── index.doctree │ │ └── upgrading.doctree │ └── html/ │ ├── .buildinfo │ ├── _modules/ │ │ ├── index.html │ │ ├── nmb/ │ │ │ ├── NetBIOS.html │ │ │ └── NetBIOSProtocol.html │ │ └── smb/ │ │ ├── SMBConnection.html │ │ ├── SMBProtocol.html │ │ ├── base.html │ │ ├── security_descriptors.html │ │ └── smb_structs.html │ ├── _sources/ │ │ ├── api/ │ │ │ ├── nmb_NBNSProtocol.rst.txt │ │ │ ├── nmb_NBNSProtocol.txt │ │ │ ├── nmb_NetBIOS.rst.txt │ │ │ ├── nmb_NetBIOS.txt │ │ │ ├── smb_SMBConnection.rst.txt │ │ │ ├── smb_SMBConnection.txt │ │ │ ├── smb_SMBHandler.rst.txt │ │ │ ├── smb_SMBHandler.txt │ │ │ ├── smb_SMBProtocolFactory.rst.txt │ │ │ ├── smb_SMBProtocolFactory.txt │ │ │ ├── smb_SharedDevice.rst.txt │ │ │ ├── smb_SharedDevice.txt │ │ │ ├── smb_SharedFile.rst.txt │ │ │ ├── smb_SharedFile.txt │ │ │ ├── smb_exceptions.rst.txt │ │ │ ├── smb_exceptions.txt │ │ │ ├── smb_security_descriptors.rst.txt │ │ │ └── smb_security_descriptors.txt │ │ ├── extending.rst.txt │ │ ├── extending.txt │ │ ├── index.rst.txt │ │ ├── index.txt │ │ ├── upgrading.rst.txt │ │ └── upgrading.txt │ ├── _static/ │ │ ├── _sphinx_javascript_frameworks_compat.js │ │ ├── basic.css │ │ ├── doctools.js │ │ ├── documentation_options.js │ │ ├── jquery-3.5.1.js │ │ ├── jquery-3.6.0.js │ │ ├── jquery.js │ │ ├── language_data.js │ │ ├── pygments.css │ │ ├── searchtools.js │ │ ├── sphinx_highlight.js │ │ ├── sphinxdoc.css │ │ ├── underscore-1.13.1.js │ │ ├── underscore-1.3.1.js │ │ ├── underscore.js │ │ └── websupport.js │ ├── api/ │ │ ├── nmb_NBNSProtocol.html │ │ ├── nmb_NetBIOS.html │ │ ├── smb_SMBConnection.html │ │ ├── smb_SMBHandler.html │ │ ├── smb_SMBProtocolFactory.html │ │ ├── smb_SharedDevice.html │ │ ├── smb_SharedFile.html │ │ ├── smb_exceptions.html │ │ └── smb_security_descriptors.html │ ├── extending.html │ ├── genindex.html │ ├── index.html │ ├── objects.inv │ ├── py-modindex.html │ ├── search.html │ ├── searchindex.js │ └── upgrading.html ├── python2/ │ ├── nmb/ │ │ ├── NetBIOS.py │ │ ├── NetBIOSProtocol.py │ │ ├── __init__.py │ │ ├── base.py │ │ ├── nmb_constants.py │ │ ├── nmb_structs.py │ │ └── utils.py │ ├── smb/ │ │ ├── SMBConnection.py │ │ ├── SMBHandler.py │ │ ├── SMBProtocol.py │ │ ├── __init__.py │ │ ├── base.py │ │ ├── ntlm.py │ │ ├── security_descriptors.py │ │ ├── securityblob.py │ │ ├── smb2_constants.py │ │ ├── smb2_structs.py │ │ ├── smb_constants.py │ │ ├── smb_structs.py │ │ └── utils/ │ │ ├── README.txt │ │ ├── U32.py │ │ ├── __init__.py │ │ ├── md4.py │ │ ├── pyDes.py │ │ ├── rc4.py │ │ └── sha256.py │ └── tests/ │ ├── DirectSMBConnectionTests/ │ │ ├── __init__.py │ │ ├── test_SMBHandler.py │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_echo.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_storefile.py │ │ └── util.py │ ├── DirectSMBTwistedTests/ │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_echo.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_storefile.py │ │ └── util.py │ ├── NetBIOSTests/ │ │ ├── __init__.py │ │ └── test_queryname.py │ ├── NetBIOSTwistedTests/ │ │ ├── __init__.py │ │ └── test_queryname.py │ ├── README.md │ ├── SMBConnectionTests/ │ │ ├── __init__.py │ │ ├── test_SMBHandler.py │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_deletepattern.py │ │ ├── test_echo.py │ │ ├── test_getattributes.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_security.py │ │ ├── test_storefile.py │ │ ├── test_with_context.py │ │ └── util.py │ ├── SMBTwistedTests/ │ │ ├── __init__.py │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_echo.py │ │ ├── test_getattributes.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_storefile.py │ │ └── util.py │ ├── __init__.py │ ├── connection.ini │ ├── test_ntlm.py │ ├── test_security_descriptors.py │ └── test_securityblob.py ├── python3/ │ ├── nmb/ │ │ ├── NetBIOS.py │ │ ├── NetBIOSProtocol.py │ │ ├── __init__.py │ │ ├── base.py │ │ ├── nmb_constants.py │ │ ├── nmb_structs.py │ │ └── utils.py │ ├── smb/ │ │ ├── SMBConnection.py │ │ ├── SMBHandler.py │ │ ├── SMBProtocol.py │ │ ├── __init__.py │ │ ├── base.py │ │ ├── ntlm.py │ │ ├── security_descriptors.py │ │ ├── securityblob.py │ │ ├── smb2_constants.py │ │ ├── smb2_structs.py │ │ ├── smb_constants.py │ │ ├── smb_structs.py │ │ ├── strategy.py │ │ └── utils/ │ │ ├── U32.py │ │ ├── __init__.py │ │ ├── md4.py │ │ ├── pyDes.py │ │ ├── rc4.py │ │ └── sha256.py │ └── tests/ │ ├── DirectSMBConnectionTests/ │ │ ├── __init__.py │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_echo.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_storefile.py │ │ ├── test_tqdm.py │ │ └── util.py │ ├── NetBIOSTests/ │ │ ├── __init__.py │ │ └── test_queryname.py │ ├── README.md │ ├── SMBConnectionTests/ │ │ ├── __init__.py │ │ ├── test_SMBHandler.py │ │ ├── test_auth.py │ │ ├── test_createdeletedirectory.py │ │ ├── test_deletepattern.py │ │ ├── test_echo.py │ │ ├── test_getattributes.py │ │ ├── test_listpath.py │ │ ├── test_listshares.py │ │ ├── test_listsnapshots.py │ │ ├── test_messages_in_exception.py │ │ ├── test_rename.py │ │ ├── test_retrievefile.py │ │ ├── test_storefile.py │ │ ├── test_with_context.py │ │ └── util.py │ ├── __init__.py │ ├── connection.ini │ ├── test_md4.py │ ├── test_ntlm.py │ ├── test_security_descriptors.py │ └── test_securityblob.py ├── setup.py ├── sphinx/ │ ├── Makefile │ ├── make.bat │ ├── requirements.txt │ └── source/ │ ├── api/ │ │ ├── nmb_NBNSProtocol.rst │ │ ├── nmb_NetBIOS.rst │ │ ├── smb_SMBConnection.rst │ │ ├── smb_SMBHandler.rst │ │ ├── smb_SMBProtocolFactory.rst │ │ ├── smb_SharedDevice.rst │ │ ├── smb_SharedFile.rst │ │ ├── smb_exceptions.rst │ │ └── smb_security_descriptors.rst │ ├── conf.py │ ├── extending.rst │ ├── index.rst │ └── upgrading.rst └── utils/ ├── ScanNetworkForSMB.py └── recursiveDelete.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Ignore per-file backup from text editors *~ # For virtualenvs in development /venv2 /venv3 # # From https://github.com/github/gitignore/blob/master/Python.gitignore # # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ ### End of https://github.com/github/gitignore/blob/master/Python.gitignore ================================================ FILE: .readthedocs.yaml ================================================ # Read the Docs configuration file for Sphinx projects # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Set the OS, Python version and other tools you might need build: os: ubuntu-22.04 tools: python: "3.12" # You can also specify other tool versions: # nodejs: "20" # rust: "1.70" # golang: "1.20" # Build documentation in the "docs/" directory with Sphinx sphinx: configuration: sphinx/source/conf.py # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs # builder: "dirhtml" # Fail on all warnings to avoid broken references # fail_on_warning: true # Optionally build your docs in additional formats such as PDF and ePub # formats: # - pdf # - epub # Optional but recommended, declare the Python requirements required # to build your documentation # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html python: install: - requirements: sphinx/requirements.txt ================================================ FILE: CHANGELOG ================================================ pysmb-1.2.13, 20 Sep 2025 ========================= - Fix type hinting issues on Python versions prior to 3.9. (#230) pysmb-1.2.12, 19 Sep 2025 ========================= - Add support for NetBIOS packet polling on Linux (#229) pysmb-1.2.11, 25 Mar 2025 ========================= - Fix out-of-memory issues during large file operations (due to accumulation of messages in message_history). pysmb-1.2.10, 25 Sep 2024 ========================= - Fix a bug where the OperationFailure exceptions do not contain the error messages that were thrown when the exception occurred (#212) - Update test cases to replace SafeConfigParser with ConfigParser (#219) - Allow callers to override default tqdm kwargs (#222) pysmb-1.2.9, 25 Dec 2022 ======================== - Add support for tqdm progress display (#205) - Fix bug where timeout parameter was not passed to socket.createConnection() (#202) pysmb-1.2.8, 12 Jun 2022 ======================== - Fix issue with listPath based on recommendation in #195 - Fix embedded MD4 algorithm - Add SMB UTF-16 surrogate exception workaround policy pysmb-1.2.7, 30 May 2021 ======================== - Fix compatibility issues on file retrievals with Likewise servers (#177) - Improve SMBConnection's connect() method to remove the need to provide sock_family parameter for IPv6 addresses in Python 3.x (#180) pysmb-1.2.6, 9 Dec 2020 ======================= - Fix bug in SMB1 store file implmentation which generates SMB_COM_WRITE_ANDX packets larger than the allowed max buffer size (#175) pysmb-1.2.5, 18 Oct 2020 ======================= - Fix bug in filename encoding which leads to failure for file retrieval and upload operations (#170 #171). - Improve resetFileAttributes() method in SMBConnection class to allow the new attribute to be specified in the reset operation (#172). pysmb-1.2.4, 6 Oct 2020 ======================= - Remove dependency on pycrypto as it is no longer under active maintenance pysmb-1.2.3, 6 Oct 2020 ======================= - Fix bug in session key generation during session negotiation (#166) - Fix bug in SMB message signing which leads to operation failures with Samba services. pysmb-1.2.2, 5 Sep 2020 ======================= - Improve SMB URL handlers to support specifying server's machine name and IP address. (#162) - Improvements to documentation on SMB URLs (#160) pysmb-1.2.1, 17 May 2020 ======================== - Fix bug in deleteFiles() method which can fail for certain search patterns. pysmb-1.2.0, 17 May 2020 ========================= - Add new parameter, delete_matching_folders, to deleteFiles() method to support deletion of child folders that match the search pattern. pysmb-1.1.29, 16 May 2020 ========================= - Fix unhandled exception for short NBNS queries #149 - Fix wildcard file deletion with servers on SMB2 protocol #33 pysmb-1.1.28, 23 Nov 2019 ======================== - SharedFile instances returned from the listPath() method now has a new file_id attribute which represents the file reference number given by the SMB server. pysmb-1.1.27, 9 Jan 2019 ======================== - Remove support for SMB-2.1 dialect as it seems to have issues with Windows 2008 R2 pysmb-1.1.26, 5 Jan 2019 ======================== - Prevents OperationError from being raised when listPath() operation does not return any matching file results. - SMBConnection is now a context manager #122. pysmb-1.1.25, 28 July 2018 ======================== - Fix buggy support for search parameter in listPath() method. Add SMB_FILE_ATTRIBUTE_INCL_NORMAL bit constant to include 'normal' files with other file types in the returned result. From now on, pysmb defines a 'normal' file as a file entry that is not read-only, not hidden, not system, not archive and not a directory; it ignores other attributes like compression, indexed, sparse, temporary and encryption. listPath() method will now include 'normal' files using the default search parameter. - Add isNormal property to SharedFile class to support test if the file is a 'normal' file (according to pysmb definition of 'normal' file). pysmb-1.1.24, 19 July 2018 ======================== - Improve listPath implementation for SMB1 - Support for STATUS_PENDING responses across all SMB2 operations. pysmb-1.1.23, 5 May 2018 ======================== - Fix bug in listShares() method which fails when the remote server has many shares. - Improve echo() method to test and fail if the provided data to echo is not a bytes object. - Fix bug in listPath() method where the path to query is not properly terminated. pysmb-1.1.22, 17 Sep 2017 ======================== - Fix bug in getAttributes() method which should return only the filename instead of the entire path for the filename property for the return result. pysmb-1.1.21, 9 Sep 2017 ======================== - Fix bug where timestamp values for SMB1 getAttributes() response are not converted properly from FILETIME to epoch time values. pysmb-1.1.20, 13 Aug 2017 ========================= - Add getSecurity() method to support security descriptors query via SMB2 - Improve retrieveFile() and retrieveFileFromOffset() methods to allow file retrievals over SMB2 even when the file is being locked on the server. - Silently discards NMB SESSION_KEEPALIVE packets instead of raising warnings. - SMB sessionID will be sent in ECHO requests to conform to SMB2 specs. - Fix type errors for MD4 functions in python3. pysmb-1.1.19, 13 Nov 2016 ========================= - Ignore STATUS_PENDING during delete and file store operations pysmb-1.1.18, 9 Apr 2016 ======================== - Rollback fixes to NTLMv2 response algorithm in pysmb 1.1.17. The fixes fail to work with some servers. - Add missing errno imports in SMBConnection.py - Fix UnboundLocalError raised when using type() in SMBConnection.py pysmb-1.1.17, 11 Nov 2015 ========================= - Fix crashes in directory listing with keyerror 'support_dfs' - Fix bugs in NTLMv2 response algorithm. - Fix bugs where client domain is not included as part of the session negotiation. pysmb-1.1.16, 10 May 2015 ========================= - Fix typo errors in authentication error messages - Improve share listings on SMB2 protocol by ignoring interim STATUS_PENDING responses. pysmb-1.1.15, 15 Feb 2015 ========================= - Add new parameter to SMBConnection's storeFileFromOffset method to determine whether the remote file is to be truncated before writing. pysmb-1.1.14, 1 Feb 2015 ======================== - Add support for DFS shares in listPath() - Bug fix for python3's _listPath_SMB2 implementation pysmb-1.1.13, 18 Oct 2014 ========================= - Add missing methods and improve compatibility with python3 - Fix bug in SMB2 rename implementation which fails to rename directory pysmb-1.1.12, 21 Sep 2014 ========================= - Fix syntax error for python3 NBNSProtocol implementation - Fix bug in SMB1 implementation which results in access denied errors with Samba 3.0 pysmb-1.1.11, 13 Sep 2014 ========================= - Add support for unicode characters in domain, username and password. - Add storeFileFromOffset method to SMB API - Fix bug in getAttributes implementation for SMB1 - Fix bug for NMB which uses broadcast flag for unicast queries - Update the Tree Connect Andx request implementation to MS-SMB 2.2.4.7.1 extensions pysmb-1.1.10, 29 Jun 2014 ========================= - Add getAttributes() method to SMBConnection and SMBProtocolFactory class - Add isReadOnly property to SharedFile class pysmb-1.1.9, 1 Jun 2014 ======================= - Add support for domains in smb:// URLs - Fix a bug which fails to test for the correct GSS security provider OID values pysmb-1.1.8, 21 Dec 2013 ======================== - Fix a bug in storeFile() method when the destination file is not overwritten if it exists in SMB1 communication - Fix a SMB1 authentication problem when extended negotation is not carried out because the remote server has specified its support for extended security in the payload, instead of in the message flags2. pysmb-1.1.7, 27 Sep 2013 ======================== - Improve listShares() function which can fail with the listing response is separated into multiple SMB packets for large number of shares. - Fix bug in python3 implementation where session connection can fail when remote server supports message signing. pysmb-1.1.6, 16 Aug 2013 ======================== - Fix bug where the status of the SMB_COM_NEGOTIATE reply is not checked for error before allowing further processing. pysmb-1.1.5, 19 June 2013 ========================= - Adds support for Direct hosting of SMB over TCP/IP (TCP port: 445) pysmb-1.1.4, 31 May 2013 ======================== - Improve query performance for query IP addresses for NetBIOS names in NetBIOSProtocol.py - Fix bugs in SMBConnection when sending large data packets can result in AssertionError. pysmb-1.1.3, 18 Mar 2013 ======================== - Fix bug which results in endless loop in SMBConnection when remote CIFS server closes the connection. pysmb-1.1.2, 28 Sep 2012 ======================== - Improve queryIPForName() in nmb.NetBIOS and nmb.NBNSProtocol class to return only server machine name and ignore workgroup names. pysmb-1.1.1, 9 June 2012 ======================== - Adds support for Python3. Noted that the Python3 SMB/NMB protocol implementations for Twisted are not well-tested as Twisted (as of v12.1) is not Python3 ready yet. - Adds support for retrieving list of shadow copies (also known as "previous versions" in Windows). Note that not all Windows editions support shadow copies. pysmb-1.1.0, 1 June 2012 ======================== - Adds SMB2 protocol implementation with signing for outgoing SMB2 messages. pysmb will utilize SMB2 protocol with servers that support SMB2 (eg. Windows Vista, Windows 7 and Samba 3). If the remote server does not support SMB2, pysmb will fall back automatically to using SMB1 protocol. pysmb-1.0.5, 7 May 2012 ======================= - Add supports for SMB message signing. pysmb will sign all SMB messages from the CIFS client to the server, but it does not verify the signatures of the SMB messages from the server. pysmb-1.0.4, 1 May 2012 ======================= - Adds support for "smb://" URL in urllib2 python packages to retrieve or upload files from/to remote CIFS servers. - Improve documentation pysmb-1.0.3, 28 April 2012 =========================== - Fix a crash in SMB._storFile() method which occurs when the remote CIFS server utilizes a max raw size larger than 65535 bytes. The bug was discovered with Windows 7 Pro SP1. - Fix a bug in SMB._listPath() method where the files/folders time information are not properly converted to Epoch time. - Add NBNSProtocol.queryIPForName() and NetBIOS.queryIPForName() methods to query for a machine's NetBIOS name at the given IP address. - Add SMBProtocol.retrieveFileFromOffset() and SMBConnection.retrieveFileFromOffset() methods for a finer control of file retrieval operation with read offset and write limits. pysmb-1.0.2, 31 March 2012 ========================== - Fix a bug in SMB._handleSessionChallenge() method in base.py where the domain attribute was not used to generate the corresponding NTLM authentication packets, resulting in the default WORKGROUP domain for used for all subsequent authentications. pysmb-1.0.1, 25 Jan 2012 ======================== - Fixes a bug in listPath() method which causes directory listing for sub-directories to return an empty list. - Fixes an incorrect implementation of the TRANS2_FIND_FIRST2 and TRANS2_FIND_NEXT2 request/response handling which causes directory listing to crash when the remote directory contains a certain number of entries. pysmb-1.0.0, 25 Dec 2011 ======================== - Completely rewrites pysmb. API is not compatible with previous pysmb-0.x.x - Supports NTLMv1 and NTLMv2 authentication - Adds in NMB/SMB protocol implementation for use with Twisted framework - Tested with Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x - Requires Python 2.4.4 or later, and pyasn1. Not tested with Python3 pysmb-0.4.5, 22 Jun 2009 ======================== - Prevents pysmb from failing when there are too many files/folders to be returned in a single SMB TRANS2 call. pysmb will "resume" requesting for more files/folders information in subsequent SMB TRANS2 requests. pysmb-0.4.4, 12 Jan 2004 ======================== - Add in support for AMK's Python Cryptography Toolkit which will be used for DES password hashing. If AMK's pycrypto is found, it will be used instead of mxCrypto. pysmb-0.4.3, 22 Feb 2003 ======================== - Fix a bug which fails to close the socket in nmb.py on socket exception - Fix a bug which fails to close the NetBIOSSession in smb.py if the session has not been properly established yet. pysmb-0.4.2, 03 Aug 2002 ======================== - Add new methods to SharedFile instances, get_mtime_epoch, get_atime_epoch and get_ctime_epoch. These methods will return the mtime, atime and ctime in epoch time rather than SMB time. - Remove debugging printout in smb.py which has been released accidentally with the last release. - Fix a bug in smbcp which causes to local to remote copy to fail pysmb-0.4.1, 22 Jun 2002 ======================== - Fix a bug in smb.py which does not return the correct file size for files with their archive bits turned off. This results in these files not being retrieved or sent properly. - Fix some typo error in the documentations pysmb-0.4.0, 17 Apr 2002 ======================== - Use NT LM0.12 dialect. - New smb.SMBMachine class - Add SMB.get_server_domain(), smb.get_server_os(), SMB.get_server_lanman() pysmb-0.3.1, 12 Nov 2001 ======================== - Fix a problem with some Windows server where an UID is required when server is in share mode. Now, pysmb calls login() with empty authentication information when server is in share mode. - Add TYPE_DOMAIN_MASTER constant and description to nmb.py. pysmb-0.3.0, 10 Nov 2001 ======================== - Add support for services in share mode. Minor changes to smb.SMB class API. - Fix a bug in smb.py's __raw_retr_file which has failed to initialize the max_buf_size prior to usage. - Fix a bug in smblistshare which fails to print the correct NMB error message - Modify smb.py not throw AttributeError in the destructor when there is an error while creating a session in the constructor pysmb-0.2.0, 04 Oct 2001 ======================== - Add support for encrypted authentication using DES - Fix a bug(?) which treats all services and filenames as case-sensitive pysmb-0.1.3, 03 Sep 2001 ======================== - Fix a bug in smblistshare and smbdu which fails to catch the nmb.NetBIOSError raised when session setup fails. - Fix a bug in smb.SMB that arises from the change in nmb.NetBIOSSession which sends the session port number as the remote host type. pysmb-0.1.2, 01 Sep 2001 ======================== - Fix a bug in nmb.NetBIOSSession which specifies a TYPE_WORKSTATION for remote host instead of TYPE_SERVER. - Minor change to nmb.NetBIOSSession constructor API. - Fix a bug in smbdu which raises OverflowError when printing long file size values. - Fix a bug in smbcp which does not handle the destination path correctly when the source file is copied to a different filename. pysmb-0.1.1, 25 Aug 2001 ======================== - Change nmb's NetBIOS and NetBIOSSession class such that they raise a NetBIOSError with a tuple of ( err_msg, err_class, err_code ) - Add a function strerror() in both smb and nmb to return human readable messages for error codes. - Fix a bug in smbcp which fails to print an error message and terminate when the remote source path is not found. - Add in another utility, smblistshare. pysmb-0.1.0, 20 Aug 2001 ======================== - First public release ================================================ FILE: LICENSE ================================================ Copyright (C) 2001-2025 Michael Teo This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice cannot be removed or altered from any source distribution. ================================================ FILE: MANIFEST.in ================================================ include LICENSE include CHANGELOG recursive-include python2 * recursive-exclude python2 *.pyc recursive-exclude python2 *~ recursive-include python3 * recursive-exclude python3 *.pyc recursive-exclude python3 *~ recursive-include sphinx * recursive-include docs * recursive-exclude docs *.zip ================================================ FILE: README.md ================================================ pysmb ===== pysmb is an experimental SMB/CIFS library written in Python. It implements the client-side SMB/CIFS protocol (SMB1 and SMB2) which allows your Python application to access and transfer files to/from SMB/CIFS shared folders like your Windows file sharing and Samba folders. * Primary Project Website: https://miketeo.net/blog/projects/pysmb * Documentation: http://pysmb.readthedocs.io/ * Issue Tracker: Please use the [issue tracker on github](https://github.com/miketeo/pysmb/issues). ================================================ FILE: README.txt ================================================ pysmb is an experimental SMB/CIFS library written in Python. It implements the client-side SMB/CIFS protocol (SMB1 and SMB2) which allows your Python application to access and transfer files to/from SMB/CIFS shared folders like your Windows file sharing and Samba folders. ================================================ FILE: docs/html/.buildinfo ================================================ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. config: 02747f6883e56a04531aef4d47846d2a tags: 645f666f9bcd5a90fca523b33c5a78b7 ================================================ FILE: docs/html/_modules/index.html ================================================ Overview: module code — pysmb 1.2.13 documentation

All modules for which code is available

================================================ FILE: docs/html/_modules/nmb/NetBIOS.html ================================================ nmb.NetBIOS — pysmb 1.2.12 documentation

Source code for nmb.NetBIOS


import os, logging, random, socket, time, select
from .base import NBNS, NotConnectedError
from .nmb_constants import TYPE_CLIENT, TYPE_SERVER, TYPE_WORKSTATION

[docs] class NetBIOS(NBNS): log = logging.getLogger('NMB.NetBIOS')
[docs] def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.broadcast: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) if listen_port: self.sock.bind(( '', listen_port ))
[docs] def close(self): """ Close the underlying and free resources. The NetBIOS instance should not be used to perform any operations after this method returns. :return: None """ self.sock.close() self.sock = None
def write(self, data, ip, port): assert self.sock, 'Socket is already closed' self.sock.sendto(data, ( ip, port ))
[docs] def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '<broadcast>' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) return self._pollForNetBIOSPacket(trn_id, timeout)
[docs] def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of string containing the names of the machine at *ip*. On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNetNameQuery(trn_id, False) self.write(data, ip, port) ret = self._pollForQueryPacket(trn_id, timeout) if ret: return list(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) else: return None
# # Protected Methods # def _pollForNetBIOSPacket(self, wait_trn_id, timeout): end_time = time.time() - timeout while True: try: _timeout = time.time()-end_time if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodePacket(data) if trn_id == wait_trn_id: return ret except select.error as ex: if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex # # Contributed by Jason Anderson # def _pollForQueryPacket(self, wait_trn_id, timeout): end_time = time.time() - timeout while True: try: _timeout = time.time()-end_time if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodeIPQueryPacket(data) if trn_id == wait_trn_id: return ret except select.error as ex: if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex
================================================ FILE: docs/html/_modules/nmb/NetBIOSProtocol.html ================================================ nmb.NetBIOSProtocol — pysmb 1.2.7 documentation

Source code for nmb.NetBIOSProtocol


import os, logging, random, socket, time
from twisted.internet import reactor, defer
from twisted.internet.protocol import DatagramProtocol
from .base import NBNS

[docs]class NetBIOSTimeout(Exception): """Raised in NBNSProtocol via Deferred.errback method when queryName method has timeout waiting for reply""" pass
[docs]class NBNSProtocol(DatagramProtocol, NBNS): log = logging.getLogger('NMB.NBNSProtocol')
[docs] def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NBNSProtocol instance. This automatically calls reactor.listenUDP method to start listening for incoming packets, so you **must not** call the listenUDP method again. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.pending_trns = { } # TRN ID -> ( expiry_time, name, Deferred instance ) self.transport = reactor.listenUDP(listen_port, self) if self.broadcast: self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) reactor.callLater(1, self.cleanupPendingTrns)
[docs] def datagramReceived(self, data, from_info): host, port = from_info trn_id, ret = self.decodePacket(data) # pending transaction exists for trn_id - handle it and remove from queue if trn_id in self.pending_trns: _, ip, d = self.pending_trns.pop(trn_id) if ip is NAME_QUERY: # decode as query packet trn_id, ret = self.decodeIPQueryPacket(data) d.callback(ret)
def write(self, data, ip, port): # We don't use the transport.write method directly as it keeps raising DeprecationWarning for ip='<broadcast>' self.transport.getHandle().sendto(data, ( ip, port ))
[docs] def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the returned Deferred instance will be called with a NetBIOSTimeout exception. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '<broadcast>' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) d = defer.Deferred() self.pending_trns[trn_id] = ( time.time()+timeout, name, d ) return d
[docs] def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of names of the machine at *ip*. On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNetNameQuery(trn_id) self.write(data, ip, port) d = defer.Deferred() d2 = defer.Deferred() d2.addErrback(d.errback) def stripCode(ret): if ret is not None: # got valid response. Somehow the callback is also called when there is an error. d.callback(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) d2.addCallback(stripCode) self.pending_trns[trn_id] = ( time.time()+timeout, NAME_QUERY, d2 ) return d
[docs] def stopProtocol(self): DatagramProtocol.stopProtocol(self)
def cleanupPendingTrns(self): now = time.time() # reply should have been received in the past # info is tuple of ( expiry_time, name, d ) expired = filter(lambda trn_id, info: info[0] < now, self.pending_trns.iteritems()) # remove expired items from dict + call errback def expire_item(item): trn_id, (expiry_time, name, d) = item del self.pending_trns[trn_id] try: d.errback(NetBIOSTimeout(name)) except: pass map(expire_item, expired) if self.transport: reactor.callLater(1, self.cleanupPendingTrns)
================================================ FILE: docs/html/_modules/smb/SMBConnection.html ================================================ smb.SMBConnection — pysmb 1.2.9 documentation

Source code for smb.SMBConnection


import os, logging, select, socket, types, struct, errno

from tqdm import tqdm
from .smb_constants import *
from .smb_structs import *
from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout


[docs]class SMBConnection(SMB): log = logging.getLogger('SMB.SMBConnection') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2
[docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. The default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ SMB.__init__(self, username, password, my_name, remote_name, domain, use_ntlm_v2, sign_options, is_direct_tcp) self.sock = None self.auth_result = None self.is_busy = False self.is_direct_tcp = is_direct_tcp
# # SMB (and its superclass) Methods # def onAuthOK(self): self.auth_result = True def onAuthFailed(self): self.auth_result = False def write(self, data): assert self.sock data_len = len(data) total_sent = 0 while total_sent < data_len: sent = self.sock.send(data[total_sent:]) if sent == 0: raise NotConnectedError('Server disconnected') total_sent = total_sent + sent # # Support for "with" context # def __enter__(self): return self def __exit__(self, *args): self.close() # # Misc Properties # @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.is_using_smb2 # # Public Methods #
[docs] def connect(self, ip, port = 139, sock_family = None, timeout = 60): """ Establish the SMB connection to the remote SMB/CIFS server. You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication. :param port: Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445. :param sock_family: In Python 3.x, use *None* as we can infer the socket family from the provided *ip*. In Python 2.x, it must be either *socket.AF_INET* or *socket.AF_INET6*. :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise. """ if self.sock: self.sock.close() self.auth_result = None if sock_family: self.sock = socket.socket(sock_family) self.sock.settimeout(timeout) self.sock.connect(( ip, port )) else: self.sock = socket.create_connection(( ip, port )) self.is_busy = True try: if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() while self.auth_result is None: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return self.auth_result
[docs] def close(self): """ Terminate the SMB connection (if it has been started) and release any sources held by the underlying socket. """ if self.sock: self.sock.close() self.sock = None
[docs] def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :return: A list of :doc:`smb.base.SharedDevice<smb_SharedDevice>` instances describing the shared resource """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listShares(cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results
[docs] def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile<smb_SharedFile>` instances. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listPath(service_name, path, cb, eb, search = search, pattern = pattern, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results
[docs] def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listSnapshots(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results
[docs] def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. :return: A :doc:`smb.base.SharedFile<smb_SharedFile>` instance containing the attributes of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0]
[docs] def getSecurity(self, service_name, path, timeout = 30): """ Retrieve the security descriptor of the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getSecurity(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0]
[docs] def retrieveFile(self, service_name, path, file_obj, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you wish to specify the offset to read from the remote *path* and/or the number of bytes to write to the *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout, show_progress = show_progress, tqdm_kwargs = tqdm_kwargs)
[docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* up to *max_length* number of bytes. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the method returns immediately after the file is opened successfully for reading. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1:]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._retrieveFileFromOffset(service_name, path, file_obj, cb, eb, offset, max_length, timeout = timeout, show_progress=show_progress, tqdm_kwargs=tqdm_kwargs) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0]
[docs] def storeFile(self, service_name, path, file_obj, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Store the contents of the *file_obj* at *path* on the *service_name*. If the file already exists on the remote server, it will be truncated and overwritten. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure<smb_exceptions>` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: Number of bytes uploaded """ return self.storeFileFromOffset(service_name, path, file_obj, 0, True, timeout, show_progress = show_progress, tqdm_kwargs = tqdm_kwargs)
[docs] def storeFileFromOffset(self, service_name, path, file_obj, offset = 0, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Store the contents of the *file_obj* at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure<smb_exceptions>` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. :param offset: Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0. :param truncate: Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: the file position where the next byte will be written. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._storeFileFromOffset(service_name, path, file_obj, cb, eb, offset, truncate = truncate, timeout = timeout, show_progress=show_progress, tqdm_kwargs=tqdm_kwargs) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0]
[docs] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False
[docs] def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) Note: this function is currently only implemented for SMB2! :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False
[docs] def createDirectory(self, service_name, path, timeout = 30): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._createDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False
[docs] def deleteDirectory(self, service_name, path, timeout = 30): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False
[docs] def rename(self, service_name, old_path, new_path, timeout = 30): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._rename(service_name, old_path, new_path, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False
[docs] def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._echo(data, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0]
# # Protected Methods # def _pollForNetBIOSPacket(self, timeout): expiry_time = time.time() + timeout read_len = 4 data = b'' while read_len > 0: try: if expiry_time < time.time(): raise SMBTimeout ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], timeout) if not ready: raise SMBTimeout d = self.sock.recv(read_len) if len(d) == 0: raise NotConnectedError data = data + d read_len -= len(d) except select.error as ex: if isinstance(ex, tuple): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex type, flags, length = struct.unpack('>BBH', data) if flags & 0x01: length = length | 0x10000 read_len = length while read_len > 0: try: if expiry_time < time.time(): raise SMBTimeout ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], timeout) if not ready: raise SMBTimeout d = self.sock.recv(read_len) if len(d) == 0: raise NotConnectedError data = data + d read_len -= len(d) except select.error as ex: if isinstance(ex, tuple): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex self.feedData(data)
================================================ FILE: docs/html/_modules/smb/SMBProtocol.html ================================================ smb.SMBProtocol — pysmb 1.2.7 documentation

Source code for smb.SMBProtocol


import os, logging, time
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientFactory, Protocol
from .smb_constants import *
from .smb_structs import *
from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout


__all__ = [ 'SMBProtocolFactory', 'NotConnectedError', 'NotReadyError' ]


class SMBProtocol(Protocol, SMB):

    log = logging.getLogger('SMB.SMBProtocol')

    #
    # Protocol Methods
    #

    def connectionMade(self):
        self.factory.instance = self
        if not self.is_direct_tcp:
            self.requestNMBSession()
        else:
            self.onNMBSessionOK()


    def connectionLost(self, reason):
        if self.factory.instance == self:
            self.instance = None

    def dataReceived(self, data):
        self.feedData(data)

    #
    # SMB (and its superclass) Methods
    #

    def write(self, data):
        self.transport.write(data)

    def onAuthOK(self):
        if self.factory.instance == self:
            self.factory.onAuthOK()
            reactor.callLater(1, self._cleanupPendingRequests)

    def onAuthFailed(self):
        if self.factory.instance == self:
            self.factory.onAuthFailed()

    def onNMBSessionFailed(self):
        self.log.error('Cannot establish NetBIOS session. You might have provided a wrong remote_name')

    #
    # Protected Methods
    #

    def _cleanupPendingRequests(self):
        if self.factory.instance == self:
            now = time.time()
            to_remove = []
            for mid, r in self.pending_requests.items():
                if r.expiry_time < now:
                    try:
                        r.errback(SMBTimeout())
                    except Exception: pass
                    to_remove.append(mid)

            for mid in to_remove:
                del self.pending_requests[mid]

            reactor.callLater(1, self._cleanupPendingRequests)


[docs]class SMBProtocolFactory(ClientFactory): protocol = SMBProtocol log = logging.getLogger('SMB.SMBFactory') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2
[docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBProtocolFactory instance. You will pass this instance to *reactor.connectTCP()* which will then instantiate the TCP connection to the remote SMB/CIFS server. Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. File operations can only be proceeded after the connection has been authenticated successfully. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ self.username = username self.password = password self.my_name = my_name self.remote_name = remote_name self.domain = domain self.use_ntlm_v2 = use_ntlm_v2 self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.instance = None #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly.
# # Public Property # @property def isReady(self): """A convenient property to return True if the underlying SMB connection has connected to remote server, has successfully authenticated itself and is ready for file operations.""" return bool(self.instance and self.instance.has_authenticated) @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.instance and self.instance.is_using_smb2 # # Public Methods for Callbacks #
[docs] def onAuthOK(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. File operations can proceed when this method has been called. """ pass
[docs] def onAuthFailed(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. If you want to retry authenticating from this method, 1. Disconnect the underlying SMB connection (call ``self.instance.transport.loseConnection()``) 2. Create a new SMBProtocolFactory subclass instance with different user credientials or different NTLM algorithm flag. 3. Call ``reactor.connectTCP`` with the new instance to re-establish the SMB connection """ pass
# # Public Methods #
[docs] def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedDevice<smb_SharedDevice>` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listShares(d.callback, d.errback, timeout) return d
[docs] def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile<smb_SharedFile>` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listPath(service_name, path, d.callback, d.errback, search = search, pattern = pattern, timeout = timeout) return d
[docs] def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (a.k.a. shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listSnapshots(service_name, path, d.callback, d.errback, timeout = timeout) return d
[docs] def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a :doc:`smb.base.SharedFile<smb_SharedFile>` instance containing the attributes of the file. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._getAttributes(service_name, path, d.callback, d.errback, timeout = timeout) return d
[docs] def retrieveFile(self, service_name, path, file_obj, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you need to specify the offset to read from the remote *path* and/or the maximum number of bytes to write to the *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout)
[docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the *Deferred* callback is invoked immediately after the file is opened successfully for reading. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._retrieveFileFromOffset(service_name, path, file_obj, d.callback, d.errback, offset, max_length, timeout = timeout) return d
[docs] def storeFile(self, service_name, path, file_obj, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. The meaning of the *timeout* parameter will be different from other file operation methods. As the uploaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of messages (usually about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and acknowledged by the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *file_obj*, number of bytes uploaded ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout) return d
[docs] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path_file_pattern* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteFiles(service_name, path_file_pattern, delete_matching_folders, d.callback, d.errback, timeout = timeout) return d
[docs] def createDirectory(self, service_name, path): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._createDirectory(service_name, path, d.callback, d.errback) return d
[docs] def deleteDirectory(self, service_name, path): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteDirectory(service_name, path, d.callback, d.errback) return d
[docs] def rename(self, service_name, old_path, new_path): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *old_path*, *new_path* ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._rename(service_name, old_path, new_path, d.callback, d.errback) return d
[docs] def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._echo(data, d.callback, d.errback, timeout) return d
[docs] def closeConnection(self): """ Disconnect from the remote SMB/CIFS server. The TCP connection will be closed at the earliest opportunity after this method returns. :return: None """ if not self.instance: raise NotConnectedError('Not connected to server') self.instance.transport.loseConnection()
# # ClientFactory methods # (Do not touch these unless you know what you are doing) #
[docs] def buildProtocol(self, addr): p = self.protocol(self.username, self.password, self.my_name, self.remote_name, self.domain, self.use_ntlm_v2, self.sign_options, self.is_direct_tcp) p.factory = self return p
================================================ FILE: docs/html/_modules/smb/base.html ================================================ smb.base — pysmb 1.2.11 documentation

Source code for smb.base


import logging, binascii, time, hmac
from datetime import datetime
from tqdm import tqdm

from .smb_constants import *
from .smb2_constants import *
from .smb_structs import *
from .smb2_structs import *
from .security_descriptors import SecurityDescriptor
from nmb.base import NMBSession
from .utils import convertFILETIMEtoEpoch
from . import ntlm, securityblob
from .strategy import DataFaultToleranceStrategy

try:
    import hashlib
    sha256 = hashlib.sha256
except ImportError:
    from .utils import sha256


[docs]class NotReadyError(Exception): """Raised when SMB connection is not ready (i.e. not authenticated or authentication failed)""" pass
[docs]class NotConnectedError(Exception): """Raised when underlying SMB connection has been disconnected or not connected yet""" pass
[docs]class SMBTimeout(Exception): """Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete.""" pass
class SMB(NMBSession): """ This class represents a "connection" to the remote SMB/CIFS server. It is not meant to be used directly in an application as it does not have any network transport implementations. For application use, please refer to - L{SMBProtocol.SMBProtocolFactory<smb.SMBProtocol>} if you are using Twisted framework In [MS-CIFS], this class will contain attributes of Client, Client.Connection and Client.Session abstract data models. References: =========== - [MS-CIFS]: 3.2.1 """ log = logging.getLogger('SMB.SMB') SIGN_NEVER = 0 SIGN_WHEN_SUPPORTED = 1 SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) self.username = username self._password = password self.domain = domain self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages self.has_negotiated = False self.has_authenticated = False self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2 self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2 self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2 self.mid = 0 self.uid = 0 self.next_signing_id = 2 #: Similar to ClientNextSendSequenceNumber as described in [MS-CIFS] 3.2.1.2 # SMB1 and SMB2 attributes # Note that the interpretations of the values may differ between SMB1 and SMB2 protocols self.capabilities = 0 self.security_mode = 0 #: Initialized from the SecurityMode field of the SMB_COM_NEGOTIATE message # SMB1 attributes # Most of the following attributes will be initialized upon receipt of SMB_COM_NEGOTIATE message from server (via self._updateServerInfo_SMB1 method) self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1 self.max_raw_size = 0 self.max_buffer_size = 0 #: Similar to MaxBufferSize as described in [MS-CIFS] 3.2.1.1 self.max_mpx_count = 0 #: Similar to MaxMpxCount as described in [MS-CIFS] 3.2.1.1 # SMB2 attributes self.max_read_size = 0 #: Similar to MaxReadSize as described in [MS-SMB2] 2.2.4 self.max_write_size = 0 #: Similar to MaxWriteSize as described in [MS-SMB2] 2.2.4 self.max_transact_size = 0 #: Similar to MaxTransactSize as described in [MS-SMB2] 2.2.4 self.session_id = 0 #: Similar to SessionID as described in [MS-SMB2] 2.2.4. This will be set in _updateState_SMB2 method # tqdm attributes for tracking progress self.pbar = None #: If not None, it means there is an active tqdm progress bar being shown self._setupSMB1Methods() self.log.info('Authentication with remote machine "%s" for user "%s" will be using NTLM %s authentication (%s extended security)', self.remote_name, self.username, (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') @property def password(self): if callable(self._password): return self._password() return self._password # # NMBSession Methods # def onNMBSessionOK(self): self._sendSMBMessage(SMBMessage(ComNegotiateRequest())) def onNMBSessionFailed(self): pass def onNMBSessionMessage(self, flags, data): while True: try: i = self.smb_message.decode(data) except SMB2ProtocolHeaderError: self.log.info('Now switching over to SMB2 protocol communication') self.is_using_smb2 = True self.mid = 0 # Must reset messageID counter, or else remote SMB2 server will disconnect self._setupSMB2Methods() self.smb_message = self._klassSMBMessage() i = self.smb_message.decode(data) next_message_offset = 0 if self.is_using_smb2: next_message_offset = self.smb_message.next_command_offset if i > 0: if not self.is_using_smb2: self.log.debug('Received SMB message "%s" (command:0x%2X flags:0x%02X flags2:0x%04X TID:%d UID:%d)', SMB_COMMAND_NAMES.get(self.smb_message.command, '<unknown>'), self.smb_message.command, self.smb_message.flags, self.smb_message.flags2, self.smb_message.tid, self.smb_message.uid) else: self.log.debug('Received SMB2 message "%s" (command:0x%04X flags:0x%04x)', SMB2_COMMAND_NAMES.get(self.smb_message.command, '<unknown>'), self.smb_message.command, self.smb_message.flags) if self._updateState(self.smb_message): # We need to create a new instance instead of calling reset() because the instance could be captured in the message history. self.smb_message = self._klassSMBMessage() if next_message_offset > 0: data = data[next_message_offset:] else: break # # Public Methods for Overriding in Subclasses # def onAuthOK(self): pass def onAuthFailed(self): pass # # Protected Methods # def _setupSMB1Methods(self): self._klassSMBMessage = SMBMessage self._updateState = self._updateState_SMB1 self._updateServerInfo = self._updateServerInfo_SMB1 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB1 self._sendSMBMessage = self._sendSMBMessage_SMB1 self._handleSessionChallenge = self._handleSessionChallenge_SMB1 self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 self._storeFile = self._storeFile_SMB1 self._storeFileFromOffset = self._storeFileFromOffset_SMB1 self._deleteFiles = self._deleteFiles_SMB1 self._resetFileAttributes = self._resetFileAttributes_SMB1 self._createDirectory = self._createDirectory_SMB1 self._deleteDirectory = self._deleteDirectory_SMB1 self._rename = self._rename_SMB1 self._echo = self._echo_SMB1 def _setupSMB2Methods(self): self._klassSMBMessage = SMB2Message self._updateState = self._updateState_SMB2 self._updateServerInfo = self._updateServerInfo_SMB2 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB2 self._sendSMBMessage = self._sendSMBMessage_SMB2 self._handleSessionChallenge = self._handleSessionChallenge_SMB2 self._listShares = self._listShares_SMB2 self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 self._getSecurity = self._getSecurity_SMB2 self._getAttributes = self._getAttributes_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 self._storeFile = self._storeFile_SMB2 self._storeFileFromOffset = self._storeFileFromOffset_SMB2 self._deleteFiles = self._deleteFiles_SMB2 self._resetFileAttributes = self._resetFileAttributes_SMB2 self._createDirectory = self._createDirectory_SMB2 self._deleteDirectory = self._deleteDirectory_SMB2 self._rename = self._rename_SMB2 self._echo = self._echo_SMB2 def _getNextRPCCallID(self): self.next_rpc_call_id += 1 return self.next_rpc_call_id # # SMB2 Methods Family # def _sendSMBMessage_SMB2(self, smb_message): if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: smb_message.flags |= SMB2_FLAGS_SIGNED raw_data = smb_message.encode() smb_message.signature = hmac.new(self.signing_session_key, raw_data, sha256).digest()[:16] smb_message.raw_data = smb_message.encode() self.log.debug('MID is %d. Signature is %s. Total raw message is %d bytes', smb_message.mid, binascii.hexlify(smb_message.signature), len(smb_message.raw_data)) else: smb_message.raw_data = smb_message.encode() self.sendNMBMessage(smb_message.raw_data) def _getNextMID_SMB2(self): self.mid += 1 return self.mid def _updateState_SMB2(self, message): if message.isReply: if message.command == SMB2_COM_NEGOTIATE: if message.status == 0: self.has_negotiated = True self.log.info('SMB2 dialect negotiation successful') self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB2_COM_NEGOTIATE' % message.status, message.raw_data, message) elif message.command == SMB2_COM_SESSION_SETUP: if message.status == 0: self.session_id = message.session_id try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') # [MS-SMB2]: 3.2.5.3.1 # If the security subsystem indicates that the session was established by an anonymous user, # Session.SigningRequired MUST be set to FALSE. # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired # MUST be set to FALSE. if message.payload.isGuestSession or message.payload.isAnonymousSession: self.is_signing_active = False self.log.info('Signing disabled because session is guest/anonymous') self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED self.session_id = message.session_id try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE or message.status == 0xc0000064 # STATUS_NO_SUCH_USER or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account or password has expired.') self.onAuthFailed() elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been disabled.') self.onAuthFailed() elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Not allowed.') self.onAuthFailed() elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Domain not trusted.') self.onAuthFailed() elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) if message.isAsync: if message.status == 0x00000103: # STATUS_PENDING req = self.pending_requests.pop(message.mid, None) if req: self.async_requests[message.async_id] = req else: # All other status including SUCCESS req = self.async_requests.pop(message.async_id, None) if req: req.callback(message, **req.kwargs) return True else: req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB2(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_transact_size = payload.max_transact_size self.max_read_size = payload.max_read_size self.max_write_size = payload.max_write_size self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication def _handleNegotiateResponse_SMB2(self, message): ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) def _handleSessionChallenge_SMB2(self, message, ntlm_token): server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) if self.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & SMB2_NEGOTIATE_SIGNING_ENABLED: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = session_signing_key if self.log.isEnabledFor(logging.DEBUG): self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _listShares_SMB2(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMB2Message(SMB2CreateRequest('srvsvc', file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE | FILE_OPEN_NO_RECALL, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: call_id = self._getNextRPCCallID() # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(b' ', b'')) + \ struct.pack('<I', call_id) + \ binascii.unhexlify(b""" b8 10 b8 10 00 00 00 00 02 00 00 00 00 00 01 00 c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 04 5d 88 8a eb 1c c9 11 9f e8 08 00 2b 10 48 60 02 00 00 00 01 00 01 00 c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 2c 1c b7 6c 12 98 40 45 03 00 00 00 00 00 00 00 01 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2WriteRequest(create_message.payload.fid, data_bytes, 0)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history)) def rpcBindCB(trans_message, **kwargs): self._pushToArray(messages_history, trans_message) if trans_message.status == 0: m = SMB2Message(SMB2ReadRequest(kwargs['fid'], read_len = 1024, read_offset = 0)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) self._pushToArray(messages_history, m) else: closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') def rpcReadCB(read_message, **kwargs): self._pushToArray(messages_history, read_message) if read_message.status == 0: call_id = self._getNextRPCCallID() padding = b'' remote_name = '\\\\' + self.remote_name server_len = len(remote_name) + 1 server_bytes_len = server_len * 2 if server_len % 2 != 0: padding = b'\0\0' server_bytes_len += 2 # The data bytes are the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify(b"""05 00 00 03 10 00 00 00""".replace(b' ', b'')) + \ struct.pack('<HHI', 72+server_bytes_len, 0, call_id) + \ binascii.unhexlify(b"""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(b' ', b'')) + \ struct.pack('<III', server_len, 0, server_len) + \ (remote_name + '\0').encode('UTF-16LE') + padding + \ binascii.unhexlify(b""" 01 00 00 00 01 00 00 00 04 00 02 00 00 00 00 00 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2IoctlRequest(kwargs['fid'], 0x0011C017, flags = 0x01, max_out_size = 8196, in_data = data_bytes)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) self._pushToArray(messages_history, m) else: closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') def listShareResultsCB(result_message, **kwargs): self._pushToArray(messages_history, result_message) if result_message.status == 0: # The payload.data_bytes will contain the results of the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. data_bytes = result_message.payload.out_data if data_bytes[3] & 0x02 == 0: sendReadRequest(kwargs['tid'], kwargs['fid'], data_bytes) else: decodeResults(kwargs['tid'], kwargs['fid'], data_bytes) else: closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def decodeResults(tid, fid, data_bytes): shares_count = struct.unpack('<I', data_bytes[36:40])[0] results = [ ] # A list of SharedDevice instances offset = 36 + 12 # You need to study the byte stream to understand the meaning of these constants for i in range(0, shares_count): results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) offset += 12 for i in range(0, shares_count): max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 results[i].name = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2]) if length % 2 != 0: offset += (length * 2 + 2) else: offset += (length * 2) max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 results[i].comments = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2]) if length % 2 != 0: offset += (length * 2 + 2) else: offset += (length * 2) closeFid(tid, fid) callback(results) def sendReadRequest(tid, fid, data_bytes): read_count = min(4280, self.max_read_size) m = SMB2Message(SMB2ReadRequest(fid, 0, read_count)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, tid = tid, fid = fid, data_bytes = data_bytes) def readCB(read_message, **kwargs): self._pushToArray(messages_history, read_message) if read_message.status == 0: data_bytes = read_message.payload.data if data_bytes[3] & 0x02 == 0: sendReadRequest(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: decodeResults(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: errback(OperationFailure(kwargs['error'], messages_history)) if path not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[path] = connect_message.tid connectSrvSvc(connect_message.tid) else: errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = path) self._pushToArray(messages_history, m) else: connectSrvSvc(self.connected_trees[path]) def _listPath_SMB2(self, service_name, path, callback, errback, search, pattern, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: sendQuery(kwargs['tid'], create_message.payload.fid, b'') elif create_message.status == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID errback(OperationFailure('Failed to list %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to list %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendQuery(tid, fid, data_buf): m = SMB2Message(SMB2QueryDirectoryRequest(fid, pattern, info_class = 0x25, # FileIdBothDirectoryInformation flags = 0, output_buf_len = self.max_transact_size)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = tid, fid = fid, data_buf = data_buf) self._pushToArray(messages_history, m) def queryCB(query_message, **kwargs): self._pushToArray(messages_history, query_message) if query_message.status == 0: data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data) sendQuery(kwargs['tid'], kwargs['fid'], data_buf) elif query_message.status == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # If there are no matching files, we just treat as success instead of failing closeFid(kwargs['tid'], kwargs['fid'], results = results) elif query_message.status == 0x80000006: # STATUS_NO_MORE_FILES closeFid(kwargs['tid'], kwargs['fid'], results = results) else: closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def decodeQueryStruct(data_bytes): # FileIdBothDirectoryInformation structure. See [MS-SMB]: 2.2.8.1.3 and [MS-FSCC]: 2.4.17 info_format = '<IIQQQQQQIIIBB24sHQ' info_size = struct.calcsize(info_format) data_length = len(data_bytes) offset = 0 while offset < data_length: if offset + info_size > data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name, _, file_id = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset2:offset2+filename_length]) short_name = DataFaultToleranceStrategy.data_bytes_decode(short_name[:short_name_length]) accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset else: break return b'' def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files callback([ ]) else: errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getAttributes_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: p = create_message.payload filename = self._extractLastPathComponent(path) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, filename, filename) closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) def closeFid(tid, fid, info = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, info = info, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['info'] is not None: callback(kwargs['info']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get attributes for %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, info_type = SMB2_INFO_SECURITY, file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 input_buf = '', output_buf_len = self.max_transact_size)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) def queryCB(query_message, **kwargs): self._pushToArray(messages_history, query_message) if query_message.status == 0: security = SecurityDescriptor.from_bytes(query_message.payload.data) closeFid(kwargs['tid'], kwargs['fid'], result = security) else: closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def closeFid(tid, fid, result = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['result'] is not None: callback(kwargs['result']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout) def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 input_buf = b'', output_buf_len = 4096)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): self._pushToArray(messages_history, info_message) if info_message.status == 0: file_len = struct.unpack('<Q', info_message.payload.data[8:16])[0] if max_length == 0 or starting_offset > file_len: if self.pbar: self.pbar.close() self.pbar = None closeFid(info_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], 0 )) # Note that this is a tuple of 3-elements else: remaining_len = max_length if remaining_len < 0: remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset if show_progress: tqdm_kwargs.setdefault("total", remaining_len) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Downloading {path}") self.pbar = tqdm(**tqdm_kwargs) sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) m = SMB2Message(SMB2ReadRequest(fid, offset, read_count)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) def readCB(read_message, **kwargs): # To avoid crazy memory usage when retrieving large files, we do not save every read_message in messages_history. if read_message.status == 0: data_len = read_message.payload.data_length file_obj.write(read_message.payload.data) remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) if self.pbar: self.pbar.update(data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: self._pushToArray(messages_history, read_message) closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, ret = ret, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['ret'] is not None: callback(kwargs['ret']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _storeFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): self._storeFileFromOffset_SMB2(service_name, path, file_obj, callback, errback, 0, True, timeout) def _storeFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] if show_progress: total_bytes = os.stat(file_obj.name).st_size tqdm_kwargs.setdefault("total", total_bytes) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Uploading {path}") self.pbar = tqdm(**tqdm_kwargs) def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 10 00 04 00 00 00 18 00 08 00 00 00 41 6c 53 69 00 00 00 00 85 62 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = ATTR_ARCHIVE, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OVERWRITE_IF if truncate else FILE_OPEN_IF, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): create_message.tid = kwargs['tid'] self._pushToArray(messages_history, create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): write_count = self.max_write_size data = file_obj.read(write_count) data_len = len(data) if data_len > 0: m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) if self.pbar: self.pbar.update(data_len) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, write_message) closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid, error = None, offset = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, fid = fid, offset = offset, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['offset'] is not None: callback(( file_obj, kwargs['offset'] )) # Note that this is a tuple of 2-elements elif kwargs['error'] is not None: errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): open_message.tid = kwargs['tid'] self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(open_message.tid, open_message.payload.fid) elif open_message.status == 0xc0000034: # STATUS_OBJECT_NAME_NOT_FOUND callback(path) elif open_message.status == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = b'\x01')) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendCreate(tid) def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_WRITE_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendReset(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation data = struct.pack('qqqqii', 0, 0, 0, 0, file_attributes, 0))) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def resetCB(reset_message, **kwargs): self._pushToArray(messages_history, reset_message) if reset_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path_file_pattern) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Reset failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _createDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_EA | FILE_WRITE_EA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | READ_CONTROL | DELETE | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_CREATE, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): callback(path) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = b'\x01')) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _rename_SMB2(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout messages_history = [ ] new_path = new_path.replace('/', '\\') if new_path.startswith('\\'): new_path = new_path[1:] if new_path.endswith('\\'): new_path = new_path[:-1] old_path = old_path.replace('/', '\\') if old_path.startswith('\\'): old_path = old_path[1:] if old_path.endswith('\\'): old_path = old_path[:-1] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(old_path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) def sendRename(tid, fid): data = b'\x00'*16 + struct.pack('<I', len(new_path)*2) + new_path.encode('UTF-16LE') m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0a, # SMB2_FILE_RENAME_INFO data = data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def renameCB(rename_message, **kwargs): self._pushToArray(messages_history, rename_message) if rename_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = rename_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(( old_path, new_path )) else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _listSnapshots_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: sendEnumSnapshots(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open file/directory' % ( path, service_name ), messages_history)) def sendEnumSnapshots(tid, fid): m = SMB2Message(SMB2IoctlRequest(fid, ctlcode = 0x00144064, # FSCTL_SRV_ENUMERATE_SNAPSHOTS flags = 0x0001, in_data = b'')) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, enumSnapshotsCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def enumSnapshotsCB(enum_message, **kwargs): self._pushToArray(messages_history, enum_message) if enum_message.status == 0: results = [ ] snapshots_count = struct.unpack('<I', enum_message.payload.out_data[4:8])[0] for i in range(0, snapshots_count): s = DataFaultToleranceStrategy.data_bytes_decode(enum_message.payload.out_data[12+i*50:12+48+i*50]) results.append(datetime(*list(map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] ))))) closeFid(kwargs['tid'], kwargs['fid'], results = results) else: closeFid(kwargs['tid'], kwargs['fid'], status = enum_message.status) def closeFid(tid, fid, status = None, results = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, status = status, results = results) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['results'] is not None: callback(kwargs['results']) else: errback(OperationFailure('Failed to list snapshots %s on %s: List failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _echo_SMB2(self, data, callback, errback, timeout = 30): messages_history = [ ] def echoCB(echo_message, **kwargs): self._pushToArray(messages_history, echo_message) if echo_message.status == 0: callback(data) else: errback(OperationFailure('Echo failed', messages_history)) m = SMB2Message(SMB2EchoRequest()) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, echoCB, errback) self._pushToArray(messages_history, m) # # SMB1 Methods Family # def _sendSMBMessage_SMB1(self, smb_message): if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB1() if not smb_message.uid: smb_message.uid = self.uid if self.is_signing_active: smb_message.flags2 |= SMB_FLAGS2_SMB_SECURITY_SIGNATURE # Increment the next_signing_id as described in [MS-CIFS] 3.2.4.1.3 smb_message.security = self.next_signing_id self.next_signing_id += 2 # All our defined messages currently have responses, so always increment by 2 raw_data = smb_message.encode() md = ntlm.MD5(self.signing_session_key) if self.signing_challenge_response: md.update(self.signing_challenge_response) md.update(raw_data) signature = md.digest()[:8] self.log.debug('MID is %d. Signing ID is %d. Signature is %s. Total raw message is %d bytes', smb_message.mid, smb_message.security, binascii.hexlify(signature), len(raw_data)) smb_message.raw_data = raw_data[:14] + signature + raw_data[22:] else: smb_message.raw_data = smb_message.encode() self.sendNMBMessage(smb_message.raw_data) def _getNextMID_SMB1(self): self.mid += 1 if self.mid >= 0xFFFF: # MID cannot be 0xFFFF. [MS-CIFS]: 2.2.1.6.2 # We don't use MID of 0 as MID can be reused for SMB_COM_TRANSACTION2_SECONDARY messages # where if mid=0, _sendSMBMessage will re-assign new MID values again self.mid = 1 return self.mid def _updateState_SMB1(self, message): if message.isReply: if message.command == SMB_COM_NEGOTIATE: if not message.status.hasError: self.has_negotiated = True self.log.info('SMB dialect negotiation successful (ExtendedSecurity:%s)', message.hasExtendedSecurity) self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_NEGOTIATE' % message.status.internal_value, message.raw_data, message) elif message.command == SMB_COM_SESSION_SETUP_ANDX: if message.hasExtendedSecurity: if not message.status.hasError: try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (with extended security) successful!') self.onAuthOK() else: raise ProtocolError('SMB_COM_SESSION_SETUP_ANDX status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status.internal_value == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Please check username and password.') self.onAuthFailed() elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account or password has expired.') self.onAuthFailed() elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been disabled.') self.onAuthFailed() elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Not allowed.') self.onAuthFailed() elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Domain not trusted.') self.onAuthFailed() elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, message.raw_data, message) else: if message.status.internal_value == 0: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (without extended security) successful!') self.onAuthOK() else: self.has_authenticated = False self.log.info('Authentication (without extended security) failed. Please check username and password') self.onAuthFailed() elif message.command == SMB_COM_TREE_CONNECT_ANDX: try: req = self.pending_requests[message.mid] except KeyError: pass else: if not message.status.hasError: self.connected_trees[req.kwargs['path']] = message.tid req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB1(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_raw_size = payload.max_raw_size self.max_buffer_size = payload.max_buffer_size self.max_mpx_count = payload.max_mpx_count self.use_plaintext_authentication = not bool(payload.security_mode & NEGOTIATE_ENCRYPT_PASSWORDS) if self.use_plaintext_authentication: self.log.warning('Remote server only supports plaintext authentication. Your password can be stolen easily over the network.') def _handleSessionChallenge_SMB1(self, message, ntlm_token): assert message.hasExtendedSecurity if message.uid and not self.uid: self.uid = message.uid server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, signing_session_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(0, blob))) if self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRE: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLE: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = signing_session_key if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _handleNegotiateResponse_SMB1(self, message): if message.uid and not self.uid: self.uid = message.uid if message.hasExtendedSecurity or message.payload.supportsExtendedSecurity: ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(message.payload.session_key, blob))) else: nt_password, _, _ = ntlm.generateChallengeResponseV1(self.password, message.payload.challenge, False) self.log.info('Performing NTLMv1 authentication (without extended security) with challenge "%s" and hashed password of "%s"', binascii.hexlify(message.payload.challenge), binascii.hexlify(nt_password)) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__NoSecurityExtension(message.payload.session_key, self.username, nt_password, True, self.domain))) def _listShares_SMB1(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMBMessage(ComNTCreateAndxRequest('\\srvsvc', flags = NT_CREATE_REQUEST_EXTENDED_RESPONSE, access_mask = READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_READ_EA | FILE_APPEND_DATA | FILE_WRITE_DATA | FILE_READ_DATA, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, create_disp = FILE_OPEN, create_options = FILE_OPEN_NO_RECALL | FILE_NON_DIRECTORY_FILE, impersonation = SEC_IMPERSONATE, security_flags = 0)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: call_id = self._getNextRPCCallID() # See [MS-CIFS]: 2.2.5.6.1 for more information on TRANS_TRANSACT_NMPIPE (0x0026) parameters setup_bytes = struct.pack('<HH', 0x0026, create_message.payload.fid) # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 48 00 00 00""".replace(b' ', b'')) + \ struct.pack('<I', call_id) + \ binascii.unhexlify(b""" b8 10 b8 10 00 00 00 00 01 00 00 00 00 00 01 00 c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 04 5d 88 8a eb 1c c9 11 9f e8 08 00 2b 10 48 60 02 00 00 00""".replace(b' ', b'').replace(b'\n', b'')) m = SMBMessage(ComTransactionRequest(max_params_count = 0, max_data_count = 4280, max_setup_count = 0, data_bytes = data_bytes, setup_bytes = setup_bytes)) m.tid = create_message.tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, fid = create_message.payload.fid) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history)) def rpcBindCB(trans_message, **kwargs): self._pushToArray(messages_history, trans_message) if not trans_message.status.hasError: call_id = self._getNextRPCCallID() padding = b'' server_len = len(self.remote_name) + 1 server_bytes_len = server_len * 2 if server_len % 2 != 0: padding = b'\0\0' server_bytes_len += 2 # See [MS-CIFS]: 2.2.5.6.1 for more information on TRANS_TRANSACT_NMPIPE (0x0026) parameters setup_bytes = struct.pack('<HH', 0x0026, kwargs['fid']) # The data bytes are the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify(b"""05 00 00 03 10 00 00 00""".replace(b' ', b'')) + \ struct.pack('<HHI', 72+server_bytes_len, 0, call_id) + \ binascii.unhexlify(b"""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(b' ', b'')) + \ struct.pack('<III', server_len, 0, server_len) + \ (self.remote_name + '\0').encode('UTF-16LE') + padding + \ binascii.unhexlify(b""" 01 00 00 00 01 00 00 00 04 00 02 00 00 00 00 00 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMBMessage(ComTransactionRequest(max_params_count = 0, max_data_count = 4280, max_setup_count = 0, data_bytes = data_bytes, setup_bytes = setup_bytes)) m.tid = trans_message.tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) self._pushToArray(messages_history, m) else: closeFid(trans_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to bind to Server Service RPC endpoint', messages_history)) def listShareResultsCB(result_message, **kwargs): self._pushToArray(messages_history, result_message) if not result_message.status.hasError: # The payload.data_bytes will contain the results of the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. data_bytes = result_message.payload.data_bytes if data_bytes[3] & 0x02 == 0: sendReadRequest(result_message.tid, kwargs['fid'], data_bytes) else: decodeResults(result_message.tid, kwargs['fid'], data_bytes) else: closeFid(result_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def decodeResults(tid, fid, data_bytes): shares_count = struct.unpack('<I', data_bytes[36:40])[0] results = [ ] # A list of SharedDevice instances offset = 36 + 12 # You need to study the byte stream to understand the meaning of these constants for i in range(0, shares_count): results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) offset += 12 for i in range(0, shares_count): max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 results[i].name = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2]) if length % 2 != 0: offset += (length * 2 + 2) else: offset += (length * 2) max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 results[i].comments = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2]) if length % 2 != 0: offset += (length * 2 + 2) else: offset += (length * 2) closeFid(tid, fid) callback(results) def sendReadRequest(tid, fid, data_bytes): read_count = min(4280, self.max_raw_size - 2) m = SMBMessage(ComReadAndxRequest(fid = fid, offset = 0, max_return_bytes_count = read_count, min_return_bytes_count = read_count)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, fid = fid, data_bytes = data_bytes) def readCB(read_message, **kwargs): self._pushToArray(messages_history, read_message) if not read_message.status.hasError: data_bytes = read_message.payload.data if data_bytes[3] & 0x02 == 0: sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[path] = connect_message.tid connectSrvSvc(connect_message.tid) else: errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = path) self._pushToArray(messages_history, m) def _listPath_SMB1(self, service_name, path, callback, errback, search, pattern, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if not path.endswith('\\'): path += '\\' messages_history = [ ] results = [ ] def sendFindFirst(tid, support_dfs=False): setup_bytes = struct.pack('<H', 0x0001) # TRANS2_FIND_FIRST2 sub-command. See [MS-CIFS]: 2.2.6.2.1 params_bytes = \ struct.pack('<HHHHI', search & 0xFFFF, # SearchAttributes (need to restrict the values due to introduction of SMB_FILE_ATTRIBUTE_INCL_NORMAL) 100, # SearchCount 0x0006, # Flags: SMB_FIND_CLOSE_AT_EOS | SMB_FIND_RETURN_RESUME_KEYS 0x0104, # InfoLevel: SMB_FIND_FILE_BOTH_DIRECTORY_INFO 0x0000) # SearchStorageType (seems to be ignored by Windows) if support_dfs: params_bytes += ("\\" + self.remote_name + "\\" + service_name + path + pattern + '\0').encode('UTF-16LE') else: params_bytes += (path + pattern + '\0').encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 10, max_data_count = 16644, max_setup_count = 0, params_bytes = params_bytes, setup_bytes = setup_bytes)) m.tid = tid if support_dfs: m.flags2 |= SMB_FLAGS2_DFS self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, findFirstCB, errback) self._pushToArray(messages_history, m) def decodeFindStruct(data_bytes): # SMB_FIND_FILE_BOTH_DIRECTORY_INFO structure. See [MS-CIFS]: 2.2.8.1.7 and [MS-SMB]: 2.2.8.1.1 info_format = '<IIQQQQQQIIIBB24s' info_size = struct.calcsize(info_format) data_length = len(data_bytes) offset = 0 while offset < data_length: if offset + info_size > data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset2:offset2+filename_length]) short_name = DataFaultToleranceStrategy.data_bytes_decode(short_name) accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset else: break return b'' def findFirstCB(find_message, **kwargs): self._pushToArray(messages_history, find_message) if not find_message.status.hasError: if 'total_count' not in kwargs: # TRANS2_FIND_FIRST2 response. [MS-CIFS]: 2.2.6.2.2 sid, search_count, end_of_search, _, last_name_offset = struct.unpack('<HHHHH', find_message.payload.params_bytes[:10]) kwargs.update({ 'sid': sid, 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': b'' }) else: sid, end_of_search, last_name_offset = kwargs['sid'], kwargs['end_of_search'], kwargs['last_name_offset'] send_next = True if find_message.payload.data_bytes: d = decodeFindStruct(kwargs['data_buf'] + find_message.payload.data_bytes) if 'data_count' not in kwargs: if len(find_message.payload.data_bytes) != find_message.payload.total_data_count: kwargs.update({ 'data_count': len(find_message.payload.data_bytes), 'total_count': find_message.payload.total_data_count, 'data_buf': d, }) send_next = False else: kwargs['data_count'] += len(find_message.payload.data_bytes) kwargs['total_count'] = min(find_message.payload.total_data_count, kwargs['total_count']) kwargs['data_buf'] = d if kwargs['data_count'] != kwargs['total_count']: send_next = False if not send_next: self.pending_requests[find_message.mid] = _PendingRequest(find_message.mid, expiry_time, findFirstCB, errback, **kwargs) elif end_of_search: callback(results) else: sendFindNext(find_message.tid, sid, 0, results[-1].filename, kwargs.get('support_dfs', False)) else: if find_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files callback([ ]) else: errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) def sendFindNext(tid, sid, resume_key, resume_file, support_dfs): setup_bytes = struct.pack('<H', 0x0002) # TRANS2_FIND_NEXT2 sub-command. See [MS-CIFS]: 2.2.6.3.1 params_bytes = \ struct.pack('<HHHIH', sid, # SID 100, # SearchCount 0x0104, # InfoLevel: SMB_FIND_FILE_BOTH_DIRECTORY_INFO resume_key, # ResumeKey 0x0006) # Flags: SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS params_bytes += (resume_file+'\0').encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 10, max_data_count = 16644, max_setup_count = 0, params_bytes = params_bytes, setup_bytes = setup_bytes)) m.tid = tid if support_dfs: m.flags2 |= SMB_FLAGS2_DFS self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, findNextCB, errback, sid = sid, support_dfs = support_dfs) self._pushToArray(messages_history, m) def findNextCB(find_message, **kwargs): self._pushToArray(messages_history, find_message) if not find_message.status.hasError: if 'total_count' not in kwargs: # TRANS2_FIND_NEXT2 response. [MS-CIFS]: 2.2.6.3.2 search_count, end_of_search, _, last_name_offset = struct.unpack('<HHHH', find_message.payload.params_bytes[:8]) kwargs.update({ 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': b'' }) else: end_of_search, last_name_offset = kwargs['end_of_search'], kwargs['last_name_offset'] send_next = True if find_message.payload.data_bytes: d = decodeFindStruct(kwargs['data_buf'] + find_message.payload.data_bytes) if 'data_count' not in kwargs: if len(find_message.payload.data_bytes) != find_message.payload.total_data_count: kwargs.update({ 'data_count': len(find_message.payload.data_bytes), 'total_count': find_message.payload.total_data_count, 'data_buf': d, }) send_next = False else: kwargs['data_count'] += len(find_message.payload.data_bytes) kwargs['total_count'] = min(find_message.payload.total_data_count, kwargs['total_count']) kwargs['data_buf'] = d if kwargs['data_count'] != kwargs['total_count']: send_next = False if not send_next: self.pending_requests[find_message.mid] = _PendingRequest(find_message.mid, expiry_time, findNextCB, errback, **kwargs) elif end_of_search: callback(results) else: sendFindNext(find_message.tid, kwargs['sid'], 0, results[-1].filename, kwargs.get('support_dfs', False)) else: errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) def sendDFSReferral(tid): setup_bytes = struct.pack('<H', 0x0010) # TRANS2_GET_DFS_REFERRAL sub-command. See [MS-CIFS]: 2.2.6.16.1 params_bytes = struct.pack('<H', 3) # Max referral level 3 params_bytes += ("\\" + self.remote_name + "\\" + service_name).encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 10, max_data_count = 16644, max_setup_count = 0, params_bytes = params_bytes, setup_bytes = setup_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, dfsReferralCB, errback) self._pushToArray(messages_history, m) def dfsReferralCB(dfs_message, **kwargs): sendFindFirst(dfs_message.tid, True) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid if connect_message.payload.optional_support & SMB_TREE_CONNECTX_SUPPORT_DFS: sendDFSReferral(connect_message.tid) else: sendFindFirst(connect_message.tid, False) else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendFindFirst(self.connected_trees[service_name]) def _getAttributes_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendQuery(tid): setup_bytes = struct.pack('<H', 0x0005) # TRANS2_QUERY_PATH_INFORMATION sub-command. See [MS-CIFS]: 2.2.6.6.1 params_bytes = \ struct.pack('<HI', 0x0107, # SMB_QUERY_FILE_ALL_INFO ([MS-CIFS] 2.2.2.3.3) 0x0000) # Reserved params_bytes += (path + '\0').encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 2, max_data_count = 65535, max_setup_count = 0, params_bytes = params_bytes, setup_bytes = setup_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback) self._pushToArray(messages_history, m) def queryCB(query_message, **kwargs): self._pushToArray(messages_history, query_message) if not query_message.status.hasError: info_format = '<QQQQIIQQ' info_size = struct.calcsize(info_format) create_time, last_access_time, last_write_time, last_attr_change_time, \ file_attributes, _, alloc_size, file_size = struct.unpack(info_format, query_message.payload.data_bytes[:info_size]) filename = self._extractLastPathComponent(path) info = SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, filename, filename) callback(info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Read failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendQuery(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendQuery(self.connected_trees[service_name]) def _getSecurity_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): raise NotReadyError('getSecurity is not yet implemented for SMB1') def _retrieveFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30, show_progress = False, tqdm_kwargs = { }): return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout, show_progress, tqdm_kwargs) def _retrieveFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0040, # Sharing mode: Deny nothing to others open_mode = 0x0001, # Failed if file does not exist search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: if max_length == 0: closeFid(open_message.tid, open_message.payload.fid) callback(( file_obj, open_message.payload.file_attributes, 0 )) else: if show_progress and max_length > 0: tqdm_kwargs.setdefault("total", max_length) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Downloading {path}") self.pbar = tqdm(**tqdm_kwargs) sendRead(open_message.tid, open_message.payload.fid, starting_offset, open_message.payload.file_attributes, 0, max_length) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, file_attributes, read_len, remaining_len): read_count = self.max_raw_size - 2 m = SMBMessage(ComReadAndxRequest(fid = fid, offset = offset, max_return_bytes_count = read_count, min_return_bytes_count = min(0xFFFF, read_count))) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, fid = fid, offset = offset, file_attributes = file_attributes, read_len = read_len, remaining_len = remaining_len) def readCB(read_message, **kwargs): # To avoid crazy memory usage when retrieving large files, we do not save every read_message in messages_history. if not read_message.status.hasError: read_len = kwargs['read_len'] remaining_len = kwargs['remaining_len'] data_len = read_message.payload.data_length if max_length > 0: if data_len > remaining_len: file_obj.write(read_message.payload.data[:remaining_len]) read_len += remaining_len remaining_len = 0 else: file_obj.write(read_message.payload.data) remaining_len -= data_len read_len += data_len else: file_obj.write(read_message.payload.data) read_len += data_len if self.pbar: self.pbar.update(data_len) if (max_length > 0 and remaining_len <= 0) or data_len < (self.max_raw_size - 2): if self.pbar: self.pbar.close() self.pbar = None closeFid(read_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], read_len )) # Note that this is a tuple of 3-elements else: sendRead(read_message.tid, kwargs['fid'], kwargs['offset']+data_len, kwargs['file_attributes'], read_len, remaining_len) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, read_message) closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _storeFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30, show_progress = False, tqdm_kwargs = { }): self._storeFileFromOffset_SMB1(service_name, path, file_obj, callback, errback, 0, True, timeout, show_progress, tqdm_kwargs) def _storeFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0041, # Sharing mode: Deny nothing to others + Open for writing open_mode = 0x0012 if truncate else 0x0011, # Create file if file does not exist. Overwrite or append depending on truncate parameter. search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: if show_progress: tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Uploading {path}") self.pbar = tqdm(**tqdm_kwargs) sendWrite(open_message.tid, open_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): # [MS-SMB] 2.2.4.5.2.2: The total SMB message size (inclusive of SMB header) must be not exceed the max_buffer_size. write_count = min(self.max_buffer_size-64, 0xFFFF-64) # SMB header is 32-bytes. We factor in another 32-bytes for the message parameter block data_bytes = file_obj.read(write_count) data_len = len(data_bytes) if data_len > 0: m = SMBMessage(ComWriteAndxRequest(fid = fid, offset = offset, data_bytes = data_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(tid, fid) callback(( file_obj, offset )) # Note that this is a tuple of 2-elements def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if not write_message.status.hasError: if self.pbar: self.pbar.update(kwargs['offset']) sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, write_message) closeFid(write_message.tid, kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteRequest(filename_pattern = path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) elif delete_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # If there are no matching files, we just treat as success instead of failing callback(path) elif delete_message.status.internal_value == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) elif delete_message.status.internal_value == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendDelete(tid) def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendCreate(tid): m = SMBMessage(ComCreateDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendDelete(self.connected_trees[service_name]) def _rename_SMB1(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') new_path = new_path.replace('/', '\\') old_path = old_path.replace('/', '\\') messages_history = [ ] def sendRename(tid): m = SMBMessage(ComRenameRequest(old_path = old_path, new_path = new_path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback) self._pushToArray(messages_history, m) def renameCB(rename_message, **kwargs): self._pushToArray(messages_history, rename_message) if not rename_message.status.hasError: callback(( old_path, new_path )) # Note that this is a tuple of 2-elements else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendRename(connect_message.tid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendRename(self.connected_trees[service_name]) def _listSnapshots_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if not path.endswith('\\'): path += '\\' messages_history = [ ] results = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0040, # Sharing mode: Deny nothing to others open_mode = 0x0001, # Failed if file does not exist search_attributes = 0, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: sendEnumSnapshots(open_message.tid, open_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open path' % ( path, service_name ), messages_history)) def sendEnumSnapshots(tid, fid): # [MS-CIFS]: 2.2.7.2 # [MS-SMB]: 2.2.7.2.1 setup_bytes = struct.pack('<IHBB', 0x00144064, # [MS-SMB]: 2.2.7.2.1 fid, # FID 0x01, # IsFctl 0) # IsFlags m = SMBMessage(ComNTTransactRequest(function = 0x0002, # NT_TRANSACT_IOCTL. [MS-CIFS]: 2.2.7.2.1 max_params_count = 0, max_data_count = 0xFFFF, max_setup_count = 0, setup_bytes = setup_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, enumSnapshotsCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def enumSnapshotsCB(enum_message, **kwargs): self._pushToArray(messages_history, enum_message) if not enum_message.status.hasError: results = [ ] snapshots_count = struct.unpack('<I', enum_message.payload.data_bytes[4:8])[0] for i in range(0, snapshots_count): s = DataFaultToleranceStrategy.data_bytes_decode(enum_message.payload.data_bytes[12+i*50:12+48+i*50]) results.append(datetime(*list(map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] ))))) closeFid(kwargs['tid'], kwargs['fid']) callback(results) else: closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list snapshots %s on %s: Unable to list snapshots on path' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _echo_SMB1(self, data, callback, errback, timeout = 30): messages_history = [ ] if not isinstance(data, type(b'')): raise TypeError('Echo data must be %s not %s' % (type(b'').__name__, type(data).__name__)) def echoCB(echo_message, **kwargs): self._pushToArray(messages_history, echo_message) if not echo_message.status.hasError: callback(echo_message.payload.data) else: errback(OperationFailure('Echo failed', messages_history)) m = SMBMessage(ComEchoRequest(echo_data = data)) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, echoCB, errback) self._pushToArray(messages_history, m) def _extractLastPathComponent(self, path): return path.replace('\\', '/').split('/')[-1] def _pushToArray(self, messages_history, message): if len(messages_history) > 10: messages_history.pop(0) messages_history.append(message)
[docs]class SharedDevice: """ Contains information about a single shared device on the remote server. The following attributes are available: * name : An unicode string containing the name of the shared device * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 # They are used to identify the type of shared resource from the results from the NetrShareEnum in Server Service RPC DISK_TREE = 0x00 PRINT_QUEUE = 0x01 COMM_DEVICE = 0x02 IPC = 0x03 def __init__(self, type, name, comments): self._type = type self.name = name #: An unicode string containing the name of the shared device self.comments = comments #: An unicode string containing the user description of the shared device @property def type(self): """ Returns one of the following integral constants. - SharedDevice.DISK_TREE - SharedDevice.PRINT_QUEUE - SharedDevice.COMM_DEVICE - SharedDevice.IPC """ return self._type & 0xFFFF @property def isSpecial(self): """ Returns True if this shared device is a special share reserved for interprocess communication (IPC$) or remote administration of the server (ADMIN$). Can also refer to administrative shares such as C$, D$, E$, and so forth """ return bool(self._type & 0x80000000) @property def isTemporary(self): """ Returns True if this is a temporary share that is not persisted for creation each time the file server initializes. """ return bool(self._type & 0x40000000) def __unicode__(self): return 'Shared device: %s (type:0x%02x comments:%s)' % (self.name, self.type, self.comments )
[docs]class SharedFile: """ Contain information about a file/folder entry that is shared on the shared device. As an application developer, you should not need to instantiate a *SharedFile* instance directly in your application. These *SharedFile* instances are usually returned via a call to *listPath* method in :doc:`smb.SMBProtocol.SMBProtocolFactory<smb_SMBProtocolFactory>`. If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). The following attributes are available: * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server * file_size : File size in number of bytes * alloc_size : Total number of bytes allocated to store this file * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): """A convenience property to return True if this file resource is a directory on the remote server""" return bool(self.file_attributes & ATTR_DIRECTORY) @property def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) @property def isNormal(self): """ A convenient property to return True if this is a normal file. Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. """ return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) def __unicode__(self): return 'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory )
class _PendingRequest: def __init__(self, mid, expiry_time, callback, errback, **kwargs): self.mid = mid self.expiry_time = expiry_time self.callback = callback self.errback = errback self.kwargs = kwargs
================================================ FILE: docs/html/_modules/smb/security_descriptors.html ================================================ smb.security_descriptors — pysmb 1.2.12 documentation

Source code for smb.security_descriptors

"""
This module implements security descriptors, and the partial structures
used in them, as specified in [MS-DTYP].
"""

import struct


# Security descriptor control flags
# [MS-DTYP]: 2.4.6
SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001
SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002
SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004
SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008
SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010
SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020
SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040
SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080
SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100
SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200
SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400
SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800
SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000
SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000
SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000
SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000

# ACE types
# [MS-DTYP]: 2.4.4.1
ACE_TYPE_ACCESS_ALLOWED = 0x00
ACE_TYPE_ACCESS_DENIED = 0x01
ACE_TYPE_SYSTEM_AUDIT = 0x02
ACE_TYPE_SYSTEM_ALARM = 0x03
ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04
ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05
ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06
ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07
ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08
ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09
ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A
ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B
ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C
ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D
ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E
ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F
ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10
ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11
ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12
ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13

# ACE flags
# [MS-DTYP]: 2.4.4.1
ACE_FLAG_OBJECT_INHERIT = 0x01
ACE_FLAG_CONTAINER_INHERIT = 0x02
ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04
ACE_FLAG_INHERIT_ONLY = 0x08
ACE_FLAG_INHERITED = 0x10
ACE_FLAG_SUCCESSFUL_ACCESS = 0x40
ACE_FLAG_FAILED_ACCESS = 0x80

# Pre-defined well-known SIDs
# [MS-DTYP]: 2.4.2.4
SID_NULL = "S-1-0-0"
SID_EVERYONE = "S-1-1-0"
SID_LOCAL = "S-1-2-0"
SID_CONSOLE_LOGON = "S-1-2-1"
SID_CREATOR_OWNER = "S-1-3-0"
SID_CREATOR_GROUP = "S-1-3-1"
SID_OWNER_SERVER = "S-1-3-2"
SID_GROUP_SERVER = "S-1-3-3"
SID_OWNER_RIGHTS = "S-1-3-4"
SID_NT_AUTHORITY = "S-1-5"
SID_DIALUP = "S-1-5-1"
SID_NETWORK = "S-1-5-2"
SID_BATCH = "S-1-5-3"
SID_INTERACTIVE = "S-1-5-4"
SID_SERVICE = "S-1-5-6"
SID_ANONYMOUS = "S-1-5-7"
SID_PROXY = "S-1-5-8"
SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9"
SID_PRINCIPAL_SELF = "S-1-5-10"
SID_AUTHENTICATED_USERS = "S-1-5-11"
SID_RESTRICTED_CODE = "S-1-5-12"
SID_TERMINAL_SERVER_USER = "S-1-5-13"
SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14"
SID_THIS_ORGANIZATION = "S-1-5-15"
SID_IUSR = "S-1-5-17"
SID_LOCAL_SYSTEM = "S-1-5-18"
SID_LOCAL_SERVICE = "S-1-5-19"
SID_NETWORK_SERVICE = "S-1-5-20"
SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496"
SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497"
SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544"
SID_BUILTIN_USERS = "S-1-5-32-545"
SID_BUILTIN_GUESTS = "S-1-5-32-546"
SID_POWER_USERS = "S-1-5-32-547"
SID_ACCOUNT_OPERATORS = "S-1-5-32-548"
SID_SERVER_OPERATORS = "S-1-5-32-549"
SID_PRINTER_OPERATORS = "S-1-5-32-550"
SID_BACKUP_OPERATORS = "S-1-5-32-551"
SID_REPLICATOR = "S-1-5-32-552"
SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554"
SID_REMOTE_DESKTOP = "S-1-5-32-555"
SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556"
SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557"
SID_PERFMON_USERS = "S-1-5-32-558"
SID_PERFLOG_USERS = "S-1-5-32-559"
SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560"
SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561"
SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562"
SID_IIS_IUSRS = "S-1-5-32-568"
SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569"
SID_EVENT_LOG_READERS = "S-1-5-32-573"
SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574"
SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575"
SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576"
SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577"
SID_HYPER_V_ADMINS = "S-1-5-32-578"
SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579"
SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580"
SID_WRITE_RESTRICTED_CODE = "S-1-5-33"
SID_NTLM_AUTHENTICATION = "S-1-5-64-10"
SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14"
SID_DIGEST_AUTHENTICATION = "S-1-5-64-21"
SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1"
SID_NT_SERVICE = "S-1-5-80"
SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0"
SID_LOCAL_ACCOUNT = "S-1-5-113"
SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114"
SID_OTHER_ORGANIZATION = "S-1-5-1000"
SID_ALL_APP_PACKAGES = "S-1-15-2-1"
SID_ML_UNTRUSTED = "S-1-16-0"
SID_ML_LOW = "S-1-16-4096"
SID_ML_MEDIUM = "S-1-16-8192"
SID_ML_MEDIUM_PLUS = "S-1-16-8448"
SID_ML_HIGH = "S-1-16-12288"
SID_ML_SYSTEM = "S-1-16-16384"
SID_ML_PROTECTED_PROCESS = "S-1-16-20480"
SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1"
SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2"
SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3"
SID_KEY_TRUST_IDENTITY = "S-1-18-4"
SID_KEY_PROPERTY_MFA = "S-1-18-5"
SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6"


[docs] class SID(object): """ A Windows security identifier. Represents a single principal, such a user or a group, as a sequence of numbers consisting of the revision, identifier authority, and a variable-length list of subauthorities. See [MS-DTYP]: 2.4.2 """ def __init__(self, revision, identifier_authority, subauthorities): #: Revision, should always be 1. self.revision = revision #: An integer representing the identifier authority. self.identifier_authority = identifier_authority #: A list of integers representing all subauthorities. self.subauthorities = subauthorities def __str__(self): """ String representation, as specified in [MS-DTYP]: 2.4.2.1 """ if self.identifier_authority >= 2**32: id_auth = '%#x' % (self.identifier_authority,) else: id_auth = self.identifier_authority auths = [self.revision, id_auth] + self.subauthorities return 'S-' + '-'.join(str(subauth) for subauth in auths) def __repr__(self): return 'SID(%r)' % (str(self),) @classmethod def from_bytes(cls, data, return_tail=False): revision, subauth_count = struct.unpack('<BB', data[:2]) identifier_authority = struct.unpack('>Q', b'\x00\x00' + data[2:8])[0] subauth_data = data[8:] subauthorities = [struct.unpack('<L', subauth_data[4 * i : 4 * (i+1)])[0] for i in range(subauth_count)] sid = cls(revision, identifier_authority, subauthorities) if return_tail: return sid, subauth_data[4 * subauth_count :] return sid
[docs] class ACE(object): """ Represents a single access control entry. See [MS-DTYP]: 2.4.4 """ HEADER_FORMAT = '<BBH' def __init__(self, type_, flags, mask, sid, additional_data): #: An integer representing the type of the ACE. One of the #: ``ACE_TYPE_*`` constants. Corresponds to the ``AceType`` field #: from [MS-DTYP] 2.4.4.1. self.type = type_ #: An integer bitmask with ACE flags, corresponds to the #: ``AceFlags`` field. self.flags = flags #: An integer representing the ``ACCESS_MASK`` as specified in #: [MS-DTYP] 2.4.3. self.mask = mask #: The :class:`SID` of a trustee. self.sid = sid #: A dictionary of additional fields present in the ACE, depending #: on the type. The following fields can be present: #: #: * ``flags`` #: * ``object_type`` #: * ``inherited_object_type`` #: * ``application_data`` #: * ``attribute_data`` self.additional_data = additional_data def __repr__(self): return "ACE(type=%#04x, flags=%#04x, mask=%#010x, sid=%s)" % ( self.type, self.flags, self.mask, self.sid, ) @property def isInheritOnly(self): """Convenience property which indicates if this ACE is inherit only, meaning that it doesn't apply to the object itself.""" return bool(self.flags & ACE_FLAG_INHERIT_ONLY) @classmethod def from_bytes(cls, data): header_size = struct.calcsize(cls.HEADER_FORMAT) header = data[:header_size] type_, flags, size = struct.unpack(cls.HEADER_FORMAT, header) assert len(data) >= size body = data[header_size:size] additional_data = {} # In all ACE types, the mask immediately follows the header. mask = struct.unpack('<I', body[:4])[0] body = body[4:] # All OBJECT-type ACEs contain additional flags, and two GUIDs as # the following fields. if type_ in (ACE_TYPE_ACCESS_ALLOWED_OBJECT, ACE_TYPE_ACCESS_DENIED_OBJECT, ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT, ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT, ACE_TYPE_SYSTEM_AUDIT_OBJECT, ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT): additional_data['flags'] = struct.unpack('<I', body[:4])[0] additional_data['object_type'] = body[4:20] additional_data['inherited_object_type'] = body[20:36] body = body[36:] # Then the SID in all types. sid, body = SID.from_bytes(body, return_tail=True) # CALLBACK-type ACEs (and for some obscure reason, # SYSTEM_AUDIT_OBJECT) have a final tail of application data. if type_ in (ACE_TYPE_ACCESS_ALLOWED_CALLBACK, ACE_TYPE_ACCESS_DENIED_CALLBACK, ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT, ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT, ACE_TYPE_SYSTEM_AUDIT_OBJECT, ACE_TYPE_SYSTEM_AUDIT_CALLBACK, ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT): additional_data['application_data'] = body # SYSTEM_RESOURCE_ATTRIBUTE ACEs have a tail of attribute data. if type_ == ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE: additional_data['attribute_data'] = body return cls(type_, flags, mask, sid, additional_data)
[docs] class ACL(object): """ Access control list, encapsulating a sequence of access control entries. See [MS-DTYP]: 2.4.5 """ HEADER_FORMAT = '<BBHHH' def __init__(self, revision, aces): #: Integer value of the revision. self.revision = revision #: List of :class:`ACE` instances. self.aces = aces def __repr__(self): return "ACL(%r)" % (self.aces,) @classmethod def from_bytes(cls, data): revision = None aces = [] header_size = struct.calcsize(cls.HEADER_FORMAT) header, remaining = data[:header_size], data[header_size:] revision, sbz1, size, count, sbz2 = struct.unpack(cls.HEADER_FORMAT, header) assert len(data) >= size for i in range(count): ace_size = struct.unpack('<H', remaining[2:4])[0] ace_data, remaining = remaining[:ace_size], remaining[ace_size:] aces.append(ACE.from_bytes(ace_data)) return cls(revision, aces)
[docs] class SecurityDescriptor(object): """ Represents a security descriptor. See [MS-DTYP]: 2.4.6 """ HEADER_FORMAT = '<BBHIIII' def __init__(self, flags, owner, group, dacl, sacl): #: Integer bitmask of control flags. Corresponds to the #: ``Control`` field in [MS-DTYP] 2.4.6. self.flags = flags #: Instance of :class:`SID` representing the owner user. self.owner = owner #: Instance of :class:`SID` representing the owner group. self.group = group #: Instance of :class:`ACL` representing the discretionary access #: control list, which specifies access restrictions of an object. self.dacl = dacl #: Instance of :class:`ACL` representing the system access control #: list, which specifies audit logging of an object. self.sacl = sacl @classmethod def from_bytes(cls, data): owner = None group = None dacl = None sacl = None header = data[:struct.calcsize(cls.HEADER_FORMAT)] (revision, sbz1, flags, owner_offset, group_offset, sacl_offset, dacl_offset) = struct.unpack(cls.HEADER_FORMAT, header) assert revision == 1 assert flags & SECURITY_DESCRIPTOR_SELF_RELATIVE for offset in (owner_offset, group_offset, sacl_offset, dacl_offset): assert 0 <= offset < len(data) if owner_offset: owner = SID.from_bytes(data[owner_offset:]) if group_offset: group = SID.from_bytes(data[group_offset:]) if dacl_offset: dacl = ACL.from_bytes(data[dacl_offset:]) if sacl_offset: sacl = ACL.from_bytes(data[sacl_offset:]) return cls(flags, owner, group, dacl, sacl)
================================================ FILE: docs/html/_modules/smb/smb_structs.html ================================================ smb.smb_structs — pysmb 1.2.12 documentation

Source code for smb.smb_structs


import os, sys, struct, types, logging, binascii, time
from copy import copy
from io import StringIO
from .smb_constants import *
from .strategy import DataFaultToleranceStrategy

# Set to True if you want to enable support for extended security. Required for Windows Vista and later
SUPPORT_EXTENDED_SECURITY = True

# Set to True if you want to enable SMB2 protocol.
SUPPORT_SMB2 = True

# Supported dialects
DIALECTS = [ ]
for i, ( name, dialect ) in enumerate([ ( 'NT_LAN_MANAGER_DIALECT', b'NT LM 0.12' ), ]):
    DIALECTS.append(dialect)
    globals()[name] = i

DIALECTS2 = [ ]
for i, ( name, dialect ) in enumerate([ ( 'SMB2_DIALECT', b'SMB 2.002' ) ]):
    DIALECTS2.append(dialect)
    globals()[name] = i + len(DIALECTS)


[docs] class UnsupportedFeature(Exception): """ Raised when an supported feature is present/required in the protocol but is not currently supported by pysmb """ pass
[docs] class ProtocolError(Exception): def __init__(self, message, data_buf = None, smb_message = None): self.message = message self.data_buf = data_buf self.smb_message = smb_message def __str__(self): b = StringIO() b.write(self.message + os.linesep) if self.smb_message: b.write('=' * 20 + ' SMB Message ' + '=' * 20 + os.linesep) b.write(str(self.smb_message)) if self.data_buf: b.write('=' * 20 + ' SMB Data Packet (hex) ' + '=' * 20 + os.linesep) b.write(str(binascii.hexlify(self.data_buf))) b.write(os.linesep) return b.getvalue()
class SMB2ProtocolHeaderError(ProtocolError): def __init__(self): ProtocolError.__init__(self, "Packet header belongs to SMB2")
[docs] class OperationFailure(Exception): def __init__(self, message, smb_messages): self.message = message self.smb_messages = [copy(msg) for msg in smb_messages] self.args = (message, self.smb_messages) def __str__(self): b = StringIO() b.write(self.message + os.linesep) for idx, m in enumerate(self.smb_messages): b.write('=' * 20 + ' SMB Message %d ' % idx + '=' * 20 + os.linesep) b.write('SMB Header:' + os.linesep) b.write('-----------' + os.linesep) b.write(str(m)) b.write('SMB Data Packet (hex):' + os.linesep) b.write('----------------------' + os.linesep) b.write(str(binascii.hexlify(m.raw_data))) b.write(os.linesep) return b.getvalue()
class SMBError: def __init__(self): self.reset() def reset(self): self.internal_value = 0 self.is_ntstatus = True def __str__(self): if self.is_ntstatus: return 'NTSTATUS=0x%08X' % self.internal_value else: return 'ErrorClass=0x%02X ErrorCode=0x%04X' % ( self.internal_value >> 24, self.internal_value & 0xFFFF ) @property def hasError(self): return self.internal_value != 0 class SMBMessage: HEADER_STRUCT_FORMAT = "<4sBIBHHQxxHHHHB" HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) log = logging.getLogger('SMB.SMBMessage') protocol = 1 def __init__(self, payload = None): self.reset() if payload: self.payload = payload self.payload.initMessage(self) def __str__(self): b = StringIO() b.write('Command: 0x%02X (%s) %s' % ( self.command, SMB_COMMAND_NAMES.get(self.command, '<unknown>'), os.linesep )) b.write('Status: %s %s' % ( str(self.status), os.linesep )) b.write('Flags: 0x%02X %s' % ( self.flags, os.linesep )) b.write('Flags2: 0x%04X %s' % ( self.flags2, os.linesep )) b.write('PID: %d %s' % ( self.pid, os.linesep )) b.write('UID: %d %s' % ( self.uid, os.linesep )) b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Security: 0x%016X %s' % ( self.security, os.linesep )) b.write('Parameters: %d bytes %s%s %s' % ( len(self.parameters_data), os.linesep, str(binascii.hexlify(self.parameters_data)), os.linesep )) b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, str(binascii.hexlify(self.data)), os.linesep )) return b.getvalue() def reset(self): self.raw_data = b'' self.command = 0 self.status = SMBError() self.flags = 0 self.flags2 = 0 self.pid = 0 self.tid = 0 self.uid = 0 self.mid = 0 self.security = 0 self.parameters_data = b'' self.data = b'' self.payload = None @property def isAsync(self): return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): return bool(self.flags & SMB_FLAGS_REPLY) @property def hasExtendedSecurity(self): return bool(self.flags2 & SMB_FLAGS2_EXTENDED_SECURITY) def encode(self): """ Encode this SMB message into a series of bytes suitable to be embedded with a NetBIOS session message. AssertionError will be raised if this SMB message has not been initialized with a Payload instance @return: a string containing the encoded SMB message """ assert self.payload self.pid = os.getpid() self.payload.prepare(self) parameters_len = len(self.parameters_data) assert parameters_len % 2 == 0 headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, b'\xFFSMB', self.command, self.status.internal_value, self.flags, self.flags2, (self.pid >> 16) & 0xFFFF, self.security, self.tid, self.pid & 0xFFFF, self.uid, self.mid, int(parameters_len / 2)) return headers_data + self.parameters_data + struct.pack('<H', len(self.data)) + self.data def decode(self, buf): """ Decodes the SMB message in buf. All fields of the SMBMessage object will be reset to default values before decoding. On errors, do not assume that the fields will be reinstated back to what they are before this method is invoked. @param buf: data containing one complete SMB message @type buf: string @return: a positive integer indicating the number of bytes used in buf to decode this SMB message @raise ProtocolError: raised when decoding fails """ buf_len = len(buf) if buf_len < self.HEADER_STRUCT_SIZE: # We need at least 32 bytes (header) + 1 byte (parameter count) raise ProtocolError('Not enough data to decode SMB header', buf) self.reset() protocol, self.command, status, self.flags, \ self.flags2, pid_high, self.security, self.tid, \ pid_low, self.uid, self.mid, params_count = struct.unpack(self.HEADER_STRUCT_FORMAT, buf[:self.HEADER_STRUCT_SIZE]) if protocol == b'\xFESMB': raise SMB2ProtocolHeaderError() if protocol != b'\xFFSMB': raise ProtocolError('Invalid 4-byte protocol field', buf) self.pid = (pid_high << 16) | pid_low self.status.internal_value = status self.status.is_ntstatus = bool(self.flags2 & SMB_FLAGS2_NT_STATUS) offset = self.HEADER_STRUCT_SIZE if buf_len < params_count * 2 + 2: # Not enough data in buf to decode up to body length raise ProtocolError('Not enough data. Parameters list decoding failed', buf) datalen_offset = offset + params_count*2 body_len = struct.unpack('<H', buf[datalen_offset:datalen_offset+2])[0] if body_len > 0 and buf_len < (datalen_offset + 2 + body_len): # Not enough data in buf to decode body raise ProtocolError('Not enough data. Body decoding failed', buf) self.parameters_data = buf[offset:datalen_offset] if body_len > 0: self.data = buf[datalen_offset+2:datalen_offset+2+body_len] self.raw_data = buf self._decodePayload() return self.HEADER_STRUCT_SIZE + params_count * 2 + 2 + body_len def _decodePayload(self): if self.command == SMB_COM_READ_ANDX: self.payload = ComReadAndxResponse() elif self.command == SMB_COM_WRITE_ANDX: self.payload = ComWriteAndxResponse() elif self.command == SMB_COM_TRANSACTION: self.payload = ComTransactionResponse() elif self.command == SMB_COM_TRANSACTION2: self.payload = ComTransaction2Response() elif self.command == SMB_COM_OPEN_ANDX: self.payload = ComOpenAndxResponse() elif self.command == SMB_COM_NT_CREATE_ANDX: self.payload = ComNTCreateAndxResponse() elif self.command == SMB_COM_TREE_CONNECT_ANDX: self.payload = ComTreeConnectAndxResponse() elif self.command == SMB_COM_ECHO: self.payload = ComEchoResponse() elif self.command == SMB_COM_SESSION_SETUP_ANDX: self.payload = ComSessionSetupAndxResponse() elif self.command == SMB_COM_NEGOTIATE: self.payload = ComNegotiateResponse() if self.payload: self.payload.decode(self) class Payload: DEFAULT_ANDX_PARAM_HEADER = b'\xFF\x00\x00\x00' DEFAULT_ANDX_PARAM_SIZE = 4 def initMessage(self, message): # SMB_FLAGS2_UNICODE must always be enabled. Without this, almost all the Payload subclasses will need to be # rewritten to check for OEM/Unicode strings which will be tedious. Fortunately, almost all tested CIFS services # support SMB_FLAGS2_UNICODE by default. assert message.payload == self message.flags = SMB_FLAGS_CASE_INSENSITIVE | SMB_FLAGS_CANONICALIZED_PATHS message.flags2 = SMB_FLAGS2_UNICODE | SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_LONG_NAMES if SUPPORT_EXTENDED_SECURITY: message.flags2 |= SMB_FLAGS2_EXTENDED_SECURITY def prepare(self, message): raise NotImplementedError def decode(self, message): raise NotImplementedError class ComNegotiateRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.52.1 - [MS-SMB]: 2.2.4.5.1 """ def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_NEGOTIATE def prepare(self, message): assert message.payload == self message.parameters_data = b'' if SUPPORT_SMB2: message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS + DIALECTS2]) else: message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS]) class ComNegotiateResponse(Payload): """ Contains information on the SMB_COM_NEGOTIATE response from server After calling the decode method, each instance will contain the following attributes, - security_mode (integer) - max_mpx_count (integer) - max_number_vcs (integer) - max_buffer_size (long) - max_raw_size (long) - session_key (long) - capabilities (long) - system_time (long) - server_time_zone (integer) - challenge_length (integer) If the underlying SMB message's flag2 does not have SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - challenge (string) - domain (unicode) If the underlying SMB message's flags2 has SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - server_guid (string) - security_blob (string) References: =========== - [MS-SMB]: 2.2.4.5.2.1 - [MS-CIFS]: 2.2.4.52.2 """ PAYLOAD_STRUCT_FORMAT = '<HBHHIIIIQHB' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_NEGOTIATE if not message.isReply: raise ProtocolError('Not a SMB_COM_NEGOTIATE reply', message.raw_data, message) self.security_mode, self.max_mpx_count, self.max_number_vcs, self.max_buffer_size, \ self.max_raw_size, self.session_key, self.capabilities, self.system_time, self.server_time_zone, \ self.challenge_length = ( 0, ) * 10 data_len = len(message.parameters_data) if data_len < 2: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE dialect_index field', message.raw_data, message) self.dialect_index = struct.unpack('<H', message.parameters_data[:2])[0] if self.dialect_index == NT_LAN_MANAGER_DIALECT: if data_len != (0x11 * 2): raise ProtocolError('NT LAN Manager dialect selected in SMB_COM_NEGOTIATE but parameters bytes count (%d) does not meet specs' % data_len, message.raw_data, message) else: _, self.security_mode, self.max_mpx_count, self.max_number_vcs, self.max_buffer_size, \ self.max_raw_size, self.session_key, self.capabilities, self.system_time, self.server_time_zone, \ self.challenge_length = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) elif self.dialect_index == 0xFFFF: raise ProtocolError('Server does not support any of the pysmb dialects. Please email pysmb to add in support for your OS', message.raw_data, message) else: raise ProtocolError('Unknown dialect index (0x%04X)' % self.dialect_index, message.raw_data, message) data_len = len(message.data) if not message.hasExtendedSecurity: self.challenge, self.domain = '', '' if self.challenge_length > 0: if data_len >= self.challenge_length: self.challenge = message.data[:self.challenge_length] s = b'' offset = self.challenge_length while offset < data_len: _s = message.data[offset:offset+2] if _s == b'\0\0': self.domain = DataFaultToleranceStrategy.data_bytes_decode(s)#.decode('UTF-16LE') break else: s += _s offset += 2 else: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (without security extensions) Challenge field', message.raw_data, message) else: if data_len < 16: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (with security extensions) ServerGUID field', message.raw_data, message) self.server_guid = message.data[:16] self.security_blob = message.data[16:] @property def supportsExtendedSecurity(self): return bool(self.capabilities & CAP_EXTENDED_SECURITY) class ComSessionSetupAndxRequest__WithSecurityExtension(Payload): """ References: =========== - [MS-SMB]: 2.2.4.6.1 """ PAYLOAD_STRUCT_FORMAT = '<HHHIHII' def __init__(self, session_key, security_blob): self.session_key = session_key self.security_blob = security_blob def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_SESSION_SETUP_ANDX def prepare(self, message): assert message.hasExtendedSecurity message.flags2 |= SMB_FLAGS2_UNICODE cap = CAP_UNICODE | CAP_STATUS32 | CAP_EXTENDED_SECURITY | CAP_NT_SMBS message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, 16644, 10, 1, self.session_key, len(self.security_blob), 0, cap) message.data = self.security_blob if (SMBMessage.HEADER_STRUCT_SIZE + len(message.parameters_data) + len(message.data)) % 2 != 0: message.data = message.data + b'\0' message.data = message.data + b'\0' * 4 class ComSessionSetupAndxRequest__NoSecurityExtension(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.53.1 """ PAYLOAD_STRUCT_FORMAT = '<HHHIHHII' def __init__(self, session_key, username, password, is_unicode, domain): self.username = username self.session_key = session_key self.password = password self.is_unicode = is_unicode self.domain = domain def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_SESSION_SETUP_ANDX def prepare(self, message): if self.is_unicode: message.flags2 |= SMB_FLAGS2_UNICODE else: message.flags2 &= (~SMB_FLAGS2_UNICODE & 0xFFFF) password_len = len(self.password) message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, 16644, 10, 0, self.session_key, (not self.is_unicode and password_len) or 0, (self.is_unicode and password_len) or 0, 0, CAP_UNICODE | CAP_LARGE_FILES | CAP_STATUS32) est_offset = SMBMessage.HEADER_STRUCT_SIZE + len(message.parameters_data) # To check if data until SMB paramaters are aligned to a 16-bit boundary message.data = self.password if (est_offset + len(message.data)) % 2 != 0 and message.flags2 & SMB_FLAGS2_UNICODE: message.data = message.data + b'\0' if message.flags2 & SMB_FLAGS2_UNICODE: message.data = message.data + self.username.encode('UTF-16LE') + b'\0' else: message.data = message.data + str(self.username).encode('UTF-8') + b'\0' if (est_offset + len(message.data)) % 2 != 0 and message.flags2 & SMB_FLAGS2_UNICODE: message.data = message.data + b'\0' if message.flags2 & SMB_FLAGS2_UNICODE: message.data = message.data + self.domain.encode('UTF-16LE') + b'\0\0' + 'pysmb'.encode('UTF-16LE') + b'\0\0' else: message.data = message.data + self.domain.encode('UTF-8') + b'\0pysmb\0' class ComSessionSetupAndxResponse(Payload): """ Contains information on the SMB_COM_SESSION_SETUP_ANDX response from server If the underlying SMB message's flags2 does not have SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following attributes, - action If the underlying SMB message's flags2 has SMB_FLAGS2_EXTENDED_SECURITY bit enabled and the message status is STATUS_MORE_PROCESSING_REQUIRED or equals to 0x00 (no error), then the instance will have the following attributes, - action - securityblob If the underlying SMB message's flags2 has SMB_FLAGS2_EXTENDED_SECURITY bit enabled but the message status is not STATUS_MORE_PROCESSING_REQUIRED References: =========== - [MS-SMB]: 2.2.4.6.2 - [MS-CIFS]: 2.2.4.53.2 """ NOSECURE_PARAMETER_STRUCT_FORMAT = '<BBHH' NOSECURE_PARAMETER_STRUCT_SIZE = struct.calcsize(NOSECURE_PARAMETER_STRUCT_FORMAT) SECURE_PARAMETER_STRUCT_FORMAT = '<BBHHH' SECURE_PARAMETER_STRUCT_SIZE = struct.calcsize(SECURE_PARAMETER_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_SESSION_SETUP_ANDX if not message.hasExtendedSecurity: if not message.status.hasError: if len(message.parameters_data) < self.NOSECURE_PARAMETER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_SESSION_SETUP_ANDX (no security extensions) parameters', message.raw_data, message) _, _, _, self.action = struct.unpack(self.NOSECURE_PARAMETER_STRUCT_FORMAT, message.parameters_data[:self.NOSECURE_PARAMETER_STRUCT_SIZE]) else: if not message.status.hasError or message.status.internal_value == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED if len(message.parameters_data) < self.SECURE_PARAMETER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_SESSION_SETUP_ANDX (with security extensions) parameters', message.raw_data, message) _, _, _, self.action, blob_length = struct.unpack(self.SECURE_PARAMETER_STRUCT_FORMAT, message.parameters_data[:self.SECURE_PARAMETER_STRUCT_SIZE]) if len(message.data) < blob_length: raise ProtocolError('Not enough data to decode SMB_COM_SESSION_SETUP_ANDX (with security extensions) security blob', message.raw_data, message) self.security_blob = message.data[:blob_length] class ComTreeConnectAndxRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.55.1 - [MS-SMB]: 2.2.4.7.1 """ PAYLOAD_STRUCT_FORMAT = '<HH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, path, service, password = ''): self.path = path self.service = service self.password = password + '\0' def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_TREE_CONNECT_ANDX def prepare(self, message): password_len = len(self.password) message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, 0x08 | \ ((message.hasExtendedSecurity and 0x0004) or 0x00) | \ ((message.tid and message.tid != 0xffff and 0x0001) or 0x00), # Disconnect tid, if message.tid must be non-zero password_len) padding = b'' if password_len % 2 == 0: padding = b'\0' # Note that service field is never encoded in UTF-16LE. [MS-CIFS]: 2.2.1.1 message.data = self.password.encode('UTF-8') + padding + self.path.encode('UTF-16LE') + b'\0\0' + self.service.encode('UTF-8') + b'\0' class ComTreeConnectAndxResponse(Payload): """ Contains information about the SMB_COM_TREE_CONNECT_ANDX response from the server. If the message has no errors, each instance contains the following attributes: - optional_support References: =========== - [MS-CIFS]: 2.2.4.55.2 """ PAYLOAD_STRUCT_FORMAT = '<BBHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_TREE_CONNECT_ANDX if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_TREE_CONNECT_ANDX parameters', message.raw_data, message) _, _, _, self.optional_support = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) class ComNTCreateAndxRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.64.1 - [MS-SMB]: 2.2.4.9.1 """ PAYLOAD_STRUCT_FORMAT = '<BHIIIQIIIIIB' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, filename, flags = 0, root_fid = 0, access_mask = 0, allocation_size = 0, ext_attr = 0, share_access = 0, create_disp = 0, create_options = 0, impersonation = 0, security_flags = 0): self.filename = (filename + '\0').encode('UTF-16LE') self.flags = flags self.root_fid = root_fid self.access_mask = access_mask self.allocation_size = allocation_size self.ext_attr = ext_attr self.share_access = share_access self.create_disp = create_disp self.create_options = create_options self.impersonation = impersonation self.security_flags = security_flags def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_NT_CREATE_ANDX def prepare(self, message): filename_len = len(self.filename) message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, 0x00, # reserved filename_len, # NameLength self.flags, # Flags self.root_fid, # RootDirectoryFID self.access_mask, # DesiredAccess self.allocation_size, # AllocationSize self.ext_attr, # ExtFileAttributes self.share_access, # ShareAccess self.create_disp, # CreateDisposition self.create_options, # CreateOptions self.impersonation, # ImpersonationLevel self.security_flags) # SecurityFlags padding = b'' if (message.HEADER_STRUCT_SIZE + len(message.parameters_data)) % 2 != 0: padding = b'\0' message.data = padding + self.filename class ComNTCreateAndxResponse(Payload): """ Contains (partial) information about the SMB_COM_NT_CREATE_ANDX response from the server. Each instance contains the following attributes after decoding: - oplock_level - fid References: =========== - [MS-CIFS]: 2.2.4.64.2 """ PAYLOAD_STRUCT_FORMAT = '<BBHBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_NT_CREATE_ANDX if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_NT_CREATE_ANDX parameters', message.raw_data, message) _, _, _, self.oplock_level, self.fid = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) class ComTransactionRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.33.1 """ PAYLOAD_STRUCT_FORMAT = '<HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, params_bytes = b'', data_bytes = b'', setup_bytes = b'', flags = 0, timeout = 0, name = "\\PIPE\\"): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) self.max_params_count = max_params_count self.max_data_count = max_data_count self.max_setup_count = max_setup_count self.flags = flags self.timeout = timeout self.params_bytes = params_bytes self.data_bytes = data_bytes self.setup_bytes = setup_bytes self.name = name def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_TRANSACTION def prepare(self, message): name = (self.name + '\0').encode('UTF-16LE') name_len = len(name) setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: padding0 = b'\0' offset += 1 offset += name_len # For the name field padding1 = b'' if offset % 4 != 0: padding1 = b'\0'*(4-offset%4) offset += (4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = b'' if offset % 4 != 0: padding2 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransactionResponse(Payload): """ Contains information about a SMB_COM_TRANSACTION response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.33.2 """ PAYLOAD_STRUCT_FORMAT = '<HHHHHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_TRANSACTION if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.total_params_count, self.total_data_count, _, \ params_bytes_len, params_bytes_offset, params_bytes_displ, \ data_bytes_len, data_bytes_offset, data_bytes_displ, \ setup_count = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) if setup_count > 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComTransaction2Request(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.46.1 """ PAYLOAD_STRUCT_FORMAT = 'HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, params_bytes = b'', data_bytes = b'', setup_bytes = b'', flags = 0, timeout = 0): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) self.max_params_count = max_params_count self.max_data_count = max_data_count self.max_setup_count = max_setup_count self.flags = flags self.timeout = timeout self.params_bytes = params_bytes self.data_bytes = data_bytes self.setup_bytes = setup_bytes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_TRANSACTION2 def prepare(self, message): setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) name = b'\0\0' padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: padding0 = b'\0' offset += 1 offset += 2 # For the name field padding1 = b'' if offset % 4 != 0: padding1 = b'\0'*(4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = b'' if offset % 4 != 0: padding2 = b'\0'*(4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransaction2Response(Payload): """ Contains information about a SMB_COM_TRANSACTION2 response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.46.2 """ PAYLOAD_STRUCT_FORMAT = '<HHHHHHHHHBB' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_TRANSACTION2 if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION2 parameters', message.raw_data, message) self.total_params_count, self.total_data_count, _, \ params_bytes_len, params_bytes_offset, params_bytes_displ, \ data_bytes_len, data_bytes_offset, data_bytes_displ, \ setup_count, _ = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) if setup_count > 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComCloseRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.5.1 """ PAYLOAD_STRUCT_FORMAT = '<HI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, fid, last_modified_time = 0xFFFFFFFF): self.fid = fid self.last_modified_time = last_modified_time def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_CLOSE def prepare(self, message): message.parameters_data = struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.fid, self.last_modified_time) message.data = b'' class ComOpenAndxRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.41.1 """ PAYLOAD_STRUCT_FORMAT = '<HHHHIHIII' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, filename, access_mode, open_mode, flags = 0x0000, search_attributes = 0, file_attributes = 0, create_time = 0, timeout = 0): """ @param create_time: Epoch time value to indicate the time of creation for this file. If zero, we will automatically assign the current time @type create_time: int @param timeout: Number of milliseconds to wait for blocked open request before failing @type timeout: int """ self.filename = filename self.access_mode = access_mode self.open_mode = open_mode self.flags = flags self.search_attributes = search_attributes self.file_attributes = file_attributes self.create_time = create_time or int(time.time()) self.timeout = timeout def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_OPEN_ANDX def prepare(self, message): message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.flags, self.access_mode, self.search_attributes, self.file_attributes, self.create_time, self.open_mode, 0, # AllocationSize 0, # Timeout (in milli-secs) 0) # Reserved message.data = b'\0' + self.filename.encode('UTF-16LE') + b'\0\0' class ComOpenAndxResponse(Payload): """ Contains information about a SMB_COM_OPEN_ANDX response from the server After decoding, each instance will contain the following attributes: - fid (integer) - file_attributes (integer) - last_write_time (long) - access_rights (integer) - resource_type (integer) - open_results (integer) References: =========== - [MS-CIFS]: 2.2.4.41.2 - [MS-SMB]: 2.2.4.1.2 """ PAYLOAD_STRUCT_FORMAT = '<BBHHHIIHHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_OPEN_ANDX if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_OPEN_ANDX parameters', message.raw_data, message) _, _, _, self.fid, self.file_attributes, self.last_write_time, _, \ self.access_rights, self.resource_type, _, self.open_results, _, _, _ = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) class ComWriteAndxRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.43.1 - [MS-SMB]: 2.2.4.3.1 """ PAYLOAD_STRUCT_FORMAT = '<HIIHHHHHI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, fid, data_bytes, offset, write_mode = 0, timeout = 0): """ @param timeout: Number of milliseconds to wait for blocked write request before failing. Must be zero for writing to regular file @type timeout: int """ self.fid = fid self.offset = offset self.data_bytes = data_bytes self.timeout = timeout self.write_mode = write_mode def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_WRITE_ANDX def prepare(self, message): # constant 1 is to account for the pad byte in the message.data # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) data_offset = message.HEADER_STRUCT_SIZE + self.DEFAULT_ANDX_PARAM_SIZE + self.PAYLOAD_STRUCT_SIZE + 1 + 2 data_len = len(self.data_bytes) message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.fid, self.offset & 0xFFFFFFFF, self.timeout, self.write_mode, data_len, # Remaining 0x0000, # Reserved len(self.data_bytes), # DataLength data_offset, # DataOffset self.offset >> 32) # OffsetHigh field defined in [MS-SMB]: 2.2.4.3.1 message.data = b'\0' + self.data_bytes class ComWriteAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.43.2 - [MS-SMB]: 2.2.4.3.2 """ PAYLOAD_STRUCT_FORMAT = '<BBHHHHH' # We follow the SMB_COM_WRITEX_ANDX server extensions in [MS-SMB]: 2.2.4.3.2 PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_WRITE_ANDX if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_WRITE_ANDX parameters', message.raw_data, message) _, _, _, count, self.available, high_count, _ = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) self.count = (count & 0xFFFF) | (high_count << 16) class ComReadAndxRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.42.1 - [MS-SMB]: 2.2.4.2.1 """ PAYLOAD_STRUCT_FORMAT = '<HIHHIHI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, fid, offset, max_return_bytes_count, min_return_bytes_count, timeout = 0, remaining = 0): """ @param timeout: If reading from a regular file, this parameter must be 0. @type timeout: int """ self.fid = fid self.remaining = remaining self.max_return_bytes_count = max_return_bytes_count self.min_return_bytes_count = min_return_bytes_count self.offset = offset self.timeout = timeout def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_READ_ANDX def prepare(self, message): message.parameters_data = \ self.DEFAULT_ANDX_PARAM_HEADER + \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.fid, self.offset & 0xFFFFFFFF, self.max_return_bytes_count, self.min_return_bytes_count, self.timeout or (self.max_return_bytes_count >> 32), # Note that in [MS-SMB]: 2.2.4.2.1, this field can also act as MaxCountHigh field self.remaining, # In [MS-CIFS]: 2.2.4.42.1, this field must be set to 0x0000 self.offset >> 32) message.data = b'' class ComReadAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.42.2 - [MS-SMB]: 2.2.4.2.2 """ PAYLOAD_STRUCT_FORMAT = '<BBHHHHHHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_READ_ANDX if not message.status.hasError: if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB_COM_READ_ANDX parameters', message.raw_data, message) _, _, _, _, _, _, self.data_length, data_offset, _, _, _, _, _ = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) offset = data_offset - message.HEADER_STRUCT_SIZE - self.PAYLOAD_STRUCT_SIZE - 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) self.data = message.data[offset:offset+self.data_length] assert len(self.data) == self.data_length class ComDeleteRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.7.1 """ def __init__(self, filename_pattern, search_attributes = 0): self.filename_pattern = filename_pattern self.search_attributes = search_attributes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_DELETE def prepare(self, message): message.parameters_data = struct.pack('<H', self.search_attributes) message.data = b'\x04' + self.filename_pattern.encode('UTF-16LE') + b'\0\0' class ComCreateDirectoryRequest(Payload): """ Although this command has been marked deprecated in [MS-CIFS], we continue to use it for its simplicity as compared to its replacement TRANS2_CREATE_DIRECTORY sub-command [MS-CIFS]: 2.2.6.14 References: =========== - [MS-CIFS]: 2.2.4.1.1 """ def __init__(self, path): self.path = path def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_CREATE_DIRECTORY def prepare(self, message): message.parameters_data = b'' message.data = b'\x04' + self.path.encode('UTF-16LE') + b'\0\0' class ComDeleteDirectoryRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.2.1 """ def __init__(self, path): self.path = path def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_DELETE_DIRECTORY def prepare(self, message): message.parameters_data = b'' message.data = b'\x04' + self.path.encode('UTF-16LE') + b'\0\0' class ComRenameRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.8.1 """ def __init__(self, old_path, new_path, search_attributes = 0): self.old_path = old_path self.new_path = new_path self.search_attributes = search_attributes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_RENAME def prepare(self, message): message.parameters_data = struct.pack('<H', self.search_attributes) message.data = b'\x04' + self.old_path.encode('UTF-16LE') + b'\x00\x00\x04\x00' + self.new_path.encode('UTF-16LE') + b'\x00\x00' class ComEchoRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.39.1 """ def __init__(self, echo_data = b'', echo_count = 1): self.echo_count = echo_count self.echo_data = echo_data def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_ECHO message.tid = 0xFFFF def prepare(self, message): message.parameters_data = struct.pack('<H', self.echo_count) message.data = self.echo_data class ComEchoResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.39.2 """ def decode(self, message): self.sequence_number = struct.unpack('<H', message.parameters_data[:2])[0] self.data = message.data class ComNTTransactRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.62.1 """ PAYLOAD_STRUCT_FORMAT = '<BHIIIIIIIIBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, function, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, params_bytes = b'', setup_bytes = b'', data_bytes = b''): self.function = function self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) self.max_params_count = max_params_count self.max_data_count = max_data_count self.max_setup_count = max_setup_count self.params_bytes = params_bytes self.setup_bytes = setup_bytes self.data_bytes = data_bytes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_NT_TRANSACT def prepare(self, message): setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 4 != 0: padding0 = b'\0'*(4-offset%4) offset += (4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset else: params_bytes_offset = 0 offset += params_bytes_len padding1 = b'' if offset % 4 != 0: padding1 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2), self.function) + \ self.setup_bytes message.data = padding0 + self.params_bytes + padding1 + self.data_bytes class ComNTTransactResponse(Payload): """ Contains information about a SMB_COM_NT_TRANSACT response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.62.2 """ PAYLOAD_STRUCT_FORMAT = '<3sIIIIIIIIBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_NT_TRANSACT if not message.status.hasError: _, self.total_params_count, self.total_data_count, \ params_count, params_offset, params_displ, \ data_count, data_offset, data_displ, setup_count = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_count*2] if params_count > 0: params_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.params_bytes = message.data[params_offset:params_offset+params_count] else: self.params_bytes = b'' if data_count > 0: data_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.data_bytes = message.data[data_offset:data_offset+data_count] else: self.data_bytes = b''
================================================ FILE: docs/html/_sources/api/nmb_NBNSProtocol.rst.txt ================================================ NBNSProtocol Class ================== pysmb has a *NBNSProtocol* implementation for Twisted framework. This allows you to perform name query asynchronously without having your application to block and wait for the results. In your project, 1. Create a NBNSProtocol instance. 2. Just call *queryName* method which will return a *Deferred* instance. Add your callback function to the *Deferred* instance via *addCallback* method to receive the results of the name query. 3. When you are done with the NBNSProtocol instance, call its .transport.stopListening method to remove this instance from the reactor. .. autoclass:: nmb.NetBIOSProtocol.NBNSProtocol :members: :special-members: .. autoclass:: nmb.NetBIOSProtocol.NetBIOSTimeout :members: ================================================ FILE: docs/html/_sources/api/nmb_NBNSProtocol.txt ================================================ NBNSProtocol Class ================== pysmb has a *NBNSProtocol* implementation for Twisted framework. This allows you to perform name query asynchronously without having your application to block and wait for the results. In your project, 1. Create a NBNSProtocol instance. 2. Just call *queryName* method which will return a *Deferred* instance. Add your callback function to the *Deferred* instance via *addCallback* method to receive the results of the name query. 3. When you are done with the NBNSProtocol instance, call its .transport.stopListening method to remove this instance from the reactor. .. autoclass:: nmb.NetBIOSProtocol.NBNSProtocol :members: :special-members: .. autoclass:: nmb.NetBIOSProtocol.NetBIOSTimeout :members: ================================================ FILE: docs/html/_sources/api/nmb_NetBIOS.rst.txt ================================================ NetBIOS class ============= To use the NetBIOS class in your application, 1. Create a new NetBIOS instance 2. Call *queryName* method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout. 3. When you are done, call *close* method to release the underlying resources. .. autoclass:: nmb.NetBIOS.NetBIOS :members: :special-members: ================================================ FILE: docs/html/_sources/api/nmb_NetBIOS.txt ================================================ NetBIOS class ============= To use the NetBIOS class in your application, 1. Create a new NetBIOS instance 2. Call *queryName* method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout. 3. When you are done, call *close* method to release the underlying resources. .. autoclass:: nmb.NetBIOS.NetBIOS :members: :special-members: ================================================ FILE: docs/html/_sources/api/smb_SMBConnection.rst.txt ================================================ SMBConnection Class =================== The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially. Each file operation method, when invoked, will block and return after it has completed or has encountered an error. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from smb.SMBConnection import SMBConnection # 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) assert 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() SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBConnection* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * It is not meant to be used asynchronously. * A single *SMBConnection* instance should not be used to perform more than one operation concurrently at the same time. * Do not keep a *SMBConnection* instance "idle" for too long, i.e. keeping a *SMBConnection* instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client. .. autoclass:: smb.SMBConnection.SMBConnection :members: :special-members: ================================================ FILE: docs/html/_sources/api/smb_SMBConnection.txt ================================================ SMBConnection Class =================== The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially. Each file operation method, when invoked, will block and return after it has completed or has encountered an error. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from smb.SMBConnection import SMBConnection # 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) assert 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() SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBConnection* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * It is not meant to be used asynchronously. * A single *SMBConnection* instance should not be used to perform more than one operation concurrently at the same time. * Do not keep a *SMBConnection* instance "idle" for too long, i.e. keeping a *SMBConnection* instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client. .. autoclass:: smb.SMBConnection.SMBConnection :members: :special-members: ================================================ FILE: docs/html/_sources/api/smb_SMBHandler.rst.txt ================================================ SMbHandler Class ================ The SMBHandler class provides support for "smb://" URLs in the `urllib2 `_ python package. Notes ----- * The host component of the URL must be one of the following: * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com * An IP address. Example: 192.168.1.1 * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 * The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file. * You can retrieve and upload files, but you cannot delete files/folders or create folders. In uploads, if the parent folders do not exist, an *urllib2.URLError* will be raised. Example ------- The following code snippet illustrates file retrieval with Python 2.:: # -*- coding: utf-8 -*- import urllib2 from smb.SMBHandler import SMBHandler director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib2 from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() The following code snippet illustrates file retrieval with Python 3.:: import urllib from smb.SMBHandler import SMBHandler director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() ================================================ FILE: docs/html/_sources/api/smb_SMBHandler.txt ================================================ SMbHandler Class ================ The SMBHandler class provides support for "smb://" URLs in the `urllib2 `_ python package. Notes ----- * The host component of the URL must be one of the following: * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com * An IP address. Example: 192.168.1.1 * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 * The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file. * You can retrieve and upload files, but you cannot delete files/folders or create folders. In uploads, if the parent folders do not exist, an *urllib2.URLError* will be raised. Example ------- The following code snippet illustrates file retrieval with Python 2.:: # -*- coding: utf-8 -*- import urllib2 from smb.SMBHandler import SMBHandler director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib2 from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() The following code snippet illustrates file retrieval with Python 3.:: import urllib from smb.SMBHandler import SMBHandler director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() ================================================ FILE: docs/html/_sources/api/smb_SMBProtocolFactory.rst.txt ================================================ SMBProtocolFactory Class ======================== For those who want to utilize pysmb in Twisted framework, pysmb has a *smb.SMBProtocol.SMBProtocol* implementation. In most cases, you do not need to touch or import the *SMBProtocol* directly. All the SMB functionalities are exposed in the *SMBProtocolFactory*. In your project, 1. Create a new class and subclass *SMBProtocolFactory*. 2. Override the *SMBProtocolFactory.onAuthOK* and *SMBProtocolFactory.onAuthFailed* instance methods to provide your own post-authenthentication handling. Once *SMBProtocolFactory.onAuthOK* has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through the *SMBProtocolFactory* public methods such as *SMBProtocolFactory.storeFile*, *SMBProtocolFactory.retrieveFile*, etc. 3. When you want to disconnect from the remote SMB/CIFS server, just call *SMBProtocolFactory.closeConnection* method. All the *SMBProtocolFactory* public methods that provide file functionlities will return a *twisted.internet.defer.Deferred* instance. A :doc:`NotReadyError` exception is raised when the underlying SMB is not authenticated. If the underlying SMB connection has been terminated, a :doc:`NotConnectedError` exception is raised. All the file operation methods in *SMBProtocolFactory* class accept a *timeout* parameter. This parameter specifies the time limit where pysmb will wait for the entire file operation (except *storeFile* and *retrieveFile* methods) to complete. If the file operation fails to complete within the timeout period, the returned *Deferred* instance's *errback* method will be called with a *SMBTimeout* exception. If you are interested in learning the results of the operation or to know when the operation has completed, you should add a handling method to the returned *Deferred* instance via *Deferred.addCallback*. If the file operation fails, the *Deferred.errback* function will be called with an :doc:`OperationFailure`; on timeout, it will be called with a :doc:`SMBTimeout`. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from twisted.internet import reactor from smb.SMBProtocol import SMBProtocolFactory class RetrieveFileFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) def fileRetrieved(self, write_result): file_obj, file_attributes, file_size = write_result # 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() to if you # need to read from the beginning file_obj.close() self.transport.loseConnection() def onAuthOK(self): d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile()) d.addCallback(self.fileRetrieved) d.addErrback(self.d.errback) def onAuthFailed(self): print 'Auth failed' # 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 factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(server_ip, 139, factory) SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBProtocolFactory* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection. * The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call *storeFile* or *retrieveFile* in batches. * The *timeout* parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise *SMBTimeout* exception after 1.5 sec. .. autoclass:: smb.SMBProtocol.SMBProtocolFactory :members: :special-members: ================================================ FILE: docs/html/_sources/api/smb_SMBProtocolFactory.txt ================================================ SMBProtocolFactory Class ======================== For those who want to utilize pysmb in Twisted framework, pysmb has a *smb.SMBProtocol.SMBProtocol* implementation. In most cases, you do not need to touch or import the *SMBProtocol* directly. All the SMB functionalities are exposed in the *SMBProtocolFactory*. In your project, 1. Create a new class and subclass *SMBProtocolFactory*. 2. Override the *SMBProtocolFactory.onAuthOK* and *SMBProtocolFactory.onAuthFailed* instance methods to provide your own post-authenthentication handling. Once *SMBProtocolFactory.onAuthOK* has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through the *SMBProtocolFactory* public methods such as *SMBProtocolFactory.storeFile*, *SMBProtocolFactory.retrieveFile*, etc. 3. When you want to disconnect from the remote SMB/CIFS server, just call *SMBProtocolFactory.closeConnection* method. All the *SMBProtocolFactory* public methods that provide file functionlities will return a *twisted.internet.defer.Deferred* instance. A :doc:`NotReadyError` exception is raised when the underlying SMB is not authenticated. If the underlying SMB connection has been terminated, a :doc:`NotConnectedError` exception is raised. All the file operation methods in *SMBProtocolFactory* class accept a *timeout* parameter. This parameter specifies the time limit where pysmb will wait for the entire file operation (except *storeFile* and *retrieveFile* methods) to complete. If the file operation fails to complete within the timeout period, the returned *Deferred* instance's *errback* method will be called with a *SMBTimeout* exception. If you are interested in learning the results of the operation or to know when the operation has completed, you should add a handling method to the returned *Deferred* instance via *Deferred.addCallback*. If the file operation fails, the *Deferred.errback* function will be called with an :doc:`OperationFailure`; on timeout, it will be called with a :doc:`SMBTimeout`. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from twisted.internet import reactor from smb.SMBProtocol import SMBProtocolFactory class RetrieveFileFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) def fileRetrieved(self, write_result): file_obj, file_attributes, file_size = write_result # 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() to if you # need to read from the beginning file_obj.close() self.transport.loseConnection() def onAuthOK(self): d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile()) d.addCallback(self.fileRetrieved) d.addErrback(self.d.errback) def onAuthFailed(self): print 'Auth failed' # 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 factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(server_ip, 139, factory) SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBProtocolFactory* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection. * The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call *storeFile* or *retrieveFile* in batches. * The *timeout* parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise *SMBTimeout* exception after 1.5 sec. .. autoclass:: smb.SMBProtocol.SMBProtocolFactory :members: :special-members: ================================================ FILE: docs/html/_sources/api/smb_SharedDevice.rst.txt ================================================ SharedDevice Class ================== .. autoclass:: smb.base.SharedDevice :members: ================================================ FILE: docs/html/_sources/api/smb_SharedDevice.txt ================================================ SharedDevice Class ================== .. autoclass:: smb.base.SharedDevice :members: ================================================ FILE: docs/html/_sources/api/smb_SharedFile.rst.txt ================================================ SharedFile Class ================ .. autoclass:: smb.base.SharedFile :members: ================================================ FILE: docs/html/_sources/api/smb_SharedFile.txt ================================================ SharedFile Class ================ .. autoclass:: smb.base.SharedFile :members: ================================================ FILE: docs/html/_sources/api/smb_exceptions.rst.txt ================================================ SMB Exceptions ============== .. autoclass:: smb.base.SMBTimeout :members: .. autoclass:: smb.base.NotReadyError :members: .. autoclass:: smb.base.NotConnectedError :members: .. autoclass:: smb.smb_structs.UnsupportedFeature :members: .. autoclass:: smb.smb_structs.ProtocolError :members: .. autoclass:: smb.smb_structs.OperationFailure :members: ================================================ FILE: docs/html/_sources/api/smb_exceptions.txt ================================================ SMB Exceptions ============== .. autoclass:: smb.base.SMBTimeout :members: .. autoclass:: smb.base.NotReadyError :members: .. autoclass:: smb.base.NotConnectedError :members: .. autoclass:: smb.smb_structs.UnsupportedFeature :members: .. autoclass:: smb.smb_structs.ProtocolError :members: .. autoclass:: smb.smb_structs.OperationFailure :members: ================================================ FILE: docs/html/_sources/api/smb_security_descriptors.rst.txt ================================================ Security Descriptors ==================== .. module:: smb.security_descriptors :synopsis: Data structures used in Windows security descriptors. This module implements security descriptors, and associated data structures, as specified in `[MS-DTYP]`_. .. autoclass:: SID :members: .. autoclass:: ACE :members: .. autoclass:: ACL :members: .. autoclass:: SecurityDescriptor :members: .. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx ================================================ FILE: docs/html/_sources/api/smb_security_descriptors.txt ================================================ Security Descriptors ==================== .. module:: smb.security_descriptors :synopsis: Data structures used in Windows security descriptors. This module implements security descriptors, and associated data structures, as specified in `[MS-DTYP]`_. .. autoclass:: SID :members: .. autoclass:: ACE :members: .. autoclass:: ACL :members: .. autoclass:: SecurityDescriptor :members: .. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx ================================================ FILE: docs/html/_sources/extending.rst.txt ================================================ Extending pysmb For Other Frameworks ==================================== This page briefly describes the steps involved in extending pysmb for other frameworks. In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, initiate file operations with the remote SMB/CIFS server. Now the above steps in more technical details: 1. Create a new class which subclasses the *smb.base.SMB* class. Most often, the connection setup will be part of the *__init__* method. 2. Override the *write(self, data)* method to provide an implementation which will write *data* to the socket. 3. Write your own loop handling method to read data from the socket. Once data have been read, call *feedData* method with the parameter. The *feedData* method has its own internal buffer, so it can accept incomplete NetBIOS session packet data. 4. Override * *onAuthOK* method to include your own operations to perform when authentication is successful. You can initiate file operations in this method. * *onAuthFailed* method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (*use_ntlm_v2* parameter in the constructor). * *onNMBSessionFailed* method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong *remote_name* parameter in the constructor. ================================================ FILE: docs/html/_sources/extending.txt ================================================ Extending pysmb For Other Frameworks ==================================== This page briefly describes the steps involved in extending pysmb for other frameworks. In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, initiate file operations with the remote SMB/CIFS server. Now the above steps in more technical details: 1. Create a new class which subclasses the *smb.base.SMB* class. Most often, the connection setup will be part of the *__init__* method. 2. Override the *write(self, data)* method to provide an implementation which will write *data* to the socket. 3. Write your own loop handling method to read data from the socket. Once data have been read, call *feedData* method with the parameter. The *feedData* method has its own internal buffer, so it can accept incomplete NetBIOS session packet data. 4. Override * *onAuthOK* method to include your own operations to perform when authentication is successful. You can initiate file operations in this method. * *onAuthFailed* method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (*use_ntlm_v2* parameter in the constructor). * *onNMBSessionFailed* method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong *remote_name* parameter in the constructor. ================================================ FILE: docs/html/_sources/index.rst.txt ================================================ Welcome to pysmb's documentation! ================================= pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x. The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. License ------- pysmb itself is licensed under an opensource license. You are free to use pysmb in any applications, including for commercial purposes. For more details on the terms of use, please read the LICENSE file that comes with your pysmb source. pysmb depends on other 3rd-party modules whose terms of use are not covered by pysmb. Use of these modules could possibly conflict with your licensing needs. Please exercise your own discretion to determine their suitabilities. I have listed these modules in the following section. Credits ------- pysmb is not alone. It is made possible with support from other modules. * **pyasn1** : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately) * **md4** and **U32** : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb. * **pyDes** : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb. * **sha256** : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm. In various places, there are references to different specifications. Most of these referenced specifications can be downloaded from Microsoft web site under Microsoft's "Open Specification Promise". If you need to download a copy of these specifications, please google for it. For example, google for "MS-CIFS" to download the CIFS specification for NT LM dialect. Package Contents and Description ================================ pysmb is organized into 2 main packages: smb and nmb. The smb package contains all the functionalities related to Server Message Block (SMB) implementation. As an application developer, you will be importing this module into your application. Hence, please take some time to familiarize yourself with the smb package contents. * **nmb/base.py** : Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication without any network transport specifics. * **nmb/NetBIOS.py**: Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O. * **nmb/NetBIOSProtocol.py** : Provides the NBNS protocol implementation for use in Twisted framework. * **smb/base.py** : Contains the SMB abstract class which implements the SMB communication without any network transport specifics. * **smb/ntlm.py** : Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages. * **smb/securityblob.py** : Provides routines to encode/decode the NTLMSSP security blob in the SMB messages. * **smb/smb_constants.py** : All the constants used in the smb package for SMB1 protocol * **smb/smb_structs.py** : Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message. * **smb/smb2_constants.py** : All the constants used in the smb package for SMB2 protocol * **smb/smb2_structs.py** : Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message. * **smb/SMBConnection.py** : Contains a SMB protocol implementation. All operations are blocking I/O. * **smb/SMBProtocol.py** : Contains the SMB protocol implementation for use in the Twisted framework. * **smb/SMBHandler.py** : Provides support for "smb://" URL in the urllib2 python package. Using pysmb =========== As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses, * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`nmb.NetBIOS.NetBIOS` documentation. * To use pysmb in Twisted, please read :doc:`nmb.NetBIOSProtocol.NBNSProtocol` documentation. As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB: * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`smb.SMBConnection.SMBConnection` documentation. * To use pysmb in Twisted, please read :doc:`smb.SMBProtocol.SMBProtocolFactory` documentation. * To support "smb://" URL in urllib2 python package, read :doc:`smb.SMBHandler.SMBHandler` documentation. As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: * Read :doc:`extending` If you are upgrading from older pysmb versions: * Read :doc:`upgrading` Indices and tables ================== .. toctree:: :glob: :maxdepth: 1 api/* extending upgrading * :ref:`genindex` * :ref:`search` ================================================ FILE: docs/html/_sources/index.txt ================================================ .. pysmb documentation master file, created by sphinx-quickstart on Sun Dec 18 15:54:40 2011. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to pysmb's documentation! ================================= pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. pysmb is developed in Python 2.7.x and Python 3.5.x and has been tested against shared folders on Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x. The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. License ------- pysmb itself is licensed under an opensource license. You are free to use pysmb in any applications, including for commercial purposes. For more details on the terms of use, please read the LICENSE file that comes with your pysmb source. pysmb depends on other 3rd-party modules whose terms of use are not covered by pysmb. Use of these modules could possibly conflict with your licensing needs. Please exercise your own discretion to determine their suitabilities. I have listed these modules in the following section. Credits ------- pysmb is not alone. It is made possible with support from other modules. * **pyasn1** : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately) * **md4** and **U32** : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb. * **pyDes** : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb. * **sha256** : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm. In various places, there are references to different specifications. Most of these referenced specifications can be downloaded from Microsoft web site under Microsoft's "Open Specification Promise". If you need to download a copy of these specifications, please google for it. For example, google for "MS-CIFS" to download the CIFS specification for NT LM dialect. Package Contents and Description ================================ pysmb is organized into 2 main packages: smb and nmb. The smb package contains all the functionalities related to Server Message Block (SMB) implementation. As an application developer, you will be importing this module into your application. Hence, please take some time to familiarize yourself with the smb package contents. * **nmb/base.py** : Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication without any network transport specifics. * **nmb/NetBIOS.py**: Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O. * **nmb/NetBIOSProtocol.py** : Provides the NBNS protocol implementation for use in Twisted framework. * **smb/base.py** : Contains the SMB abstract class which implements the SMB communication without any network transport specifics. * **smb/ntlm.py** : Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages. * **smb/securityblob.py** : Provides routines to encode/decode the NTLMSSP security blob in the SMB messages. * **smb/smb_constants.py** : All the constants used in the smb package for SMB1 protocol * **smb/smb_structs.py** : Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message. * **smb/smb2_constants.py** : All the constants used in the smb package for SMB2 protocol * **smb/smb2_structs.py** : Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message. * **smb/SMBConnection.py** : Contains a SMB protocol implementation. All operations are blocking I/O. * **smb/SMBProtocol.py** : Contains the SMB protocol implementation for use in the Twisted framework. * **smb/SMBHandler.py** : Provides support for "smb://" URL in the urllib2 python package. Using pysmb =========== As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses, * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`nmb.NetBIOS.NetBIOS` documentation. * To use pysmb in Twisted, please read :doc:`nmb.NetBIOSProtocol.NBNSProtocol` documentation. As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB: * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`smb.SMBConnection.SMBConnection` documentation. * To use pysmb in Twisted, please read :doc:`smb.SMBProtocol.SMBProtocolFactory` documentation. * To support "smb://" URL in urllib2 python package, read :doc:`smb.SMBHandler.SMBHandler` documentation. As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: * Read :doc:`extending` If you are upgrading from older pysmb versions: * Read :doc:`upgrading` Indices and tables ================== .. toctree:: :glob: :maxdepth: 1 api/* extending upgrading * :ref:`genindex` * :ref:`search` ================================================ FILE: docs/html/_sources/upgrading.rst.txt ================================================ Upgrading from older pysmb versions ==================================== This page documents the improvements and changes to the API that could be incompatible with previous releases. pysmb 1.2.0 ----------- - Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.28 ------------ - SharedFile instances returned from the `listPath()` method now has a new property `file_id` attribute which represents the file reference number given by the remote SMB server. pysmb 1.1.26 ------------ - SMBConnection class can now be used as a context manager pysmb 1.1.25 ------------ - SharedFile class has a new property `isNormal` which will be True if the file is a 'normal' file. pysmb defines a 'normal' file as a file entry that is not read-only, not hidden, not system, not archive and not a directory; it ignores other attributes like compression, indexed, sparse, temporary and encryption. - `listPath()` method in SMBProtocolFactory and SMBConnection class will now include 'normal' files by default if you do not specify the `search` parameter. pysmb 1.1.20 ------------ - A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.15 ------------ - Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection class to support truncation of the file before writing. If you are passing timeout parameter to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.11 ------------ - A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.10 ------------ - A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class - SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. pysmb 1.1.2 ----------- - `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. pysmb 1.0.3 ----------- - Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` to support querying for a machine's NetBIOS name at the given IP address. - A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection to support finer control of file retrieval operation. pysmb 1.0.0 ----------- pysmb was completely rewritten in version 1.0.0. If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API. ================================================ FILE: docs/html/_sources/upgrading.txt ================================================ Upgrading from older pysmb versions ==================================== This page documents the improvements and changes to the API that could be incompatible with previous releases. pysmb 1.2.0 ----------- - Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.28 ------------ - SharedFile instances returned from the `listPath()` method now has a new property `file_id` attribute which represents the file reference number given by the remote SMB server. pysmb 1.1.26 ------------ - SMBConnection class can now be used as a context manager pysmb 1.1.25 ------------ - SharedFile class has a new property `isNormal` which will be True if the file is a 'normal' file. pysmb defines a 'normal' file as a file entry that is not read-only, not hidden, not system, not archive and not a directory; it ignores other attributes like compression, indexed, sparse, temporary and encryption. - `listPath()` method in SMBProtocolFactory and SMBConnection class will now include 'normal' files by default if you do not specify the `search` parameter. pysmb 1.1.20 ------------ - A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.15 ------------ - Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection class to support truncation of the file before writing. If you are passing timeout parameter to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.11 ------------ - A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.10 ------------ - A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class - SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. pysmb 1.1.2 ----------- - `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. pysmb 1.0.3 ----------- - Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` to support querying for a machine's NetBIOS name at the given IP address. - A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection to support finer control of file retrieval operation. pysmb 1.0.0 ----------- pysmb was completely rewritten in version 1.0.0. If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API. ================================================ FILE: docs/html/_static/_sphinx_javascript_frameworks_compat.js ================================================ /* * _sphinx_javascript_frameworks_compat.js * ~~~~~~~~~~ * * Compatability shim for jQuery and underscores.js. * * WILL BE REMOVED IN Sphinx 6.0 * xref RemovedInSphinx60Warning * */ /** * select a different prefix for underscore */ $u = _.noConflict(); /** * small helper function to urldecode strings * * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL */ jQuery.urldecode = function(x) { if (!x) { return x } return decodeURIComponent(x.replace(/\+/g, ' ')); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node, addItems) { if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className) && !jQuery(node.parentNode).hasClass("nohighlight")) { var span; var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); if (isInSVG) { span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); } else { span = document.createElement("span"); span.className = className; } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); if (isInSVG) { var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); var bbox = node.parentElement.getBBox(); rect.x.baseVal.value = bbox.x; rect.y.baseVal.value = bbox.y; rect.width.baseVal.value = bbox.width; rect.height.baseVal.value = bbox.height; rect.setAttribute('class', className); addItems.push({ "parent": node.parentNode, "target": rect}); } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this, addItems); }); } } var addItems = []; var result = this.each(function() { highlight(this, addItems); }); for (var i = 0; i < addItems.length; ++i) { jQuery(addItems[i].parent).before(addItems[i].target); } return result; }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } ================================================ FILE: docs/html/_static/basic.css ================================================ /* * basic.css * ~~~~~~~~~ * * Sphinx stylesheet -- basic theme. * * :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* -- main layout ----------------------------------------------------------- */ div.clearer { clear: both; } div.section::after { display: block; content: ''; clear: left; } /* -- relbar ---------------------------------------------------------------- */ div.related { width: 100%; font-size: 90%; } div.related h3 { display: none; } div.related ul { margin: 0; padding: 0 0 0 10px; list-style: none; } div.related li { display: inline; } div.related li.right { float: right; margin-right: 5px; } /* -- sidebar --------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 10px 5px 0 10px; } div.sphinxsidebar { float: left; width: 230px; margin-left: -100%; font-size: 90%; word-wrap: break-word; overflow-wrap : break-word; } div.sphinxsidebar ul { list-style: none; } div.sphinxsidebar ul ul, div.sphinxsidebar ul.want-points { margin-left: 20px; list-style: square; } div.sphinxsidebar ul ul { margin-top: 0; margin-bottom: 0; } div.sphinxsidebar form { margin-top: 10px; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } div.sphinxsidebar #searchbox form.search { overflow: hidden; } div.sphinxsidebar #searchbox input[type="text"] { float: left; width: 80%; padding: 0.25em; box-sizing: border-box; } div.sphinxsidebar #searchbox input[type="submit"] { float: left; width: 20%; border-left: none; padding: 0.25em; box-sizing: border-box; } img { border: 0; max-width: 100%; } /* -- search page ----------------------------------------------------------- */ ul.search { margin: 10px 0 0 20px; padding: 0; } ul.search li { padding: 5px 0 5px 20px; background-image: url(file.png); background-repeat: no-repeat; background-position: 0 7px; } ul.search li a { font-weight: bold; } ul.search li p.context { color: #888; margin: 2px 0 0 30px; text-align: left; } ul.keywordmatches li.goodmatch a { font-weight: bold; } /* -- index page ------------------------------------------------------------ */ table.contentstable { width: 90%; margin-left: auto; margin-right: auto; } table.contentstable p.biglink { line-height: 150%; } a.biglink { font-size: 1.3em; } span.linkdescr { font-style: italic; padding-top: 5px; font-size: 90%; } /* -- general index --------------------------------------------------------- */ table.indextable { width: 100%; } table.indextable td { text-align: left; vertical-align: top; } table.indextable ul { margin-top: 0; margin-bottom: 0; list-style-type: none; } table.indextable > tbody > tr > td > ul { padding-left: 0em; } table.indextable tr.pcap { height: 10px; } table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2; } img.toggler { margin-right: 3px; margin-top: 3px; cursor: pointer; } div.modindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } div.genindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } /* -- domain module index --------------------------------------------------- */ table.modindextable td { padding: 2px; border-collapse: collapse; } /* -- general body styles --------------------------------------------------- */ div.body { min-width: 360px; max-width: 800px; } div.body p, div.body dd, div.body li, div.body blockquote { -moz-hyphens: auto; -ms-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } a.headerlink { visibility: hidden; } a:visited { color: #551A8B; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink, caption:hover > a.headerlink, p.caption:hover > a.headerlink, div.code-block-caption:hover > a.headerlink { visibility: visible; } div.body p.caption { text-align: inherit; } div.body td { text-align: left; } .first { margin-top: 0 !important; } p.rubric { margin-top: 30px; font-weight: bold; } img.align-left, figure.align-left, .figure.align-left, object.align-left { clear: left; float: left; margin-right: 1em; } img.align-right, figure.align-right, .figure.align-right, object.align-right { clear: right; float: right; margin-left: 1em; } img.align-center, figure.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } img.align-default, figure.align-default, .figure.align-default { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left; } .align-center { text-align: center; } .align-default { text-align: center; } .align-right { text-align: right; } /* -- sidebars -------------------------------------------------------------- */ div.sidebar, aside.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; padding: 7px; background-color: #ffe; width: 40%; float: right; clear: right; overflow-x: auto; } p.sidebar-title { font-weight: bold; } nav.contents, aside.topic, div.admonition, div.topic, blockquote { clear: left; } /* -- topics ---------------------------------------------------------------- */ nav.contents, aside.topic, div.topic { border: 1px solid #ccc; padding: 7px; margin: 10px 0 10px 0; } p.topic-title { font-size: 1.1em; font-weight: bold; margin-top: 10px; } /* -- admonitions ----------------------------------------------------------- */ div.admonition { margin-top: 10px; margin-bottom: 10px; padding: 7px; } div.admonition dt { font-weight: bold; } p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; } div.body p.centered { text-align: center; margin-top: 25px; } /* -- content of sidebars/topics/admonitions -------------------------------- */ div.sidebar > :last-child, aside.sidebar > :last-child, nav.contents > :last-child, aside.topic > :last-child, div.topic > :last-child, div.admonition > :last-child { margin-bottom: 0; } div.sidebar::after, aside.sidebar::after, nav.contents::after, aside.topic::after, div.topic::after, div.admonition::after, blockquote::after { display: block; content: ''; clear: both; } /* -- tables ---------------------------------------------------------------- */ table.docutils { margin-top: 10px; margin-bottom: 10px; border: 0; border-collapse: collapse; } table.align-center { margin-left: auto; margin-right: auto; } table.align-default { margin-left: auto; margin-right: auto; } table caption span.caption-number { font-style: italic; } table caption span.caption-text { } table.docutils td, table.docutils th { padding: 1px 8px 1px 5px; border-top: 0; border-left: 0; border-right: 0; border-bottom: 1px solid #aaa; } th { text-align: left; padding-right: 5px; } table.citation { border-left: solid 1px gray; margin-left: 1px; } table.citation td { border-bottom: none; } th > :first-child, td > :first-child { margin-top: 0px; } th > :last-child, td > :last-child { margin-bottom: 0px; } /* -- figures --------------------------------------------------------------- */ div.figure, figure { margin: 0.5em; padding: 0.5em; } div.figure p.caption, figcaption { padding: 0.3em; } div.figure p.caption span.caption-number, figcaption span.caption-number { font-style: italic; } div.figure p.caption span.caption-text, figcaption span.caption-text { } /* -- field list styles ----------------------------------------------------- */ table.field-list td, table.field-list th { border: 0 !important; } .field-list ul { margin: 0; padding-left: 1em; } .field-list p { margin: 0; } .field-name { -moz-hyphens: manual; -ms-hyphens: manual; -webkit-hyphens: manual; hyphens: manual; } /* -- hlist styles ---------------------------------------------------------- */ table.hlist { margin: 1em 0; } table.hlist td { vertical-align: top; } /* -- object description styles --------------------------------------------- */ .sig { font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; } .sig-name, code.descname { background-color: transparent; font-weight: bold; } .sig-name { font-size: 1.1em; } code.descname { font-size: 1.2em; } .sig-prename, code.descclassname { background-color: transparent; } .optional { font-size: 1.3em; } .sig-paren { font-size: larger; } .sig-param.n { font-style: italic; } /* C++ specific styling */ .sig-inline.c-texpr, .sig-inline.cpp-texpr { font-family: unset; } .sig.c .k, .sig.c .kt, .sig.cpp .k, .sig.cpp .kt { color: #0033B3; } .sig.c .m, .sig.cpp .m { color: #1750EB; } .sig.c .s, .sig.c .sc, .sig.cpp .s, .sig.cpp .sc { color: #067D17; } /* -- other body styles ----------------------------------------------------- */ ol.arabic { list-style: decimal; } ol.loweralpha { list-style: lower-alpha; } ol.upperalpha { list-style: upper-alpha; } ol.lowerroman { list-style: lower-roman; } ol.upperroman { list-style: upper-roman; } :not(li) > ol > li:first-child > :first-child, :not(li) > ul > li:first-child > :first-child { margin-top: 0px; } :not(li) > ol > li:last-child > :last-child, :not(li) > ul > li:last-child > :last-child { margin-bottom: 0px; } ol.simple ol p, ol.simple ul p, ul.simple ol p, ul.simple ul p { margin-top: 0; } ol.simple > li:not(:first-child) > p, ul.simple > li:not(:first-child) > p { margin-top: 0; } ol.simple p, ul.simple p { margin-bottom: 0; } aside.footnote > span, div.citation > span { float: left; } aside.footnote > span:last-of-type, div.citation > span:last-of-type { padding-right: 0.5em; } aside.footnote > p { margin-left: 2em; } div.citation > p { margin-left: 4em; } aside.footnote > p:last-of-type, div.citation > p:last-of-type { margin-bottom: 0em; } aside.footnote > p:last-of-type:after, div.citation > p:last-of-type:after { content: ""; clear: both; } dl.field-list { display: grid; grid-template-columns: fit-content(30%) auto; } dl.field-list > dt { font-weight: bold; word-break: break-word; padding-left: 0.5em; padding-right: 5px; } dl.field-list > dd { padding-left: 0.5em; margin-top: 0em; margin-left: 0em; margin-bottom: 0em; } dl { margin-bottom: 15px; } dd > :first-child { margin-top: 0px; } dd ul, dd table { margin-bottom: 10px; } dd { margin-top: 3px; margin-bottom: 10px; margin-left: 30px; } .sig dd { margin-top: 0px; margin-bottom: 0px; } .sig dl { margin-top: 0px; margin-bottom: 0px; } dl > dd:last-child, dl > dd:last-child > :last-child { margin-bottom: 0; } dt:target, span.highlighted { background-color: #fbe54e; } rect.highlighted { fill: #fbe54e; } dl.glossary dt { font-weight: bold; font-size: 1.1em; } .versionmodified { font-style: italic; } .system-message { background-color: #fda; padding: 5px; border: 3px solid red; } .footnote:target { background-color: #ffa; } .line-block { display: block; margin-top: 1em; margin-bottom: 1em; } .line-block .line-block { margin-top: 0; margin-bottom: 0; margin-left: 1.5em; } .guilabel, .menuselection { font-family: sans-serif; } .accelerator { text-decoration: underline; } .classifier { font-style: oblique; } .classifier:before { font-style: normal; margin: 0 0.5em; content: ":"; display: inline-block; } abbr, acronym { border-bottom: dotted 1px; cursor: help; } .translated { background-color: rgba(207, 255, 207, 0.2) } .untranslated { background-color: rgba(255, 207, 207, 0.2) } /* -- code displays --------------------------------------------------------- */ pre { overflow: auto; overflow-y: hidden; /* fixes display issues on Chrome browsers */ } pre, div[class*="highlight-"] { clear: both; } span.pre { -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; white-space: nowrap; } div[class*="highlight-"] { margin: 1em 0; } td.linenos pre { border: 0; background-color: transparent; color: #aaa; } table.highlighttable { display: block; } table.highlighttable tbody { display: block; } table.highlighttable tr { display: flex; } table.highlighttable td { margin: 0; padding: 0; } table.highlighttable td.linenos { padding-right: 0.5em; } table.highlighttable td.code { flex: 1; overflow: hidden; } .highlight .hll { display: block; } div.highlight pre, table.highlighttable pre { margin: 0; } div.code-block-caption + div { margin-top: 0; } div.code-block-caption { margin-top: 1em; padding: 2px 5px; font-size: small; } div.code-block-caption code { background-color: transparent; } table.highlighttable td.linenos, span.linenos, div.highlight span.gp { /* gp: Generic.Prompt */ user-select: none; -webkit-user-select: text; /* Safari fallback only */ -webkit-user-select: none; /* Chrome/Safari */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* IE10+ */ } div.code-block-caption span.caption-number { padding: 0.1em 0.3em; font-style: italic; } div.code-block-caption span.caption-text { } div.literal-block-wrapper { margin: 1em 0; } code.xref, a code { background-color: transparent; font-weight: bold; } h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { background-color: transparent; } .viewcode-link { float: right; } .viewcode-back { float: right; font-family: sans-serif; } div.viewcode-block:target { margin: -1px -10px; padding: 0 10px; } /* -- math display ---------------------------------------------------------- */ img.math { vertical-align: middle; } div.body div.math p { text-align: center; } span.eqno { float: right; } span.eqno a.headerlink { position: absolute; z-index: 1; } div.math:hover a.headerlink { visibility: visible; } /* -- printout stylesheet --------------------------------------------------- */ @media print { div.document, div.documentwrapper, div.bodywrapper { margin: 0 !important; width: 100%; } div.sphinxsidebar, div.related, div.footer, #top-link { display: none; } } ================================================ FILE: docs/html/_static/doctools.js ================================================ /* * doctools.js * ~~~~~~~~~~~ * * Base JavaScript utilities for all Sphinx HTML documentation. * * :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ "use strict"; const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ "TEXTAREA", "INPUT", "SELECT", "BUTTON", ]); const _ready = (callback) => { if (document.readyState !== "loading") { callback(); } else { document.addEventListener("DOMContentLoaded", callback); } }; /** * Small JavaScript module for the documentation. */ const Documentation = { init: () => { Documentation.initDomainIndexTable(); Documentation.initOnKeyListeners(); }, /** * i18n support */ TRANSLATIONS: {}, PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), LOCALE: "unknown", // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext: (string) => { const translated = Documentation.TRANSLATIONS[string]; switch (typeof translated) { case "undefined": return string; // no translation case "string": return translated; // translation exists default: return translated[0]; // (singular, plural) translation tuple exists } }, ngettext: (singular, plural, n) => { const translated = Documentation.TRANSLATIONS[singular]; if (typeof translated !== "undefined") return translated[Documentation.PLURAL_EXPR(n)]; return n === 1 ? singular : plural; }, addTranslations: (catalog) => { Object.assign(Documentation.TRANSLATIONS, catalog.messages); Documentation.PLURAL_EXPR = new Function( "n", `return (${catalog.plural_expr})` ); Documentation.LOCALE = catalog.locale; }, /** * helper function to focus on search bar */ focusSearchBar: () => { document.querySelectorAll("input[name=q]")[0]?.focus(); }, /** * Initialise the domain index toggle buttons */ initDomainIndexTable: () => { const toggler = (el) => { const idNumber = el.id.substr(7); const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); if (el.src.substr(-9) === "minus.png") { el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; toggledRows.forEach((el) => (el.style.display = "none")); } else { el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; toggledRows.forEach((el) => (el.style.display = "")); } }; const togglerElements = document.querySelectorAll("img.toggler"); togglerElements.forEach((el) => el.addEventListener("click", (event) => toggler(event.currentTarget)) ); togglerElements.forEach((el) => (el.style.display = "")); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); }, initOnKeyListeners: () => { // only install a listener if it is really needed if ( !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS ) return; document.addEventListener("keydown", (event) => { // bail for input elements if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; // bail with special keys if (event.altKey || event.ctrlKey || event.metaKey) return; if (!event.shiftKey) { switch (event.key) { case "ArrowLeft": if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; const prevLink = document.querySelector('link[rel="prev"]'); if (prevLink && prevLink.href) { window.location.href = prevLink.href; event.preventDefault(); } break; case "ArrowRight": if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; const nextLink = document.querySelector('link[rel="next"]'); if (nextLink && nextLink.href) { window.location.href = nextLink.href; event.preventDefault(); } break; } } // some keyboard layouts may need Shift to get / switch (event.key) { case "/": if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; Documentation.focusSearchBar(); event.preventDefault(); } }); }, }; // quick alias for translations const _ = Documentation.gettext; _ready(Documentation.init); ================================================ FILE: docs/html/_static/documentation_options.js ================================================ const DOCUMENTATION_OPTIONS = { VERSION: '1.2.13', LANGUAGE: 'en', COLLAPSE_INDEX: false, BUILDER: 'html', FILE_SUFFIX: '.html', LINK_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt', NAVIGATION_WITH_KEYS: false, SHOW_SEARCH_SUMMARY: true, ENABLE_SEARCH_SHORTCUTS: true, }; ================================================ FILE: docs/html/_static/jquery-3.5.1.js ================================================ /*! * jQuery JavaScript Library v3.5.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2020-05-04T22:49Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function( array ) { return arr.flat.call( array ); } : function( array ) { return arr.concat.apply( [], array ); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. return typeof obj === "function" && typeof obj.nodeType !== "number"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var document = window.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.5.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.5 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: 2020-03-14 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; return nonHex ? // Strip the backslash prefix from a non-hex escape sequence nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { setDocument( context ); context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. if ( newContext !== context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9 - 11+, Edge 12 - 18+ // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( preferredDoc != document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, // Safari 4 - 5 only, Opera <=11.6 - 12.x only // IE/Edge & older browsers don't support the :scope pseudo-class. // Support: Safari 6.0 only // Safari 6.0 supports :scope but it's an alias of :root there. support.scope = assert( function( el ) { docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll( ":scope fieldset div" ).length; } ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { var input; // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Support: IE 11+, Edge 15 - 18+ // IE 11/Edge don't find elements on a `[name='']` query in some cases. // Adding a temporary attribute to the document before the selection works // around the issue. // Interestingly, IE 10 & older don't seem to have the issue. input = document.createElement( "input" ); input.setAttribute( "name", "" ); el.appendChild( input ); if ( !el.querySelectorAll( "[name='']" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } // Support: Firefox <=3.6 - 5 only // Old Firefox doesn't throw on a badly-escaped identifier. el.querySelectorAll( "\\\f" ); rbuggyQSA.push( "[\\r\\n\\f]" ); } ); assert( function( el ) { el.innerHTML = "" + ""; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( a == document || a.ownerDocument == preferredDoc && contains( preferredDoc, a ) ) { return -1; } // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( b == document || b.ownerDocument == preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ return a == document ? -1 : b == document ? 1 : /* eslint-enable eqeqeq */ aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ ap[ i ] == preferredDoc ? -1 : bp[ i ] == preferredDoc ? 1 : /* eslint-enable eqeqeq */ 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { setDocument( elem ); if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( context.ownerDocument || context ) != document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( elem.ownerDocument || elem ) != document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq outermostContext = context == document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( !context && elem.ownerDocument != document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = ""; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = ""; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } return Sizzle; } )( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, _i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, _i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, _i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( elem.contentDocument != null && // Support: IE 11+ // elements with no `data` attribute has an object // `contentDocument` with a `null` prototype. getProto( elem.contentDocument ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( _i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // rejected_handlers.disable // fulfilled_handlers.disable tuples[ 3 - i ][ 3 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock, // progress_handlers.lock tuples[ 0 ][ 3 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, _key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; // Matches dashed string for camelizing var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( _all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 // Microsoft forgot to hump their vendor prefix (#9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var documentElement = document.documentElement; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }, composed = { composed: true }; // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only // Check attachment across shadow DOM boundaries when possible (gh-3504) // Support: iOS 10.0-10.2 only // Early iOS 10 versions support `attachShadow` but not `getRootNode`, // leading to errors. We need to check for `getRootNode`. if ( documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }; } var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = elem.nodeType && ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Support: Firefox <=54 // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) initial = initial / 2; // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; while ( maxIterations-- ) { // Evaluate and update our best guess (doubling guesses that zero out). // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style( elem, prop, initialInUnit + unit ); // Make sure we update the tween properties later on valueParts = valueParts || []; } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // Support: IE <=9 only // IE <=9 replaces "; support.option = !!div.lastChild; } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting or other required elements. thead: [ 1, "", "
" ], col: [ 2, "", "
" ], tr: [ 2, "", "
" ], td: [ 3, "", "
" ], _default: [ 0, "", "" ] }; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: IE <=9 only if ( !support.option ) { wrapMap.optgroup = wrapMap.option = [ 1, "" ]; } function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( attached ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 - 11+ // focus() and blur() are asynchronous, except when they are no-op. // So expect focus to be synchronous when the element is already active, // and blur to be synchronous when the element is not already active. // (focus and blur are always synchronous in other supported browsers, // this just defines when we can count on it). function expectSync( elem, type ) { return ( elem === safeActiveElement() ) === ( type === "focus" ); } // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Only attach events to objects that accept data if ( !acceptData( elem ) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = Object.create( null ); } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( nativeEvent ), handlers = ( dataPriv.get( this, "events" ) || Object.create( null ) )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // If the event is namespaced, then each handler is only invoked if it is // specially universal or its namespaces are a superset of the event's. if ( !event.rnamespace || handleObj.namespace === false || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // Utilize native event to ensure correct state for checkable inputs setup: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }, trigger: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Force setup before triggering a click if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { leverageNative( el, "click" ); } // Return non-false to allow normal event-path propagation return true; }, // For cross-browser consistency, suppress native .click() on links // Also prevent it if we're currently inside a leveraged native-event stack _default: function( event ) { var target = event.target; return rcheckableType.test( target.type ) && target.click && nodeName( target, "input" ) && dataPriv.get( target, "click" ) || nodeName( target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; // Ensure the presence of an event listener that handles manually-triggered // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. function leverageNative( el, type, expectSync ) { // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add if ( !expectSync ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } return; } // Register the controller as a special universal handler for all event namespaces dataPriv.set( el, type, false ); jQuery.event.add( el, type, { namespace: false, handler: function( event ) { var notAsync, result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event // Saved data should be false in such cases, but might be a leftover capture object // from an async native handler (gh-4350) if ( !saved.length ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array // will not be confused with a leftover capture object. saved = slice.call( arguments ); dataPriv.set( this, type, saved ); // Trigger the native event and capture its result // Support: IE <=9 - 11+ // focus() and blur() are asynchronous notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); if ( saved !== result || notAsync ) { dataPriv.set( this, type, false ); } else { result = {}; } if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); return result.value; } // If this is an inner synthetic event for an event with a bubbling surrogate // (focus or blur), assume that the surrogate already propagated from triggering the // native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { event.stopPropagation(); } // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments } else if ( saved.length ) { // ...and capture the result dataPriv.set( this, type, { value: jQuery.event.trigger( // Support: IE <=9 - 11+ // Extend with the prototype to reset the above stopImmediatePropagation() jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), saved.slice( 1 ), this ) } ); // Abort handling of the native event event.stopImmediatePropagation(); } } } ); } jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) leverageNative( this, type, expectSync ); // Return false to allow normal processing in the caller return false; }, trigger: function() { // Force setup before trigger leverageNative( this, type ); // Return non-false to allow normal event-path propagation return true; }, delegateType: delegateType }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.get( src ); events = pdataOld.events; if ( events ) { dataPriv.remove( dest, "handle events" ); for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = flat( args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl && !node.noModule ) { jQuery._evalUrl( node.src, { nonce: node.nonce || node.getAttribute( "nonce" ) }, doc ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html; }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%"; documentElement.appendChild( container ).appendChild( div ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 // Some styles come back with percentage values, even though they shouldn't div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; // Support: IE 9 - 11 only // Detect misreporting of content dimensions for box-sizing:border-box elements boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; // Support: IE 9 only // Detect overflow:scroll screwiness (gh-3699) // Support: Chrome <=64 // Don't get tricked when zoom affects offsetWidth (gh-4029) div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } function roundPixelMeasures( measure ) { return Math.round( parseFloat( measure ) ); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend( support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; }, // Support: IE 9 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Behavior in IE 9 is more subtle than in newer versions & it passes // some versions of this test; make sure not to make it pass there! reliableTrDimensions: function() { var table, tr, trChild, trStyle; if ( reliableTrDimensionsVal == null ) { table = document.createElement( "table" ); tr = document.createElement( "tr" ); trChild = document.createElement( "div" ); table.style.cssText = "position:absolute;left:-11111px"; tr.style.height = "1px"; trChild.style.height = "9px"; documentElement .appendChild( table ) .appendChild( tr ) .appendChild( trChild ); trStyle = window.getComputedStyle( tr ); reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; documentElement.removeChild( table ); } return reliableTrDimensionsVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style, vendorProps = {}; // Return a vendor-prefixed property or undefined function vendorPropName( name ) { // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a potentially-mapped jQuery.cssProps or vendor prefixed property function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( _elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin if ( box === "margin" ) { delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Support: Firefox <=54 // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } // Support: IE 9 - 11 only // Use offsetWidth/offsetHeight for when box sizing is unreliable. // In those cases, the computed value can be trusted to be border-box. if ( ( !support.boxSizingReliable() && isBorderBox || // Support: IE 10 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Interestingly, in some cases IE 9 doesn't suffer from this issue. !support.reliableTrDimensions() && nodeName( elem, "tr" ) || // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) val === "auto" || // Support: Android <=4.1 - 4.3 only // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && // Make sure the element is visible & connected elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "gridArea": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnStart": true, "gridRow": true, "gridRowEnd": true, "gridRowStart": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append // "px" to a few hardcoded values. if ( type === "number" && !isCustomProp ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( _i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // Only read styles.position if the test has a chance to fail // to avoid forcing a reflow. scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Account for unreliable border-box dimensions by comparing offset* to computed and // faking a content-box to get border and padding (gh-3699) if ( isBorderBox && scrollboxSizeBuggy ) { subtract -= Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - parseFloat( styles[ dimension ] ) - boxModelAdjustment( elem, dimension, "border", false, styles ) - 0.5 ); } // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( jQuery.cssHooks[ tween.prop ] || tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = Date.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 15 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY and Edge just mirrors // the overflowX value there. opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = result.stop.bind( result ); } return result; } } jQuery.map( props, createTween, animation ); if ( isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = Date.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } function classesToArray( value ) { if ( Array.isArray( value ) ) { return value; } if ( typeof value === "string" ) { return value.match( rnothtmlwhite ) || []; } return []; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isValidValue = type === "string" || Array.isArray( value ); if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, valueIsFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( valueIsFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion support.focusin = "onfocusin" in window; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function( e ) { e.stopPropagation(); }; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = lastElement = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { // Handle: regular nodes (via `this.ownerDocument`), window // (via `this.document`) & document (via `this`). var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = { guid: Date.now() }; var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && toType( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; if ( a == null ) { return ""; } // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( _i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() + " " ] = ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) .concat( match[ 2 ] ); } } match = responseHeaders[ key.toLowerCase() + " " ]; } return match == null ? null : match.join( ", " ); }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 15 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available and should be processed, append data to url if ( s.data && ( s.processData || typeof s.data === "string" ) ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Use a noop converter for missing script if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { s.converters[ "text script" ] = function() {}; } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( _i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery.ajaxPrefilter( function( s ) { var i; for ( i in s.headers ) { if ( i.toLowerCase() === "content-type" ) { s.contentType = s.headers[ i ] || ""; } } } ); jQuery._evalUrl = function( url, options, doc ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, // Only evaluate the response if it is successful (gh-4126) // dataFilter is not invoked for failure responses, so using it instead // of the default converter is kludgy but it works. converters: { "text script": function() {} }, dataFilter: function( response ) { jQuery.globalEval( response, options, doc ); } } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var htmlIsFunction = isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain or forced-by-attrs requests if ( s.crossDomain || s.scriptAttrs ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "

NBNSProtocol Class

pysmb has a NBNSProtocol implementation for Twisted framework. This allows you to perform name query asynchronously without having your application to block and wait for the results.

In your project,
  1. Create a NBNSProtocol instance.

  2. Just call queryName method which will return a Deferred instance. Add your callback function to the Deferred instance via addCallback method to receive the results of the name query.

  3. When you are done with the NBNSProtocol instance, call its <NBNSProtocol instance>.transport.stopListening method to remove this instance from the reactor.

================================================ FILE: docs/html/api/nmb_NetBIOS.html ================================================ NetBIOS class — pysmb 1.2.13 documentation

NetBIOS class

To use the NetBIOS class in your application,
  1. Create a new NetBIOS instance

  2. Call queryName method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout.

  3. When you are done, call close method to release the underlying resources.

class nmb.NetBIOS.NetBIOS(broadcast=True, listen_port=0)[source]
__init__(broadcast=True, listen_port=0)[source]

Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets.

Parameters:
  • broadcast (boolean) – A boolean flag to indicate if we should setup the listening UDP port in broadcast mode

  • listen_port (integer) – Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.

close()[source]

Close the underlying and free resources.

The NetBIOS instance should not be used to perform any operations after this method returns.

Returns:

None

queryIPForName(ip, port=137, timeout=30)[source]

Send a query to the machine with ip and hopes that the machine will reply back with its name.

The implementation of this function is contributed by Jason Anderson.

Parameters:
  • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

  • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

  • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None

Returns:

A list of string containing the names of the machine at ip. On timeout, returns None.

queryName(name, ip='', port=137, timeout=30)[source]

Send a query on the network and hopes that if machine matching the name will reply with its IP address.

Parameters:
  • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

  • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

  • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None

Returns:

A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None.

================================================ FILE: docs/html/api/smb_SMBConnection.html ================================================ SMBConnection Class — pysmb 1.2.13 documentation

SMBConnection Class

The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially.

Each file operation method, when invoked, will block and return after it has completed or has encountered an error.

Example

The following illustrates a simple file retrieving implementation.:

import tempfile
from smb.SMBConnection import SMBConnection

# 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)
assert 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()

SMB2 Support

Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol.

To disable SMB2 protocol in pysmb, set the SUPPORT_SMB2 flag in the smb_structs module to False before creating the SMBConnection instance.:

from smb import smb_structs
smb_structs.SUPPORT_SMB2 = False

Caveats

  • It is not meant to be used asynchronously.

  • A single SMBConnection instance should not be used to perform more than one operation concurrently at the same time.

  • Do not keep a SMBConnection instance “idle” for too long, i.e. keeping a SMBConnection instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client.

================================================ FILE: docs/html/api/smb_SMBHandler.html ================================================ SMbHandler Class — pysmb 1.2.13 documentation

SMbHandler Class

The SMBHandler class provides support for “smb://” URLs in the urllib2 python package.

Notes

  • The host component of the URL must be one of the following:

    • A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com

    • An IP address. Example: 192.168.1.1

    • A comma-separated string “<NBName>,<IP>” where <NBName> is the Windows/NetBIOS machine name for remote SMB service, and <IP> is the service’s IP address. Example: MYSERVER,192.168.1.1

  • The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file.

  • You can retrieve and upload files, but you cannot delete files/folders or create folders. In uploads, if the parent folders do not exist, an urllib2.URLError will be raised.

Example

The following code snippet illustrates file retrieval with Python 2.:

# -*- coding: utf-8 -*-
import urllib2
from smb.SMBHandler import SMBHandler

director = urllib2.build_opener(SMBHandler)
fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt')

# Process fh like a file-like object and then close it.
fh.close()

# For paths/files with unicode characters, simply pass in the URL as an unicode string
fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat')

# Process fh2 like a file-like object and then close it.
fh2.close()

The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the data parameter in the open() method:

import urllib2
from smb.SMBHandler import SMBHandler

file_fh = open('local_file.dat', 'rb')

director = urllib2.build_opener(SMBHandler)
fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh)

# Reading from fh will only return an empty string
fh.close()

The following code snippet illustrates file retrieval with Python 3.:

import urllib
from smb.SMBHandler import SMBHandler

director = urllib.request.build_opener(SMBHandler)
fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt')

# Process fh like a file-like object and then close it.
fh.close()

# For paths/files with unicode characters, simply pass in the URL as an unicode string
fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat')

# Process fh2 like a file-like object and then close it.
fh2.close()

The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the data parameter in the open() method:

import urllib
from smb.SMBHandler import SMBHandler

file_fh = open('local_file.dat', 'rb')

director = urllib.request.build_opener(SMBHandler)
fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh)

# Reading from fh will only return an empty string
fh.close()
================================================ FILE: docs/html/api/smb_SMBProtocolFactory.html ================================================ SMBProtocolFactory Class — pysmb 1.2.13 documentation

SMBProtocolFactory Class

For those who want to utilize pysmb in Twisted framework, pysmb has a smb.SMBProtocol.SMBProtocol implementation. In most cases, you do not need to touch or import the SMBProtocol directly. All the SMB functionalities are exposed in the SMBProtocolFactory.

In your project,
  1. Create a new class and subclass SMBProtocolFactory.

  2. Override the SMBProtocolFactory.onAuthOK and SMBProtocolFactory.onAuthFailed instance methods to provide your own post-authenthentication handling. Once SMBProtocolFactory.onAuthOK has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through the SMBProtocolFactory public methods such as SMBProtocolFactory.storeFile, SMBProtocolFactory.retrieveFile, etc.

  3. When you want to disconnect from the remote SMB/CIFS server, just call SMBProtocolFactory.closeConnection method.

All the SMBProtocolFactory public methods that provide file functionlities will return a twisted.internet.defer.Deferred instance. A NotReadyError exception is raised when the underlying SMB is not authenticated. If the underlying SMB connection has been terminated, a NotConnectedError exception is raised.

All the file operation methods in SMBProtocolFactory class accept a timeout parameter. This parameter specifies the time limit where pysmb will wait for the entire file operation (except storeFile and retrieveFile methods) to complete. If the file operation fails to complete within the timeout period, the returned Deferred instance’s errback method will be called with a SMBTimeout exception.

If you are interested in learning the results of the operation or to know when the operation has completed, you should add a handling method to the returned Deferred instance via Deferred.addCallback. If the file operation fails, the Deferred.errback function will be called with an OperationFailure; on timeout, it will be called with a SMBTimeout.

Example

The following illustrates a simple file retrieving implementation.:

import tempfile
from twisted.internet import reactor
from smb.SMBProtocol import SMBProtocolFactory

class RetrieveFileFactory(SMBProtocolFactory):

    def __init__(self, *args, **kwargs):
        SMBProtocolFactory.__init__(self, *args, **kwargs)

    def fileRetrieved(self, write_result):
        file_obj, file_attributes, file_size = write_result

        # 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() to if you
        # need to read from the beginning
        file_obj.close()

        self.transport.loseConnection()

    def onAuthOK(self):
        d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile())
        d.addCallback(self.fileRetrieved)
        d.addErrback(self.d.errback)

    def onAuthFailed(self):
        print 'Auth failed'

# 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
factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
factory.service = 'smbtest'
factory.path = '/rfc1001.txt'
reactor.connectTCP(server_ip, 139, factory)

SMB2 Support

Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol.

To disable SMB2 protocol in pysmb, set the SUPPORT_SMB2 flag in the smb_structs module to False before creating the SMBProtocolFactory instance.:

from smb import smb_structs
smb_structs.SUPPORT_SMB2 = False

Caveats

  • A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection.

  • The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call storeFile or retrieveFile in batches.

  • The timeout parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise SMBTimeout exception after 1.5 sec.

================================================ FILE: docs/html/api/smb_SharedDevice.html ================================================ SharedDevice Class — pysmb 1.2.13 documentation

SharedDevice Class

================================================ FILE: docs/html/api/smb_SharedFile.html ================================================ SharedFile Class — pysmb 1.2.13 documentation

SharedFile Class

================================================ FILE: docs/html/api/smb_exceptions.html ================================================ SMB Exceptions — pysmb 1.2.13 documentation

SMB Exceptions

class smb.smb_structs.UnsupportedFeature[source]

Raised when an supported feature is present/required in the protocol but is not currently supported by pysmb

class smb.smb_structs.ProtocolError(message, data_buf=None, smb_message=None)[source]
class smb.smb_structs.OperationFailure(message, smb_messages)[source]
================================================ FILE: docs/html/api/smb_security_descriptors.html ================================================ Security Descriptors — pysmb 1.2.13 documentation

Security Descriptors

This module implements security descriptors, and associated data structures, as specified in [MS-DTYP].

class smb.security_descriptors.SID(revision, identifier_authority, subauthorities)[source]

A Windows security identifier. Represents a single principal, such a user or a group, as a sequence of numbers consisting of the revision, identifier authority, and a variable-length list of subauthorities.

See [MS-DTYP]: 2.4.2

identifier_authority

An integer representing the identifier authority.

revision

Revision, should always be 1.

subauthorities

A list of integers representing all subauthorities.

class smb.security_descriptors.ACE(type_, flags, mask, sid, additional_data)[source]

Represents a single access control entry.

See [MS-DTYP]: 2.4.4

additional_data

A dictionary of additional fields present in the ACE, depending on the type. The following fields can be present:

  • flags

  • object_type

  • inherited_object_type

  • application_data

  • attribute_data

flags

An integer bitmask with ACE flags, corresponds to the AceFlags field.

property isInheritOnly

Convenience property which indicates if this ACE is inherit only, meaning that it doesn’t apply to the object itself.

mask

An integer representing the ACCESS_MASK as specified in [MS-DTYP] 2.4.3.

sid

The SID of a trustee.

type

An integer representing the type of the ACE. One of the ACE_TYPE_* constants. Corresponds to the AceType field from [MS-DTYP] 2.4.4.1.

class smb.security_descriptors.ACL(revision, aces)[source]

Access control list, encapsulating a sequence of access control entries.

See [MS-DTYP]: 2.4.5

aces

List of ACE instances.

revision

Integer value of the revision.

class smb.security_descriptors.SecurityDescriptor(flags, owner, group, dacl, sacl)[source]

Represents a security descriptor.

See [MS-DTYP]: 2.4.6

dacl

Instance of ACL representing the discretionary access control list, which specifies access restrictions of an object.

flags

Integer bitmask of control flags. Corresponds to the Control field in [MS-DTYP] 2.4.6.

group

Instance of SID representing the owner group.

owner

Instance of SID representing the owner user.

sacl

Instance of ACL representing the system access control list, which specifies audit logging of an object.

================================================ FILE: docs/html/extending.html ================================================ Extending pysmb For Other Frameworks — pysmb 1.2.13 documentation

Extending pysmb For Other Frameworks

This page briefly describes the steps involved in extending pysmb for other frameworks.

In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, initiate file operations with the remote SMB/CIFS server.

Now the above steps in more technical details:
  1. Create a new class which subclasses the smb.base.SMB class. Most often, the connection setup will be part of the __init__ method.

  2. Override the write(self, data) method to provide an implementation which will write data to the socket.

  3. Write your own loop handling method to read data from the socket. Once data have been read, call feedData method with the parameter. The feedData method has its own internal buffer, so it can accept incomplete NetBIOS session packet data.

  4. Override

  • onAuthOK method to include your own operations to perform when authentication is successful. You can initiate file operations in this method.

  • onAuthFailed method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (use_ntlm_v2 parameter in the constructor).

  • onNMBSessionFailed method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong remote_name parameter in the constructor.

================================================ FILE: docs/html/genindex.html ================================================ Index — pysmb 1.2.13 documentation

Index

_ | A | C | D | F | G | I | M | N | O | P | Q | R | S | T | U

_

A

C

D

F

G

I

M

N

O

P

Q

R

S

T

U

================================================ FILE: docs/html/index.html ================================================ Welcome to pysmb’s documentation! — pysmb 1.2.13 documentation

Welcome to pysmb’s documentation!

pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x.

The latest version of pysmb is always available at the pysmb project page at miketeo.net.

License

pysmb itself is licensed under an opensource license. You are free to use pysmb in any applications, including for commercial purposes. For more details on the terms of use, please read the LICENSE file that comes with your pysmb source.

pysmb depends on other 3rd-party modules whose terms of use are not covered by pysmb. Use of these modules could possibly conflict with your licensing needs. Please exercise your own discretion to determine their suitabilities. I have listed these modules in the following section.

Credits

pysmb is not alone. It is made possible with support from other modules.

  • pyasn1 : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately)

  • md4 and U32 : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb.

  • pyDes : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb.

  • sha256 : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm.

In various places, there are references to different specifications. Most of these referenced specifications can be downloaded from Microsoft web site under Microsoft’s “Open Specification Promise”. If you need to download a copy of these specifications, please google for it. For example, google for “MS-CIFS” to download the CIFS specification for NT LM dialect.

Package Contents and Description

pysmb is organized into 2 main packages: smb and nmb. The smb package contains all the functionalities related to Server Message Block (SMB) implementation. As an application developer, you will be importing this module into your application. Hence, please take some time to familiarize yourself with the smb package contents.

  • nmb/base.py : Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication without any network transport specifics.

  • nmb/NetBIOS.py: Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O.

  • nmb/NetBIOSProtocol.py : Provides the NBNS protocol implementation for use in Twisted framework.

  • smb/base.py : Contains the SMB abstract class which implements the SMB communication without any network transport specifics.

  • smb/ntlm.py : Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages.

  • smb/securityblob.py : Provides routines to encode/decode the NTLMSSP security blob in the SMB messages.

  • smb/smb_constants.py : All the constants used in the smb package for SMB1 protocol

  • smb/smb_structs.py : Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message.

  • smb/smb2_constants.py : All the constants used in the smb package for SMB2 protocol

  • smb/smb2_structs.py : Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message.

  • smb/SMBConnection.py : Contains a SMB protocol implementation. All operations are blocking I/O.

  • smb/SMBProtocol.py : Contains the SMB protocol implementation for use in the Twisted framework.

  • smb/SMBHandler.py : Provides support for “smb://” URL in the urllib2 python package.

Using pysmb

As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses,
As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB:
As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks:
If you are upgrading from older pysmb versions:

Indices and tables

================================================ FILE: docs/html/py-modindex.html ================================================ Python Module Index — pysmb 1.2.13 documentation

Python Module Index

s
 
s
smb
    smb.security_descriptors Data structures used in Windows security descriptors.
================================================ FILE: docs/html/search.html ================================================ Search — pysmb 1.2.13 documentation

Search

Searching for multiple words only shows matches that contain all words.

================================================ FILE: docs/html/searchindex.js ================================================ Search.setIndex({"docnames": ["api/nmb_NBNSProtocol", "api/nmb_NetBIOS", "api/smb_SMBConnection", "api/smb_SMBHandler", "api/smb_SMBProtocolFactory", "api/smb_SharedDevice", "api/smb_SharedFile", "api/smb_exceptions", "api/smb_security_descriptors", "extending", "index", "upgrading"], "filenames": ["api/nmb_NBNSProtocol.rst", "api/nmb_NetBIOS.rst", "api/smb_SMBConnection.rst", "api/smb_SMBHandler.rst", "api/smb_SMBProtocolFactory.rst", "api/smb_SharedDevice.rst", "api/smb_SharedFile.rst", "api/smb_exceptions.rst", "api/smb_security_descriptors.rst", "extending.rst", "index.rst", "upgrading.rst"], "titles": ["NBNSProtocol Class", "NetBIOS class", "SMBConnection Class", "SMbHandler Class", "SMBProtocolFactory Class", "SharedDevice Class", "SharedFile Class", "SMB Exceptions", "Security Descriptors", "Extending pysmb For Other Frameworks", "Welcome to pysmb\u2019s documentation!", "Upgrading from older pysmb versions"], "terms": {"pysmb": [0, 2, 4, 7], "ha": [0, 2, 4, 9, 10, 11], "implement": [0, 1, 2, 4, 8, 9, 10], "twist": [0, 4, 10], "framework": [0, 4, 10], "thi": [0, 1, 4, 8, 9, 10, 11], "allow": 0, "you": [0, 1, 2, 3, 4, 9, 10, 11], "perform": [0, 1, 2, 4, 9], "name": [0, 1, 2, 3, 4, 10, 11], "queri": [0, 1, 10, 11], "asynchron": [0, 2, 9], "without": [0, 10], "have": [0, 2, 9, 10, 11], "your": [0, 1, 3, 4, 9, 10, 11], "applic": [0, 1, 4, 10, 11], "block": [0, 1, 2, 10], "wait": [0, 1, 4], "result": [0, 4], "In": [0, 3, 4, 9, 10], "project": [0, 4, 10], "creat": [0, 1, 2, 3, 4, 9], "instanc": [0, 1, 2, 4, 8, 11], "just": [0, 4], "call": [0, 1, 4, 9], "querynam": [0, 1], "method": [0, 1, 2, 3, 4, 9, 11], "which": [0, 1, 8, 9, 10, 11], "return": [0, 1, 2, 3, 4, 10, 11], "defer": [0, 4], "add": [0, 4, 11], "callback": [0, 9], "function": [0, 1, 4, 10], "via": [0, 4, 10], "addcallback": [0, 4], "receiv": [0, 1], "when": [0, 1, 2, 4, 7, 9, 10], "ar": [0, 1, 2, 4, 10, 11], "done": [0, 1], "its": [0, 1, 9], "transport": [0, 4, 10], "stoplisten": 0, "remov": 0, "from": [0, 1, 2, 3, 4, 8, 9, 10], "reactor": [0, 4], "To": [1, 2, 4, 10], "us": [1, 2, 4, 11], "new": [1, 4, 9, 11], "each": [1, 2, 4], "wish": [1, 2], "The": [1, 2, 3, 4, 8, 9, 10], "until": 1, "repli": 1, "i": [1, 2, 3, 4, 7, 8, 9, 10, 11], "remot": [1, 2, 3, 4, 9, 11], "smb": [1, 2, 3, 4, 8, 9, 10, 11], "cif": [1, 2, 4, 9, 10], "servic": [1, 2, 3, 4, 9, 10], "timeout": [1, 2, 4, 11], "close": [1, 2, 3, 4], "releas": [1, 11], "underli": [1, 4, 10], "resourc": 1, "nmb": [1, 10, 11], "broadcast": 1, "true": [1, 2, 4, 11], "listen_port": 1, "0": [1, 2, 4], "sourc": [1, 7, 8, 10], "__init__": [1, 4, 9], "instanti": 1, "ipv4": 1, "udp": 1, "socket": [1, 9], "listen": 1, "send": 1, "nbn": [1, 10], "packet": [1, 9], "paramet": [1, 3, 4, 9, 10, 11], "boolean": 1, "A": [1, 2, 3, 4, 8, 11], "flag": [1, 2, 4, 8], "indic": [1, 8, 11], "we": 1, "should": [1, 2, 4, 8], "setup": [1, 4, 9], "port": 1, "mode": 1, "integ": [1, 8, 10], "specifi": [1, 4, 8, 11], "number": [1, 4, 8, 11], "bind": 1, "If": [1, 2, 4, 10, 11], "zero": 1, "o": [1, 10], "automat": [1, 2, 4], "select": 1, "free": [1, 10], "ani": [1, 10], "oper": [1, 2, 4, 9, 10, 11], "after": [1, 2, 4, 10], "none": [1, 7], "queryipfornam": [1, 11], "ip": [1, 3, 9, 10, 11], "137": 1, "30": 1, "machin": [1, 2, 3, 4, 10, 11], "hope": 1, "back": [1, 2, 4], "contribut": 1, "jason": 1, "anderson": 1, "string": [1, 2, 3, 4], "nbnsprotocol": [1, 10, 11], "wa": [1, 11], "instiant": 1, "can": [1, 2, 3, 4, 8, 9, 10, 11], "an": [1, 2, 3, 4, 7, 8, 9, 10], "empti": [1, 3], "leav": 1, "determin": [1, 10], "appropri": 1, "address": [1, 3, 9, 10, 11], "fals": [1, 2, 4], "provid": [1, 3, 4, 9, 10], "target": 1, "n": 1, "iana": 1, "standard": [1, 10], "defin": [1, 11], "touch": [1, 4], "unless": 1, "know": [1, 4], "what": [1, 2, 4, 9], "do": [1, 2, 3, 4, 9, 11], "float": 1, "second": [1, 4], "list": [1, 8, 10], "contain": [1, 10], "On": 1, "network": [1, 10], "match": [1, 2, 4], "dot": 1, "notat": 1, "aaa": 1, "bbb": 1, "ccc": 1, "ddd": 1, "suitabl": [2, 10], "develop": [2, 10], "who": [2, 4, 10], "file": [2, 3, 4, 9, 10, 11], "server": [2, 4, 9, 10, 11], "sequenti": 2, "invok": 2, "complet": [2, 4, 10, 11], "encount": 2, "error": [2, 9], "follow": [2, 3, 4, 8, 10], "illustr": [2, 3, 4], "simpl": [2, 4], "retriev": [2, 3, 4, 11], "import": [2, 3, 4, 10], "tempfil": [2, 4], "There": [2, 4], "some": [2, 4, 10], "mechan": [2, 4], "captur": [2, 4], "userid": [2, 4], "password": [2, 4], "client_machine_nam": [2, 4], "server_nam": [2, 4], "server_ip": [2, 4], "arbitari": [2, 4], "ascii": [2, 4], "els": [2, 4], "connect": [2, 4, 9], "reject": [2, 4], "conn": 2, "use_ntlm_v2": [2, 4, 9], "assert": 2, "139": [2, 4], "file_obj": [2, 4], "namedtemporaryfil": [2, 4], "file_attribut": [2, 4], "files": 2, "retrievefil": [2, 4], "smbtest": [2, 4], "rfc1001": [2, 3, 4], "txt": [2, 3, 4], "content": [2, 4], "insid": [2, 4], "need": [2, 3, 4, 9, 10], "note": [2, 4], "obj": [2, 4], "posit": [2, 4], "end": [2, 4], "so": [2, 4, 9, 10], "might": [2, 4], "seek": [2, 4], "read": [2, 3, 4, 9, 10, 11], "begin": [2, 4], "start": [2, 4], "1": [2, 3, 4, 8, 10], "util": [2, 4], "protocol": [2, 4, 7, 10], "commun": [2, 4, 10], "otherwis": [2, 4], "fallback": [2, 4], "smb1": [2, 4, 10], "disabl": [2, 4], "set": [2, 4], "support_smb2": [2, 4], "smb_struct": [2, 4, 7, 10], "modul": [2, 4, 8, 10], "befor": [2, 4, 11], "It": [2, 10], "meant": 2, "singl": [2, 8], "more": [2, 4, 9, 10], "than": [2, 4], "one": [2, 3, 4], "concurr": [2, 4], "same": [2, 4], "time": [2, 4, 10], "keep": 2, "idl": 2, "too": 2, "long": 2, "e": [2, 4, 9], "most": [2, 4, 9, 10, 11], "sort": 2, "keepal": 2, "impos": [2, 4], "limit": [2, 4], "client": [2, 4, 10], "fail": [2, 4, 9], "respond": 2, "within": [2, 4, 10], "mai": [2, 4], "disconnect": [2, 4], "support": [3, 7, 10, 11], "url": [3, 10], "urllib2": [3, 10], "python": [3, 10], "packag": 3, "host": 3, "compon": 3, "must": [3, 4], "fulli": 3, "qualifi": 3, "hostnam": 3, "resolv": 3, "local": 3, "dn": 3, "myserv": 3, "test": [3, 10], "com": 3, "192": 3, "168": 3, "comma": 3, "separ": [3, 10], "nbname": 3, "where": [3, 4, 10], "window": [3, 8, 10], "netbio": [3, 9, 10, 11], "": [3, 4, 11], "first": 3, "path": [3, 4], "point": 3, "share": [3, 10], "folder": [3, 10, 11], "subsequ": 3, "directori": [3, 11], "upload": 3, "cannot": 3, "delet": [3, 11], "parent": 3, "exist": 3, "urlerror": 3, "rais": [3, 4, 7], "code": 3, "snippet": 3, "2": [3, 8, 10], "utf": 3, "8": [3, 10], "director": 3, "build_open": 3, "fh": 3, "open": [3, 10], "myuserid": 3, "mypassword": 3, "sharedfold": 3, "process": [3, 9], "like": [3, 11], "object": [3, 8], "For": [3, 4, 10], "unicod": 3, "charact": 3, "simpli": 3, "pass": [3, 11], "fh2": 3, "u": 3, "\u6d4b\u8bd5\u6587\u4ef6\u5939": 3, "\u5783\u573e\u6587\u4ef6": 3, "dat": 3, "data": [3, 8, 9, 10], "file_fh": 3, "local_fil": 3, "rb": 3, "upload_fil": 3, "onli": [3, 8, 10, 11], "3": [3, 8, 10], "urllib": 3, "request": 3, "those": 4, "want": [4, 10], "smbprotocol": [4, 10], "case": 4, "directli": 4, "all": [4, 8, 10], "expos": 4, "subclass": [4, 9], "overrid": [4, 9], "onauthok": [4, 9], "onauthfail": [4, 9], "own": [4, 9, 10], "post": [4, 9], "authenthent": 4, "handl": [4, 9], "onc": [4, 9], "been": [4, 9, 10], "pymsb": 4, "intern": [4, 9, 10], "readi": 4, "through": 4, "public": 4, "storefil": 4, "etc": 4, "closeconnect": 4, "functionl": 4, "internet": 4, "notreadyerror": 4, "except": [4, 10], "authent": [4, 9, 10], "termin": 4, "notconnectederror": 4, "accept": [4, 9], "entir": 4, "period": 4, "errback": 4, "smbtimeout": 4, "interest": 4, "learn": 4, "operationfailur": [4, 7], "retrievefilefactori": 4, "def": 4, "self": [4, 9], "arg": 4, "kwarg": 4, "fileretriev": 4, "write_result": 4, "file_s": 4, "loseconnect": 4, "d": 4, "adderrback": 4, "print": [4, 10], "auth": 4, "factori": 4, "connecttcp": 4, "avoid": 4, "reus": 4, "usual": [4, 9, 10], "transfer": [4, 10], "thousand": 4, "queue": 4, "batch": 4, "precis": 4, "accur": 4, "interv": 4, "5": [4, 8], "sec": 4, "class": [7, 8, 9, 10, 11], "unsupportedfeatur": 7, "featur": 7, "present": [7, 8], "requir": 7, "current": 7, "protocolerror": 7, "messag": [7, 10], "data_buf": 7, "smb_messag": 7, "associ": 8, "structur": 8, "m": [8, 10], "dtyp": 8, "security_descriptor": 8, "sid": 8, "revis": 8, "identifier_author": 8, "subauthor": 8, "identifi": 8, "repres": [8, 11], "princip": 8, "user": 8, "group": 8, "sequenc": 8, "consist": 8, "author": 8, "variabl": 8, "length": 8, "see": 8, "4": [8, 10], "alwai": [8, 10], "ac": 8, "type_": 8, "mask": 8, "additional_data": 8, "access": 8, "control": [8, 11], "entri": [8, 11], "dictionari": 8, "addit": 8, "field": 8, "depend": [8, 10], "type": 8, "object_typ": 8, "inherited_object_typ": 8, "application_data": 8, "attribute_data": 8, "bitmask": 8, "correspond": 8, "aceflag": 8, "properti": [8, 11], "isinheritonli": 8, "conveni": 8, "inherit": 8, "mean": 8, "doesn": 8, "t": 8, "appli": 8, "itself": [8, 10], "access_mask": 8, "truste": 8, "One": 8, "ace_type_": 8, "constant": [8, 10], "acetyp": 8, "acl": 8, "encapsul": 8, "valu": 8, "securitydescriptor": 8, "owner": 8, "dacl": 8, "sacl": 8, "6": 8, "discretionari": 8, "restrict": 8, "system": [8, 11], "audit": 8, "log": 8, "page": [9, 10, 11], "briefli": 9, "describ": 9, "step": 9, "involv": 9, "gener": 9, "take": [9, 10], "care": 9, "tcp": 9, "find": 9, "Then": 9, "write": [9, 11], "synchron": [9, 10], "And": 9, "initi": 9, "now": [9, 11], "abov": 9, "technic": 9, "detail": [9, 10], "base": [9, 10], "often": 9, "part": 9, "loop": 9, "feeddata": 9, "buffer": 9, "incomplet": 9, "session": [9, 10], "includ": [9, 10, 11], "success": 9, "report": 9, "try": 9, "differ": [9, 10], "ntlm": [9, 10], "algorithm": [9, 10], "constructor": 9, "onnmbsessionfail": 9, "due": 9, "wrong": 9, "remote_nam": 9, "pure": 10, "side": 10, "smb2": 10, "facilit": 10, "between": 10, "well": 10, "linux": 10, "samba": 10, "7": 10, "x": [10, 11], "against": 10, "10": 10, "latest": 10, "version": 10, "avail": 10, "miketeo": 10, "net": 10, "under": 10, "opensourc": 10, "commerci": 10, "purpos": 10, "term": 10, "pleas": [10, 11], "come": 10, "other": [10, 11], "3rd": 10, "parti": 10, "whose": 10, "cover": 10, "could": [10, 11], "possibli": 10, "conflict": 10, "exercis": 10, "discret": 10, "section": 10, "alon": 10, "made": 10, "possibl": 10, "pyasn1": 10, "asn": 10, "pars": 10, "encod": 10, "togeth": 10, "instal": 10, "md4": 10, "u32": 10, "hash": 10, "32": 10, "bit": 10, "unsign": 10, "dmitri": 10, "rozmanov": 10, "lgpl": 10, "pyde": 10, "de": 10, "encrypt": [10, 11], "todd": 10, "whiteman": 10, "domain": 10, "sha256": 10, "sha": 10, "256": 10, "digest": 10, "thoma": 10, "dixon": 10, "mit": 10, "librari": 10, "doe": 10, "variou": 10, "place": 10, "refer": [10, 11], "specif": 10, "referenc": 10, "download": 10, "microsoft": 10, "web": 10, "site": 10, "promis": 10, "copi": 10, "googl": 10, "exampl": 10, "nt": 10, "lm": 10, "dialect": 10, "organ": 10, "main": 10, "relat": 10, "As": 10, "henc": 10, "familiar": 10, "yourself": 10, "py": 10, "netbiossess": 10, "abstract": 10, "netbiosprotocol": 10, "ntlmv1": 10, "ntlmv2": 10, "routin": 10, "decod": 10, "securityblob": 10, "ntlmssp": 10, "secur": 10, "blob": 10, "smb_constant": 10, "These": 10, "smb2_constant": 10, "smb2_struct": 10, "smbconnect": [10, 11], "smbhandler": 10, "look": 10, "translat": 10, "thei": 10, "style": 10, "over": 10, "smbprotocolfactori": [10, 11], "softwar": 10, "modifi": 10, "integr": 10, "extend": 10, "upgrad": 10, "older": 10, "shareddevic": 10, "sharedfil": [10, 11], "descriptor": 10, "index": [10, 11], "search": [10, 11], "document": 11, "improv": 11, "chang": 11, "api": 11, "incompat": 11, "previou": 11, "delete_matching_fold": 11, "deletefil": 11, "sub": 11, "switch": 11, "listpath": 11, "file_id": 11, "attribut": 11, "given": 11, "context": 11, "manag": 11, "isnorm": 11, "normal": 11, "hidden": 11, "archiv": 11, "ignor": 11, "compress": 11, "spars": 11, "temporari": 11, "default": 11, "getsecur": 11, "ad": 11, "truncat": 11, "storefilefromoffset": 11, "getattribut": 11, "isreadonli": 11, "filesystem": 11, "workgroup": 11, "two": 11, "were": 11, "retrievefilefromoffset": 11, "finer": 11, "rewritten": 11, "rewrit": 11}, "objects": {"nmb.NetBIOS": [[1, 0, 1, "", "NetBIOS"]], "nmb.NetBIOS.NetBIOS": [[1, 1, 1, "", "__init__"], [1, 1, 1, "", "close"], [1, 1, 1, "", "queryIPForName"], [1, 1, 1, "", "queryName"]], "smb": [[8, 2, 0, "-", "security_descriptors"]], "smb.security_descriptors": [[8, 0, 1, "", "ACE"], [8, 0, 1, "", "ACL"], [8, 0, 1, "", "SID"], [8, 0, 1, "", "SecurityDescriptor"]], "smb.security_descriptors.ACE": [[8, 3, 1, "", "additional_data"], [8, 3, 1, "", "flags"], [8, 4, 1, "", "isInheritOnly"], [8, 3, 1, "", "mask"], [8, 3, 1, "", "sid"], [8, 3, 1, "", "type"]], "smb.security_descriptors.ACL": [[8, 3, 1, "", "aces"], [8, 3, 1, "", "revision"]], "smb.security_descriptors.SID": [[8, 3, 1, "", "identifier_authority"], [8, 3, 1, "", "revision"], [8, 3, 1, "", "subauthorities"]], "smb.security_descriptors.SecurityDescriptor": [[8, 3, 1, "", "dacl"], [8, 3, 1, "", "flags"], [8, 3, 1, "", "group"], [8, 3, 1, "", "owner"], [8, 3, 1, "", "sacl"]], "smb.smb_structs": [[7, 0, 1, "", "OperationFailure"], [7, 0, 1, "", "ProtocolError"], [7, 0, 1, "", "UnsupportedFeature"]]}, "objtypes": {"0": "py:class", "1": "py:method", "2": "py:module", "3": "py:attribute", "4": "py:property"}, "objnames": {"0": ["py", "class", "Python class"], "1": ["py", "method", "Python method"], "2": ["py", "module", "Python module"], "3": ["py", "attribute", "Python attribute"], "4": ["py", "property", "Python property"]}, "titleterms": {"nbnsprotocol": 0, "class": [0, 1, 2, 3, 4, 5, 6], "netbio": 1, "smbconnect": 2, "exampl": [2, 3, 4], "smb2": [2, 4], "support": [2, 4], "caveat": [2, 4], "smbhandler": 3, "note": 3, "smbprotocolfactori": 4, "shareddevic": 5, "sharedfil": 6, "smb": 7, "except": 7, "secur": 8, "descriptor": 8, "extend": 9, "pysmb": [9, 10, 11], "For": 9, "other": 9, "framework": 9, "welcom": 10, "": 10, "document": 10, "licens": 10, "credit": 10, "packag": 10, "content": 10, "descript": 10, "us": 10, "indic": 10, "tabl": 10, "upgrad": 11, "from": 11, "older": 11, "version": 11, "1": 11, "2": 11, "0": 11, "28": 11, "26": 11, "25": 11, "20": 11, "15": 11, "11": 11, "10": 11, "3": 11}, "envversion": {"sphinx.domains.c": 3, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 9, "sphinx.domains.index": 1, "sphinx.domains.javascript": 3, "sphinx.domains.math": 2, "sphinx.domains.python": 4, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.todo": 2, "sphinx.ext.viewcode": 1, "sphinx": 60}, "alltitles": {"NBNSProtocol Class": [[0, "nbnsprotocol-class"]], "NetBIOS class": [[1, "netbios-class"]], "SMBConnection Class": [[2, "smbconnection-class"]], "Example": [[2, "example"], [3, "example"], [4, "example"]], "SMB2 Support": [[2, "smb2-support"], [4, "smb2-support"]], "Caveats": [[2, "caveats"], [4, "caveats"]], "SMbHandler Class": [[3, "smbhandler-class"]], "Notes": [[3, "notes"]], "SMBProtocolFactory Class": [[4, "smbprotocolfactory-class"]], "SharedDevice Class": [[5, "shareddevice-class"]], "SharedFile Class": [[6, "sharedfile-class"]], "SMB Exceptions": [[7, "smb-exceptions"]], "Security Descriptors": [[8, "module-smb.security_descriptors"]], "Extending pysmb For Other Frameworks": [[9, "extending-pysmb-for-other-frameworks"]], "Welcome to pysmb\u2019s documentation!": [[10, "welcome-to-pysmb-s-documentation"]], "License": [[10, "license"]], "Credits": [[10, "credits"]], "Package Contents and Description": [[10, "package-contents-and-description"]], "Using pysmb": [[10, "using-pysmb"]], "Indices and tables": [[10, "indices-and-tables"]], "Upgrading from older pysmb versions": [[11, "upgrading-from-older-pysmb-versions"]], "pysmb 1.2.0": [[11, "pysmb-1-2-0"]], "pysmb 1.1.28": [[11, "pysmb-1-1-28"]], "pysmb 1.1.26": [[11, "pysmb-1-1-26"]], "pysmb 1.1.25": [[11, "pysmb-1-1-25"]], "pysmb 1.1.20": [[11, "pysmb-1-1-20"]], "pysmb 1.1.15": [[11, "pysmb-1-1-15"]], "pysmb 1.1.11": [[11, "pysmb-1-1-11"]], "pysmb 1.1.10": [[11, "pysmb-1-1-10"]], "pysmb 1.1.2": [[11, "pysmb-1-1-2"]], "pysmb 1.0.3": [[11, "pysmb-1-0-3"]], "pysmb 1.0.0": [[11, "pysmb-1-0-0"]]}, "indexentries": {"netbios (class in nmb.netbios)": [[1, "nmb.NetBIOS.NetBIOS"]], "__init__() (nmb.netbios.netbios method)": [[1, "nmb.NetBIOS.NetBIOS.__init__"]], "close() (nmb.netbios.netbios method)": [[1, "nmb.NetBIOS.NetBIOS.close"]], "queryipforname() (nmb.netbios.netbios method)": [[1, "nmb.NetBIOS.NetBIOS.queryIPForName"]], "queryname() (nmb.netbios.netbios method)": [[1, "nmb.NetBIOS.NetBIOS.queryName"]], "operationfailure (class in smb.smb_structs)": [[7, "smb.smb_structs.OperationFailure"]], "protocolerror (class in smb.smb_structs)": [[7, "smb.smb_structs.ProtocolError"]], "unsupportedfeature (class in smb.smb_structs)": [[7, "smb.smb_structs.UnsupportedFeature"]], "ace (class in smb.security_descriptors)": [[8, "smb.security_descriptors.ACE"]], "acl (class in smb.security_descriptors)": [[8, "smb.security_descriptors.ACL"]], "sid (class in smb.security_descriptors)": [[8, "smb.security_descriptors.SID"]], "securitydescriptor (class in smb.security_descriptors)": [[8, "smb.security_descriptors.SecurityDescriptor"]], "aces (smb.security_descriptors.acl attribute)": [[8, "smb.security_descriptors.ACL.aces"]], "additional_data (smb.security_descriptors.ace attribute)": [[8, "smb.security_descriptors.ACE.additional_data"]], "dacl (smb.security_descriptors.securitydescriptor attribute)": [[8, "smb.security_descriptors.SecurityDescriptor.dacl"]], "flags (smb.security_descriptors.ace attribute)": [[8, "smb.security_descriptors.ACE.flags"]], "flags (smb.security_descriptors.securitydescriptor attribute)": [[8, "smb.security_descriptors.SecurityDescriptor.flags"]], "group (smb.security_descriptors.securitydescriptor attribute)": [[8, "smb.security_descriptors.SecurityDescriptor.group"]], "identifier_authority (smb.security_descriptors.sid attribute)": [[8, "smb.security_descriptors.SID.identifier_authority"]], "isinheritonly (smb.security_descriptors.ace property)": [[8, "smb.security_descriptors.ACE.isInheritOnly"]], "mask (smb.security_descriptors.ace attribute)": [[8, "smb.security_descriptors.ACE.mask"]], "module": [[8, "module-smb.security_descriptors"]], "owner (smb.security_descriptors.securitydescriptor attribute)": [[8, "smb.security_descriptors.SecurityDescriptor.owner"]], "revision (smb.security_descriptors.acl attribute)": [[8, "smb.security_descriptors.ACL.revision"]], "revision (smb.security_descriptors.sid attribute)": [[8, "smb.security_descriptors.SID.revision"]], "sacl (smb.security_descriptors.securitydescriptor attribute)": [[8, "smb.security_descriptors.SecurityDescriptor.sacl"]], "sid (smb.security_descriptors.ace attribute)": [[8, "smb.security_descriptors.ACE.sid"]], "smb.security_descriptors": [[8, "module-smb.security_descriptors"]], "subauthorities (smb.security_descriptors.sid attribute)": [[8, "smb.security_descriptors.SID.subauthorities"]], "type (smb.security_descriptors.ace attribute)": [[8, "smb.security_descriptors.ACE.type"]]}}) ================================================ FILE: docs/html/upgrading.html ================================================ Upgrading from older pysmb versions — pysmb 1.2.13 documentation

Upgrading from older pysmb versions

This page documents the improvements and changes to the API that could be incompatible with previous releases.

pysmb 1.2.0

  • Add new delete_matching_folders parameter to deleteFiles() method in SMBProtocolFactory and SMBConnection class to support deletion of sub-folders. If you are passing timeout parameter to the deleteFiles() method in your application, please switch to using named parameter for timeout.

pysmb 1.1.28

  • SharedFile instances returned from the listPath() method now has a new property file_id attribute which represents the file reference number given by the remote SMB server.

pysmb 1.1.26

  • SMBConnection class can now be used as a context manager

pysmb 1.1.25

  • SharedFile class has a new property isNormal which will be True if the file is a ‘normal’ file. pysmb defines a ‘normal’ file as a file entry that is not read-only, not hidden, not system, not archive and not a directory; it ignores other attributes like compression, indexed, sparse, temporary and encryption.

  • listPath() method in SMBProtocolFactory and SMBConnection class will now include ‘normal’ files by default if you do not specify the search parameter.

pysmb 1.1.20

  • A new method getSecurity() was added to SMBConnection and SMBProtocolFactory class.

pysmb 1.1.15

  • Add new truncate parameter to storeFileFromOffset() in SMBProtocolFactory and SMBConnection class to support truncation of the file before writing. If you are passing timeout parameter to the storeFileFromOffset() method in your application, please switch to using named parameter for timeout.

pysmb 1.1.11

  • A new method storeFileFromOffset() was added to SMBConnection and SMBProtocolFactory class.

pysmb 1.1.10

  • A new method getAttributes() was added to SMBConnection and SMBProtocolFactory class

  • SharedFile class has a new property isReadOnly to indicate the file is read-only on the remote filesystem.

pysmb 1.1.2

  • queryIPForName() method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names.

pysmb 1.0.3

  • Two new methods were added to NBNSProtocol class: queryIPForName() and NetBIOS.queryIPForName() to support querying for a machine’s NetBIOS name at the given IP address.

  • A new method retrieveFileFromOffset() was added to SMBProtocolFactory and SMBConnection to support finer control of file retrieval operation.

pysmb 1.0.0

pysmb was completely rewritten in version 1.0.0. If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API.

================================================ FILE: python2/nmb/NetBIOS.py ================================================ import os, logging, random, socket, time, select from base import NBNS, NotConnectedError from nmb_constants import TYPE_CLIENT, TYPE_SERVER, TYPE_WORKSTATION class NetBIOS(NBNS): log = logging.getLogger('NMB.NetBIOS') def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.broadcast: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) if listen_port: self.sock.bind(( '', listen_port )) def close(self): """ Close the underlying and free resources. The NetBIOS instance should not be used to perform any operations after this method returns. :return: None """ self.sock.close() self.sock = None def write(self, data, ip, port): assert self.sock, 'Socket is already closed' self.sock.sendto(data, ( ip, port )) def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) return self._pollForNetBIOSPacket(trn_id, timeout) def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of string containing the names of the machine at *ip*. On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNetNameQuery(trn_id, False) self.write(data, ip, port) ret = self._pollForQueryPacket(trn_id, timeout) if ret: return map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret)) else: return None # # Protected Methods # def _pollForNetBIOSPacket(self, wait_trn_id, timeout): end_time = time.time() + timeout while True: try: _timeout = end_time - time.time() if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodePacket(data) if trn_id == wait_trn_id: return ret except select.error, ex: if type(ex) is types.TupleType: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex # # Contributed by Jason Anderson # def _pollForQueryPacket(self, wait_trn_id, timeout): end_time = time.time() + timeout while True: try: _timeout = end_time - time.time() if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodeIPQueryPacket(data) if trn_id == wait_trn_id: return ret except select.error, ex: if type(ex) is types.TupleType: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex ================================================ FILE: python2/nmb/NetBIOSProtocol.py ================================================ import os, logging, random, socket, time from twisted.internet import reactor, defer from twisted.internet.protocol import DatagramProtocol from nmb_constants import TYPE_SERVER from base import NBNS IP_QUERY, NAME_QUERY = range(2) class NetBIOSTimeout(Exception): """Raised in NBNSProtocol via Deferred.errback method when queryName method has timeout waiting for reply""" pass class NBNSProtocol(DatagramProtocol, NBNS): log = logging.getLogger('NMB.NBNSProtocol') def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NBNSProtocol instance. This automatically calls reactor.listenUDP method to start listening for incoming packets, so you **must not** call the listenUDP method again. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.pending_trns = { } # TRN ID -> ( expiry_time, name, Deferred instance ) self.transport = reactor.listenUDP(listen_port, self) if self.broadcast: self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) reactor.callLater(1, self.cleanupPendingTrns) def datagramReceived(self, data, from_info): host, port = from_info trn_id, ret = self.decodePacket(data) # pending transaction exists for trn_id - handle it and remove from queue if trn_id in self.pending_trns: _, ip, d = self.pending_trns.pop(trn_id) if ip is NAME_QUERY: # decode as query packet trn_id, ret = self.decodeIPQueryPacket(data) d.callback(ret) def write(self, data, ip, port): # We don't use the transport.write method directly as it keeps raising DeprecationWarning for ip='' self.transport.getHandle().sendto(data, ( ip, port )) def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the returned Deferred instance will be called with a NetBIOSTimeout exception. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if not self.pending_trns.has_key(trn_id): break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) d = defer.Deferred() self.pending_trns[trn_id] = ( time.time()+timeout, name, d ) return d def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of names of the machine at *ip*. On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if not self.pending_trns.has_key(trn_id): break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNetNameQuery(trn_id) self.write(data, ip, port) d = defer.Deferred() d2 = defer.Deferred() d2.addErrback(d.errback) def stripCode(ret): if ret is not None: # got valid response. Somehow the callback is also called when there is an error. d.callback(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) d2.addCallback(stripCode) self.pending_trns[trn_id] = ( time.time()+timeout, NAME_QUERY, d2 ) return d def stopProtocol(self): DatagramProtocol.stopProtocol(self) def cleanupPendingTrns(self): now = time.time() # reply should have been received in the past expired = filter(lambda (trn_id, (expiry_time, name, d)): expiry_time < now, self.pending_trns.iteritems()) # remove expired items from dict + call errback def expire_item(item): trn_id, (expiry_time, name, d) = item del self.pending_trns[trn_id] try: d.errback(NetBIOSTimeout(name)) except: pass map(expire_item, expired) if self.transport: reactor.callLater(1, self.cleanupPendingTrns) ================================================ FILE: python2/nmb/__init__.py ================================================ ================================================ FILE: python2/nmb/base.py ================================================ import struct, logging, random from nmb_constants import * from nmb_structs import * from utils import encode_name class NMBSession: log = logging.getLogger('NMB.NMBSession') def __init__(self, my_name, remote_name, host_type = TYPE_SERVER, is_direct_tcp = False): self.my_name = my_name.upper() self.remote_name = remote_name.upper() self.host_type = host_type self.data_buf = '' if is_direct_tcp: self.data_nmb = DirectTCPSessionMessage() self.sendNMBPacket = self._sendNMBPacket_DirectTCP else: self.data_nmb = NMBSessionMessage() self.sendNMBPacket = self._sendNMBPacket_NetBIOS # # Overridden Methods # def write(self, data): raise NotImplementedError def onNMBSessionMessage(self, flags, data): pass def onNMBSessionOK(self): pass def onNMBSessionFailed(self): pass # # Public Methods # def feedData(self, data): self.data_buf = self.data_buf + data offset = 0 while True: length = self.data_nmb.decode(self.data_buf, offset) if length == 0: break elif length > 0: offset += length self._processNMBSessionPacket(self.data_nmb) else: raise NMBError if offset > 0: self.data_buf = self.data_buf[offset:] def sendNMBMessage(self, data): self.sendNMBPacket(SESSION_MESSAGE, data) def requestNMBSession(self): my_name_encoded = encode_name(self.my_name, TYPE_WORKSTATION) remote_name_encoded = encode_name(self.remote_name, self.host_type) self.sendNMBPacket(SESSION_REQUEST, remote_name_encoded + my_name_encoded) # # Protected Methods # def _processNMBSessionPacket(self, packet): if packet.type == SESSION_MESSAGE: self.onNMBSessionMessage(packet.flags, packet.data) elif packet.type == POSITIVE_SESSION_RESPONSE: self.onNMBSessionOK() elif packet.type == NEGATIVE_SESSION_RESPONSE: self.onNMBSessionFailed() elif packet.type == SESSION_KEEPALIVE: # Discard keepalive packets - [RFC1002]: 5.2.2.1 pass else: self.log.warning('Unrecognized NMB session type: 0x%02x', packet.type) def _sendNMBPacket_NetBIOS(self, packet_type, data): length = len(data) assert length <= 0x01FFFF flags = 0 if length > 0xFFFF: flags |= 0x01 length &= 0xFFFF self.write(struct.pack('>BBH', packet_type, flags, length) + data) def _sendNMBPacket_DirectTCP(self, packet_type, data): length = len(data) assert length <= 0x00FFFFFF self.write(struct.pack('>I', length) + data) class NBNS: log = logging.getLogger('NMB.NBNS') HEADER_STRUCT_FORMAT = '>HHHHHH' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def write(self, data, ip, port): raise NotImplementedError def decodePacket(self, data): if len(data) < self.HEADER_STRUCT_SIZE: raise Exception trn_id, code, question_count, answer_count, authority_count, additional_count = struct.unpack(self.HEADER_STRUCT_FORMAT, data[:self.HEADER_STRUCT_SIZE]) is_response = bool((code >> 15) & 0x01) opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F if opcode == 0x0000 and is_response: name_len = ord(data[self.HEADER_STRUCT_SIZE]) offset = self.HEADER_STRUCT_SIZE+2+name_len+8 # constant 2 for the padding bytes before/after the Name and constant 8 for the Type, Class and TTL fields in the Answer section after the Name record_count = (struct.unpack('>H', data[offset:offset+2])[0]) / 6 offset += 4 # Constant 4 for the Data Length and Flags field ret = [ ] for i in range(0, record_count): ret.append('%d.%d.%d.%d' % struct.unpack('4B', (data[offset:offset + 4]))) offset += 6 return trn_id, ret else: return trn_id, None def prepareNameQuery(self, trn_id, name, is_broadcast = True): header = struct.pack(self.HEADER_STRUCT_FORMAT, trn_id, (is_broadcast and 0x0110) or 0x0100, 1, 0, 0, 0) payload = encode_name(name, 0x20) + '\x00\x20\x00\x01' return header + payload # # Contributed by Jason Anderson # def decodeIPQueryPacket(self, data): if len(data) < self.HEADER_STRUCT_SIZE: raise Exception trn_id, code, question_count, answer_count, authority_count, additional_count = struct.unpack(self.HEADER_STRUCT_FORMAT, data[:self.HEADER_STRUCT_SIZE]) is_response = bool((code >> 15) & 0x01) opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F try: numnames = struct.unpack('B', data[self.HEADER_STRUCT_SIZE + 44])[0] if numnames > 0: ret = [ ] offset = self.HEADER_STRUCT_SIZE + 45 for i in range(0, numnames): mynme = data[offset:offset + 15] mynme = mynme.strip() ret.append(( mynme, ord(data[offset+15]) )) offset += 18 return trn_id, ret except IndexError: pass return trn_id, None # # Contributed by Jason Anderson # def prepareNetNameQuery(self, trn_id, is_broadcast = True): header = struct.pack(self.HEADER_STRUCT_FORMAT, trn_id, (is_broadcast and 0x0010) or 0x0000, 1, 0, 0, 0) payload = encode_name('*', 0) + '\x00\x21\x00\x01' return header + payload ================================================ FILE: python2/nmb/nmb_constants.py ================================================ # Default port for NetBIOS name service NETBIOS_NS_PORT = 137 # Default port for NetBIOS session service NETBIOS_SESSION_PORT = 139 # Owner Node Type Constants NODE_B = 0x00 NODE_P = 0x01 NODE_M = 0x10 NODE_RESERVED = 0x11 # Name Type Constants TYPE_UNKNOWN = 0x01 TYPE_WORKSTATION = 0x00 TYPE_CLIENT = 0x03 TYPE_SERVER = 0x20 TYPE_DOMAIN_MASTER = 0x1B TYPE_MASTER_BROWSER = 0x1D TYPE_BROWSER = 0x1E TYPE_NAMES = { TYPE_UNKNOWN: 'Unknown', TYPE_WORKSTATION: 'Workstation', TYPE_CLIENT: 'Client', TYPE_SERVER: 'Server', TYPE_MASTER_BROWSER: 'Master Browser', TYPE_BROWSER: 'Browser Server', TYPE_DOMAIN_MASTER: 'Domain Master' } # Values for Session Packet Type field in Session Packets SESSION_MESSAGE = 0x00 SESSION_REQUEST = 0x81 POSITIVE_SESSION_RESPONSE = 0x82 NEGATIVE_SESSION_RESPONSE = 0x83 REGTARGET_SESSION_RESPONSE = 0x84 SESSION_KEEPALIVE = 0x85 ================================================ FILE: python2/nmb/nmb_structs.py ================================================ import struct class NMBError(Exception): pass class NotConnectedError(NMBError): """ Raisd when the underlying NMB connection has been disconnected or not connected yet """ pass class NMBSessionMessage: HEADER_STRUCT_FORMAT = '>BBH' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def __init__(self): self.reset() def reset(self): self.type = 0 self.flags = 0 self.data = '' def decode(self, data, offset): data_len = len(data) if data_len < offset + self.HEADER_STRUCT_SIZE: # Not enough data for decoding return 0 self.reset() self.type, self.flags, length = struct.unpack(self.HEADER_STRUCT_FORMAT, data[offset:offset+self.HEADER_STRUCT_SIZE]) if self.flags & 0x01: length |= 0x010000 if data_len < offset + self.HEADER_STRUCT_SIZE + length: return 0 self.data = data[offset+self.HEADER_STRUCT_SIZE:offset+self.HEADER_STRUCT_SIZE+length] return self.HEADER_STRUCT_SIZE + length class DirectTCPSessionMessage(NMBSessionMessage): HEADER_STRUCT_FORMAT = '>I' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def decode(self, data, offset): data_len = len(data) if data_len < offset + self.HEADER_STRUCT_SIZE: # Not enough data for decoding return 0 self.reset() length = struct.unpack(self.HEADER_STRUCT_FORMAT, data[offset:offset+self.HEADER_STRUCT_SIZE])[0] if length >> 24 != 0: raise NMBError("Invalid protocol header for Direct TCP session message") if data_len < offset + self.HEADER_STRUCT_SIZE + length: return 0 self.data = data[offset+self.HEADER_STRUCT_SIZE:offset+self.HEADER_STRUCT_SIZE+length] return self.HEADER_STRUCT_SIZE + length ================================================ FILE: python2/nmb/utils.py ================================================ import string, re def encode_name(name, type, scope = None): """ Perform first and second level encoding of name as specified in RFC 1001 (Section 4) """ if name == '*': name = name + '\0' * 15 elif len(name) > 15: name = name[:15] + chr(type) else: name = string.ljust(name, 15) + chr(type) def _do_first_level_encoding(m): s = ord(m.group(0)) return string.uppercase[s >> 4] + string.uppercase[s & 0x0f] encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name) if scope: encoded_scope = '' for s in string.split(scope, '.'): encoded_scope = encoded_scope + chr(len(s)) + s return encoded_name + encoded_scope + '\0' else: return encoded_name + '\0' def decode_name(name): name_length = ord(name[0]) assert name_length == 32 def _do_first_level_decoding(m): s = m.group(0) return chr(((ord(s[0]) - ord('A')) << 4) | (ord(s[1]) - ord('A'))) decoded_name = re.sub('..', _do_first_level_decoding, name[1:33]) if name[33] == '\0': return 34, decoded_name, '' else: decoded_domain = '' offset = 34 while 1: domain_length = ord(name[offset]) if domain_length == 0: break decoded_domain = '.' + name[offset:offset + domain_length] offset = offset + domain_length return offset + 1, decoded_name, decoded_domain ================================================ FILE: python2/smb/SMBConnection.py ================================================ import os, logging, select, socket, struct, errno from smb_constants import * from smb_structs import * from base import SMB, NotConnectedError, NotReadyError, SMBTimeout class SMBConnection(SMB): log = logging.getLogger('SMB.SMBConnection') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. The default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ SMB.__init__(self, username, password, my_name, remote_name, domain, use_ntlm_v2, sign_options, is_direct_tcp) self.sock = None self.auth_result = None self.is_busy = False self.is_direct_tcp = is_direct_tcp # # SMB (and its superclass) Methods # def onAuthOK(self): self.auth_result = True def onAuthFailed(self): self.auth_result = False def write(self, data): assert self.sock data_len = len(data) total_sent = 0 while total_sent < data_len: sent = self.sock.send(data[total_sent:]) if sent == 0: raise NotConnectedError('Server disconnected') total_sent = total_sent + sent # # Support for "with" context # def __enter__(self): return self def __exit__(self, *args): self.close() # # Misc Properties # @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.is_using_smb2 # # Public Methods # def connect(self, ip, port = 139, sock_family = socket.AF_INET, timeout = 60): """ Establish the SMB connection to the remote SMB/CIFS server. You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication. :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise. """ if self.sock: self.sock.close() self.auth_result = None self.sock = socket.socket(sock_family) self.sock.settimeout(timeout) self.sock.connect(( ip, port )) self.is_busy = True try: if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() while self.auth_result is None: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return self.auth_result def close(self): """ Terminate the SMB connection (if it has been started) and release any sources held by the underlying socket. """ if self.sock: self.sock.close() self.sock = None def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :return: A list of :doc:`smb.base.SharedDevice` instances describing the shared resource """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listShares(cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile` instances. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listPath(service_name, path, cb, eb, search = search, pattern = pattern, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listSnapshots(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A :doc:`smb.base.SharedFile` instance containing the attributes of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def getSecurity(self, service_name, path, timeout = 30): """ Retrieve the security descriptor of the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getSecurity(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def retrieveFile(self, service_name, path, file_obj, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you wish to specify the offset to read from the remote *path* and/or the number of bytes to write to the *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0L, -1L, timeout) def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0L, max_length = -1L, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* up to *max_length* number of bytes. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the method returns immediately after the file is opened successfully for reading. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1:]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._retrieveFileFromOffset(service_name, path, file_obj, cb, eb, offset, max_length, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def storeFile(self, service_name, path, file_obj, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. If the file already exists on the remote server, it will be truncated and overwritten. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. :return: Number of bytes uploaded """ return self.storeFileFromOffset(service_name, path, file_obj, 0L, True, timeout) def storeFileFromOffset(self, service_name, path, file_obj, offset = 0L, truncate = False, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. :param offset: Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0. :param truncate: Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False. :return: the file position where the next byte will be written. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._storeFileFromOffset(service_name, path, file_obj, cb, eb, offset, truncate = truncate, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) Note: this function is currently only implemented for SMB2! :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def createDirectory(self, service_name, path, timeout = 30): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._createDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def deleteDirectory(self, service_name, path, timeout = 30): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def rename(self, service_name, old_path, new_path, timeout = 30): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._rename(service_name, old_path, new_path, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._echo(data, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] # # Protected Methods # def _pollForNetBIOSPacket(self, timeout): expiry_time = time.time() + timeout read_len = 4 data = '' while read_len > 0: try: if expiry_time < time.time(): raise SMBTimeout ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], timeout) if not ready: raise SMBTimeout d = self.sock.recv(read_len) if len(d) == 0: raise NotConnectedError data = data + d read_len -= len(d) except select.error, ex: if isinstance(ex, types.TupleType): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex type_, flags, length = struct.unpack('>BBH', data) if flags & 0x01: length = length | 0x10000 read_len = length while read_len > 0: try: if expiry_time < time.time(): raise SMBTimeout ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], timeout) if not ready: raise SMBTimeout d = self.sock.recv(read_len) if len(d) == 0: raise NotConnectedError data = data + d read_len -= len(d) except select.error, ex: if isinstance(ex, types.TupleType): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex self.feedData(data) ================================================ FILE: python2/smb/SMBHandler.py ================================================ import os, sys, socket, urllib2, mimetypes, mimetools, tempfile from urllib import (unwrap, unquote, splittype, splithost, quote, addinfourl, splitport, splittag, splitattr, ftpwrapper, splituser, splitpasswd, splitvalue) from nmb.NetBIOS import NetBIOS from smb.SMBConnection import SMBConnection try: from cStringIO import StringIO except ImportError: from StringIO import StringIO USE_NTLM = True MACHINE_NAME = None class SMBHandler(urllib2.BaseHandler): def smb_open(self, req): global USE_NTLM, MACHINE_NAME host = req.get_host() if not host: raise urllib2.URLError('SMB error: no host given') host, port = splitport(host) if port is None: port = 139 else: port = int(port) # username/password handling user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = user or '' domain = '' if ';' in user: domain, user = user.split(';', 1) passwd = passwd or '' myname = MACHINE_NAME or self.generateClientMachineName() server_name,host = host.split(',') if ',' in host else [None,host] if server_name is None: n = NetBIOS() names = n.queryIPForName(host) if names: server_name = names[0] else: raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name') path, attrs = splitattr(req.get_selector()) if path.startswith('/'): path = path[1:] dirs = path.split('/') dirs = map(unquote, dirs) service, path = dirs[0], '/'.join(dirs[1:]) try: conn = SMBConnection(user, passwd, myname, server_name, domain=domain, use_ntlm_v2 = USE_NTLM) conn.connect(host, port) if req.has_data(): data_fp = req.get_data() filelen = conn.storeFile(service, path, data_fp) headers = "Content-length: 0\n" fp = StringIO("") else: fp = self.createTempFile() file_attrs, retrlen = conn.retrieveFile(service, path, fp) fp.seek(0) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except Exception, ex: raise urllib2.URLError, ('smb error: %s' % ex), sys.exc_info()[2] def createTempFile(self): return tempfile.TemporaryFile() def generateClientMachineName(self): hostname = socket.gethostname() if hostname: return hostname.split('.')[0] return 'SMB%d' % os.getpid() ================================================ FILE: python2/smb/SMBProtocol.py ================================================ import os, logging, time from twisted.internet import reactor, defer from twisted.internet.protocol import ClientFactory, Protocol from smb_constants import * from smb_structs import * from base import SMB, NotConnectedError, NotReadyError, SMBTimeout __all__ = [ 'SMBProtocolFactory', 'NotConnectedError', 'NotReadyError' ] class SMBProtocol(Protocol, SMB): log = logging.getLogger('SMB.SMBProtocol') # # Protocol Methods # def connectionMade(self): self.factory.instance = self if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() def connectionLost(self, reason): if self.factory.instance == self: self.instance = None def dataReceived(self, data): self.feedData(data) # # SMB (and its superclass) Methods # def write(self, data): self.transport.write(data) def onAuthOK(self): if self.factory.instance == self: self.factory.onAuthOK() reactor.callLater(1, self._cleanupPendingRequests) def onAuthFailed(self): if self.factory.instance == self: self.factory.onAuthFailed() def onNMBSessionFailed(self): self.log.error('Cannot establish NetBIOS session. You might have provided a wrong remote_name') # # Protected Methods # def _cleanupPendingRequests(self): if self.factory.instance == self: now = time.time() to_remove = [] for mid, r in self.pending_requests.iteritems(): if r.expiry_time < now: try: r.errback(SMBTimeout()) except Exception: pass to_remove.append(mid) for mid in to_remove: del self.pending_requests[mid] reactor.callLater(1, self._cleanupPendingRequests) class SMBProtocolFactory(ClientFactory): protocol = SMBProtocol log = logging.getLogger('SMB.SMBFactory') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBProtocolFactory instance. You will pass this instance to *reactor.connectTCP()* which will then instantiate the TCP connection to the remote SMB/CIFS server. Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. File operations can only be proceeded after the connection has been authenticated successfully. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+``. :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ self.username = username self.password = password self.my_name = my_name self.remote_name = remote_name self.domain = domain self.use_ntlm_v2 = use_ntlm_v2 self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.instance = None #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly. # # Public Property # @property def isReady(self): """A convenient property to return True if the underlying SMB connection has connected to remote server, has successfully authenticated itself and is ready for file operations.""" return bool(self.instance and self.instance.has_authenticated) @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.instance and self.instance.is_using_smb2 # # Public Methods for Callbacks # def onAuthOK(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. File operations can proceed when this method has been called. """ pass def onAuthFailed(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. If you want to retry authenticating from this method, 1. Disconnect the underlying SMB connection (call ``self.instance.transport.loseConnection()``) 2. Create a new SMBProtocolFactory subclass instance with different user credientials or different NTLM algorithm flag. 3. Call ``reactor.connectTCP`` with the new instance to re-establish the SMB connection """ pass # # Public Methods # def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedDevice` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listShares(d.callback, d.errback, timeout) return d def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listPath(service_name, path, d.callback, d.errback, search = search, pattern = pattern, timeout = timeout) return d def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (a.k.a. shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listSnapshots(service_name, path, d.callback, d.errback, timeout = timeout) return d def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a :doc:`smb.base.SharedFile` instance containing the attributes of the file. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._getAttributes(service_name, path, d.callback, d.errback, timeout = timeout) return d def retrieveFile(self, service_name, path, file_obj, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you need to specify the offset to read from the remote *path* and/or the maximum number of bytes to write to the *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0L, -1L, timeout) def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0L, max_length = -1L, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the *Deferred* callback is invoked immediately after the file is opened successfully for reading. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._retrieveFileFromOffset(service_name, path, file_obj, d.callback, d.errback, offset, max_length, timeout = timeout) return d def storeFile(self, service_name, path, file_obj, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. The meaning of the *timeout* parameter will be different from other file operation methods. As the uploaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of messages (usually about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and acknowledged by the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *file_obj*, number of bytes uploaded ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout) return d def deleteFiles(self, service_name, path_file_pattern, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path_file_pattern* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteFiles(service_name, path_file_pattern, d.callback, d.errback, timeout = timeout) return d def createDirectory(self, service_name, path): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._createDirectory(service_name, path, d.callback, d.errback) return d def deleteDirectory(self, service_name, path): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteDirectory(service_name, path, d.callback, d.errback) return d def rename(self, service_name, old_path, new_path): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *old_path*, *new_path* ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._rename(service_name, old_path, new_path, d.callback, d.errback) return d def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._echo(data, d.callback, d.errback, timeout) return d def closeConnection(self): """ Disconnect from the remote SMB/CIFS server. The TCP connection will be closed at the earliest opportunity after this method returns. :return: None """ if not self.instance: raise NotConnectedError('Not connected to server') self.instance.transport.loseConnection() # # ClientFactory methods # (Do not touch these unless you know what you are doing) # def buildProtocol(self, addr): p = self.protocol(self.username, self.password, self.my_name, self.remote_name, self.domain, self.use_ntlm_v2, self.sign_options, self.is_direct_tcp) p.factory = self return p ================================================ FILE: python2/smb/__init__.py ================================================ ================================================ FILE: python2/smb/base.py ================================================ import logging, binascii, time, hmac from datetime import datetime from smb_constants import * from smb2_constants import * from smb_structs import * from smb2_structs import * from .security_descriptors import SecurityDescriptor from nmb.base import NMBSession from utils import convertFILETIMEtoEpoch import ntlm, securityblob try: import hashlib sha256 = hashlib.sha256 except ImportError: from utils import sha256 class NotReadyError(Exception): """Raised when SMB connection is not ready (i.e. not authenticated or authentication failed)""" pass class NotConnectedError(Exception): """Raised when underlying SMB connection has been disconnected or not connected yet""" pass class SMBTimeout(Exception): """Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete.""" pass def _convert_to_unicode(string): if not isinstance(string, unicode): string = unicode(string, "utf-8") return string class SMB(NMBSession): """ This class represents a "connection" to the remote SMB/CIFS server. It is not meant to be used directly in an application as it does not have any network transport implementations. For application use, please refer to - L{SMBProtocol.SMBProtocolFactory} if you are using Twisted framework In [MS-CIFS], this class will contain attributes of Client, Client.Connection and Client.Session abstract data models. References: =========== - [MS-CIFS]: 3.2.1 """ log = logging.getLogger('SMB.SMB') SIGN_NEVER = 0 SIGN_WHEN_SUPPORTED = 1 SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) self.username = _convert_to_unicode(username) self._password = password self.domain = _convert_to_unicode(domain) self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages self.has_negotiated = False self.has_authenticated = False self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2 self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2 self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2 self.mid = 0 self.uid = 0 self.next_signing_id = 2 #: Similar to ClientNextSendSequenceNumber as described in [MS-CIFS] 3.2.1.2 # SMB1 and SMB2 attributes # Note that the interpretations of the values may differ between SMB1 and SMB2 protocols self.capabilities = 0 self.security_mode = 0 #: Initialized from the SecurityMode field of the SMB_COM_NEGOTIATE message # SMB1 attributes # Most of the following attributes will be initialized upon receipt of SMB_COM_NEGOTIATE message from server (via self._updateServerInfo_SMB1 method) self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1 self.max_raw_size = 0 self.max_buffer_size = 0 #: Similar to MaxBufferSize as described in [MS-CIFS] 3.2.1.1 self.max_mpx_count = 0 #: Similar to MaxMpxCount as described in [MS-CIFS] 3.2.1.1 # SMB2 attributes self.max_read_size = 0 #: Similar to MaxReadSize as described in [MS-SMB2] 2.2.4 self.max_write_size = 0 #: Similar to MaxWriteSize as described in [MS-SMB2] 2.2.4 self.max_transact_size = 0 #: Similar to MaxTransactSize as described in [MS-SMB2] 2.2.4 self.session_id = 0 #: Similar to SessionID as described in [MS-SMB2] 2.2.4. This will be set in _updateState_SMB2 method self._setupSMB1Methods() self.log.info('Authentication with remote machine "%s" for user "%s" will be using NTLM %s authentication (%s extended security)', self.remote_name, self.username, (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') @property def password(self): password = self._password() if callable(self._password) else self._password return _convert_to_unicode(password) # # NMBSession Methods # def onNMBSessionOK(self): self._sendSMBMessage(SMBMessage(ComNegotiateRequest())) def onNMBSessionFailed(self): pass def onNMBSessionMessage(self, flags, data): while True: try: i = self.smb_message.decode(data) except SMB2ProtocolHeaderError: self.log.info('Now switching over to SMB2 protocol communication') self.is_using_smb2 = True self.mid = 0 # Must reset messageID counter, or else remote SMB2 server will disconnect self._setupSMB2Methods() self.smb_message = self._klassSMBMessage() i = self.smb_message.decode(data) next_message_offset = 0 if self.is_using_smb2: next_message_offset = self.smb_message.next_command_offset if i > 0: if not self.is_using_smb2: self.log.debug('Received SMB message "%s" (command:0x%2X flags:0x%02X flags2:0x%04X TID:%d UID:%d)', SMB_COMMAND_NAMES.get(self.smb_message.command, ''), self.smb_message.command, self.smb_message.flags, self.smb_message.flags2, self.smb_message.tid, self.smb_message.uid) else: self.log.debug('Received SMB2 message "%s" (command:0x%04X flags:0x%04x)', SMB2_COMMAND_NAMES.get(self.smb_message.command, ''), self.smb_message.command, self.smb_message.flags) if self._updateState(self.smb_message): # We need to create a new instance instead of calling reset() because the instance could be captured in the message history. self.smb_message = self._klassSMBMessage() if next_message_offset > 0: data = data[next_message_offset:] else: break # # Public Methods for Overriding in Subclasses # def onAuthOK(self): pass def onAuthFailed(self): pass # # Protected Methods # def _setupSMB1Methods(self): self._klassSMBMessage = SMBMessage self._updateState = self._updateState_SMB1 self._updateServerInfo = self._updateServerInfo_SMB1 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB1 self._sendSMBMessage = self._sendSMBMessage_SMB1 self._handleSessionChallenge = self._handleSessionChallenge_SMB1 self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 self._storeFile = self._storeFile_SMB1 self._storeFileFromOffset = self._storeFileFromOffset_SMB1 self._deleteFiles = self._deleteFiles_SMB1 self._resetFileAttributes = self._resetFileAttributes_SMB1 self._createDirectory = self._createDirectory_SMB1 self._deleteDirectory = self._deleteDirectory_SMB1 self._rename = self._rename_SMB1 self._echo = self._echo_SMB1 def _setupSMB2Methods(self): self._klassSMBMessage = SMB2Message self._updateState = self._updateState_SMB2 self._updateServerInfo = self._updateServerInfo_SMB2 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB2 self._sendSMBMessage = self._sendSMBMessage_SMB2 self._handleSessionChallenge = self._handleSessionChallenge_SMB2 self._listShares = self._listShares_SMB2 self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 self._getAttributes = self._getAttributes_SMB2 self._getSecurity = self._getSecurity_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 self._storeFile = self._storeFile_SMB2 self._storeFileFromOffset = self._storeFileFromOffset_SMB2 self._deleteFiles = self._deleteFiles_SMB2 self._resetFileAttributes = self._resetFileAttributes_SMB2 self._createDirectory = self._createDirectory_SMB2 self._deleteDirectory = self._deleteDirectory_SMB2 self._rename = self._rename_SMB2 self._echo = self._echo_SMB2 def _getNextRPCCallID(self): self.next_rpc_call_id += 1 return self.next_rpc_call_id # # SMB2 Methods Family # def _sendSMBMessage_SMB2(self, smb_message): if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: smb_message.flags |= SMB2_FLAGS_SIGNED raw_data = smb_message.encode() smb_message.signature = hmac.new(self.signing_session_key, raw_data, sha256).digest()[:16] smb_message.raw_data = smb_message.encode() self.log.debug('MID is %d. Signature is %s. Total raw message is %d bytes', smb_message.mid, binascii.hexlify(smb_message.signature), len(smb_message.raw_data)) else: smb_message.raw_data = smb_message.encode() self.sendNMBMessage(smb_message.raw_data) def _getNextMID_SMB2(self): self.mid += 1 return self.mid def _updateState_SMB2(self, message): if message.isReply: if message.command == SMB2_COM_NEGOTIATE: if message.status == 0: self.has_negotiated = True self.log.info('SMB2 dialect negotiation successful') self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB2_COM_NEGOTIATE' % message.status, message.raw_data, message) elif message.command == SMB2_COM_SESSION_SETUP: if message.status == 0: self.session_id = message.session_id try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') # [MS-SMB2]: 3.2.5.3.1 # If the security subsystem indicates that the session was established by an anonymous user, # Session.SigningRequired MUST be set to FALSE. # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired # MUST be set to FALSE. if message.payload.isGuestSession or message.payload.isAnonymousSession: self.is_signing_active = False self.log.info('Signing disabled because session is guest/anonymous') self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError, ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED self.session_id = message.session_id try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE or message.status == 0xc0000064 # STATUS_NO_SUCH_USER or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account or password has expired.') self.onAuthFailed() elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been disabled.') self.onAuthFailed() elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Not allowed.') self.onAuthFailed() elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Domain not trusted.') self.onAuthFailed() elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) if message.isAsync: if message.status == 0x00000103: # STATUS_PENDING req = self.pending_requests.pop(message.mid, None) if req: self.async_requests[message.async_id] = req else: # All other status including SUCCESS req = self.async_requests.pop(message.async_id, None) if req: req.callback(message, **req.kwargs) return True else: req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB2(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_transact_size = payload.max_transact_size self.max_read_size = payload.max_read_size self.max_write_size = payload.max_write_size self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication def _handleNegotiateResponse_SMB2(self, message): ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) def _handleSessionChallenge_SMB2(self, message, ntlm_token): server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) if self.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & SMB2_NEGOTIATE_SIGNING_ENABLED: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = session_signing_key if self.log.isEnabledFor(logging.DEBUG): self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _listShares_SMB2(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMB2Message(SMB2CreateRequest('srvsvc', file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE | FILE_OPEN_NO_RECALL, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: call_id = self._getNextRPCCallID() # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify("""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(' ', '')) + \ struct.pack(' data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name, _, file_id = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') short_name = short_name[:short_name_length].decode('UTF-16LE') accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset else: break return '' def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files callback([ ]) else: errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getAttributes_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: p = create_message.payload filename = self._extractLastPathComponent(unicode(path)) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, filename, filename) closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) def closeFid(tid, fid, info = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, info = info, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['info'] is not None: callback(kwargs['info']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get attributes for %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, info_type = SMB2_INFO_SECURITY, file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 input_buf = '', output_buf_len = self.max_transact_size)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) def queryCB(query_message, **kwargs): self._pushToArray(messages_history, query_message) if query_message.status == 0: security = SecurityDescriptor.from_bytes(query_message.payload.data) closeFid(kwargs['tid'], kwargs['fid'], result = security) else: closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def closeFid(tid, fid, result = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['result'] is not None: callback(kwargs['result']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0L, -1L, timeout) def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 input_buf = '', output_buf_len = 4096)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): self._pushToArray(messages_history, info_message) if info_message.status == 0: file_len = struct.unpack(' file_len: closeFid(info_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], 0 )) # Note that this is a tuple of 3-elements else: remaining_len = max_length if remaining_len < 0: remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) m = SMB2Message(SMB2ReadRequest(fid, offset, read_count)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) def readCB(read_message, **kwargs): # To avoid crazy memory usage when retrieving large files, we do not save every read_message in messages_history. if read_message.status == 0: data_len = read_message.payload.data_length file_obj.write(read_message.payload.data) remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) else: closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: self._pushToArray(messages_history, read_message) closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, ret = ret, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['ret'] is not None: callback(kwargs['ret']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _storeFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): self._storeFileFromOffset_SMB2(service_name, path, file_obj, callback, errback, 0L, True, timeout) def _storeFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 10 00 04 00 00 00 18 00 08 00 00 00 41 6c 53 69 00 00 00 00 85 62 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = ATTR_ARCHIVE, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OVERWRITE_IF if truncate else FILE_OPEN_IF, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): create_message.tid = kwargs['tid'] self._pushToArray(messages_history, create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): write_count = self.max_write_size data = file_obj.read(write_count) data_len = len(data) if data_len > 0: m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: self._pushToArray(messages_history, write_message) closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid, error = None, offset = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, fid = fid, offset = offset, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['offset'] is not None: callback(( file_obj, kwargs['offset'] )) # Note that this is a tuple of 2-elements elif kwargs['error'] is not None: errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): open_message.tid = kwargs['tid'] self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(open_message.tid, open_message.payload.fid) elif open_message.status == 0xC0000034L: # [MS-ERREF]: STATUS_OBJECT_NAME_NOT_FOUND callback(path) elif open_message.status == 0xC00000BAL: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = '\x01')) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendCreate(tid) def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_WRITE_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendReset(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation data = struct.pack('qqqqii',0,0,0,0,file_attributes,0))) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def resetCB(reset_message, **kwargs): self._pushToArray(messages_history, reset_message) if reset_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path_file_pattern) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Reset failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _createDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_EA | FILE_WRITE_EA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | READ_CONTROL | DELETE | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_CREATE, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): callback(path) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = '\x01')) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _rename_SMB2(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout messages_history = [ ] new_path = new_path.replace('/', '\\') if new_path.startswith('\\'): new_path = new_path[1:] if new_path.endswith('\\'): new_path = new_path[:-1] old_path = old_path.replace('/', '\\') if old_path.startswith('\\'): old_path = old_path[1:] if old_path.endswith('\\'): old_path = old_path[:-1] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(old_path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) def sendRename(tid, fid): data = '\x00'*16 + struct.pack('= 0xFFFF: # MID cannot be 0xFFFF. [MS-CIFS]: 2.2.1.6.2 # We don't use MID of 0 as MID can be reused for SMB_COM_TRANSACTION2_SECONDARY messages # where if mid=0, _sendSMBMessage will re-assign new MID values again self.mid = 1 return self.mid def _updateState_SMB1(self, message): if message.isReply: if message.command == SMB_COM_NEGOTIATE: if not message.status.hasError: self.has_negotiated = True self.log.info('SMB dialect negotiation successful (ExtendedSecurity:%s)', message.hasExtendedSecurity) self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_NEGOTIATE' % message.status.internal_value, message.raw_data, message) elif message.command == SMB_COM_SESSION_SETUP_ANDX: if message.hasExtendedSecurity: if not message.status.hasError: try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (with extended security) successful!') self.onAuthOK() else: raise ProtocolError('SMB_COM_SESSION_SETUP_ANDX status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError, ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status.internal_value == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Please check username and password.') self.onAuthFailed() elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account or password has expired.') self.onAuthFailed() elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been disabled.') self.onAuthFailed() elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Not allowed.') self.onAuthFailed() elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Domain not trusted.') self.onAuthFailed() elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, message.raw_data, message) else: if message.status.internal_value == 0: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (without extended security) successful!') self.onAuthOK() else: self.has_authenticated = False self.log.info('Authentication (without extended security) failed. Please check username and password') self.onAuthFailed() elif message.command == SMB_COM_TREE_CONNECT_ANDX: try: req = self.pending_requests[message.mid] except KeyError: pass else: if not message.status.hasError: self.connected_trees[req.kwargs['path']] = message.tid req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB1(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_raw_size = payload.max_raw_size self.max_buffer_size = payload.max_buffer_size self.max_mpx_count = payload.max_mpx_count self.use_plaintext_authentication = not bool(payload.security_mode & NEGOTIATE_ENCRYPT_PASSWORDS) if self.use_plaintext_authentication: self.log.warning('Remote server only supports plaintext authentication. Your password can be stolen easily over the network.') def _handleSessionChallenge_SMB1(self, message, ntlm_token): assert message.hasExtendedSecurity if message.uid and not self.uid: self.uid = message.uid server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(0, blob))) if self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRE: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLE: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = session_signing_key if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _handleNegotiateResponse_SMB1(self, message): if message.uid and not self.uid: self.uid = message.uid if message.hasExtendedSecurity or message.payload.supportsExtendedSecurity: ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(message.payload.session_key, blob))) else: nt_password, _, _ = ntlm.generateChallengeResponseV1(self.password, message.payload.challenge, False) self.log.info('Performing NTLMv1 authentication (without extended security) with challenge "%s" and hashed password of "%s"', binascii.hexlify(message.payload.challenge), binascii.hexlify(nt_password)) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__NoSecurityExtension(message.payload.session_key, self.username, nt_password, True, self.domain))) def _listShares_SMB1(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMBMessage(ComNTCreateAndxRequest('\\srvsvc', flags = NT_CREATE_REQUEST_EXTENDED_RESPONSE, access_mask = READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_READ_EA | FILE_APPEND_DATA | FILE_WRITE_DATA | FILE_READ_DATA, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, create_disp = FILE_OPEN, create_options = FILE_OPEN_NO_RECALL | FILE_NON_DIRECTORY_FILE, impersonation = SEC_IMPERSONATE, security_flags = 0)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: call_id = self._getNextRPCCallID() # See [MS-CIFS]: 2.2.5.6.1 for more information on TRANS_TRANSACT_NMPIPE (0x0026) parameters setup_bytes = struct.pack(' data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') short_name = short_name.decode('UTF-16LE') accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset else: break return '' def findFirstCB(find_message, **kwargs): self._pushToArray(messages_history, find_message) if not find_message.status.hasError: if not kwargs.has_key('total_count'): # TRANS2_FIND_FIRST2 response. [MS-CIFS]: 2.2.6.2.2 sid, search_count, end_of_search, _, last_name_offset = struct.unpack(' 0: if data_len > remaining_len: file_obj.write(read_message.payload.data[:remaining_len]) read_len += remaining_len remaining_len = 0 else: file_obj.write(read_message.payload.data) remaining_len -= data_len read_len += data_len else: file_obj.write(read_message.payload.data) read_len += data_len if (max_length > 0 and remaining_len <= 0) or data_len < (self.max_raw_size - 2): closeFid(read_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], read_len )) # Note that this is a tuple of 3-elements else: sendRead(read_message.tid, kwargs['fid'], kwargs['offset']+data_len, kwargs['file_attributes'], read_len, remaining_len) else: self._pushToArray(messages_history, read_message) closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _storeFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30): self._storeFileFromOffset_SMB1(service_name, path, file_obj, callback, errback, 0L, True, timeout) def _storeFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0041, # Sharing mode: Deny nothing to others + Open for writing open_mode = 0x0012 if truncate else 0x0011, # Create file if file does not exist. Overwrite or append depending on truncate parameter. search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: sendWrite(open_message.tid, open_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): # [MS-SMB] 2.2.4.5.2.2: The total SMB message size (inclusive of SMB header) must be not exceed the max_buffer_size. write_count = min(self.max_buffer_size-64, 0xFFFF-64) # SMB header is 32-bytes. We factor in another 32-bytes for the message parameter block data_bytes = file_obj.read(write_count) data_len = len(data_bytes) if data_len > 0: m = SMBMessage(ComWriteAndxRequest(fid = fid, offset = offset, data_bytes = data_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) else: closeFid(tid, fid) callback(( file_obj, offset )) # Note that this is a tuple of 2-elements def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if not write_message.status.hasError: sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) else: self._pushToArray(messages_history, write_message) closeFid(write_message.tid, kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteRequest(filename_pattern = path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) elif delete_message.status.internal_value == 0xC000000FL: # [MS-ERREF]: STATUS_NO_SUCH_FILE # If there are no matching files, we just treat as success instead of failing callback(path) elif delete_message.status.internal_value == 0xC00000BAL: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) elif delete_message.status.internal_value == 0xC0000034L: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendDelete(tid) def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendCreate(tid): m = SMBMessage(ComCreateDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendDelete(self.connected_trees[service_name]) def _rename_SMB1(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') new_path = new_path.replace('/', '\\') old_path = old_path.replace('/', '\\') messages_history = [ ] def sendRename(tid): m = SMBMessage(ComRenameRequest(old_path = old_path, new_path = new_path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback) self._pushToArray(messages_history, m) def renameCB(rename_message, **kwargs): self._pushToArray(messages_history, rename_message) if not rename_message.status.hasError: callback(( old_path, new_path )) # Note that this is a tuple of 2-elements else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendRename(connect_message.tid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendRename(self.connected_trees[service_name]) def _listSnapshots_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if not path.endswith('\\'): path += '\\' messages_history = [ ] results = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0040, # Sharing mode: Deny nothing to others open_mode = 0x0001, # Failed if file does not exist search_attributes = 0, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: sendEnumSnapshots(open_message.tid, open_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open path' % ( path, service_name ), messages_history)) def sendEnumSnapshots(tid, fid): # [MS-CIFS]: 2.2.7.2 # [MS-SMB]: 2.2.7.2.1 setup_bytes = struct.pack(' 10: messages_history.pop(0) messages_history.append(message) class SharedDevice: """ Contains information about a single shared device on the remote server. The following attributes are available: * name : An unicode string containing the name of the shared device * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 # They are used to identify the type of shared resource from the results from the NetrShareEnum in Server Service RPC DISK_TREE = 0x00 PRINT_QUEUE = 0x01 COMM_DEVICE = 0x02 IPC = 0x03 def __init__(self, type, name, comments): self._type = type self.name = name #: An unicode string containing the name of the shared device self.comments = comments #: An unicode string containing the user description of the shared device @property def type(self): """ Returns one of the following integral constants. - SharedDevice.DISK_TREE - SharedDevice.PRINT_QUEUE - SharedDevice.COMM_DEVICE - SharedDevice.IPC """ return self._type & 0xFFFF @property def isSpecial(self): """ Returns True if this shared device is a special share reserved for interprocess communication (IPC$) or remote administration of the server (ADMIN$). Can also refer to administrative shares such as C$, D$, E$, and so forth """ return bool(self._type & 0x80000000) @property def isTemporary(self): """ Returns True if this is a temporary share that is not persisted for creation each time the file server initializes. """ return bool(self._type & 0x40000000) def __unicode__(self): return u'Shared device: %s (type:0x%02x comments:%s)' % (self.name, self.type, self.comments ) class SharedFile: """ Contain information about a file/folder entry that is shared on the shared device. As an application developer, you should not need to instantiate a *SharedFile* instance directly in your application. These *SharedFile* instances are usually returned via a call to *listPath* method in :doc:`smb.SMBProtocol.SMBProtocolFactory`. If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). The following attributes are available: * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server * file_size : File size in number of bytes * alloc_size : Total number of bytes allocated to store this file * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): """A convenient property to return True if this file resource is a directory on the remote server""" return bool(self.file_attributes & ATTR_DIRECTORY) @property def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) @property def isNormal(self): """ A convenient property to return True if this is a normal file. Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. """ return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) def __unicode__(self): return u'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory ) class _PendingRequest: def __init__(self, mid, expiry_time, callback, errback, **kwargs): self.mid = mid self.expiry_time = expiry_time self.callback = callback self.errback = errback self.kwargs = kwargs ================================================ FILE: python2/smb/ntlm.py ================================================ import types, hmac, binascii, struct, random, string from .utils.rc4 import RC4_encrypt from utils.pyDes import des try: import hashlib hashlib.new('md4') def MD4(): return hashlib.new('md4') except ( ImportError, ValueError ): from utils.md4 import MD4 try: import hashlib def MD5(s): return hashlib.md5(s) except ImportError: import md5 def MD5(s): return md5.new(s) ################ # NTLMv2 Methods ################ # The following constants are defined in accordance to [MS-NLMP]: 2.2.2.5 NTLM_NegotiateUnicode = 0x00000001 NTLM_NegotiateOEM = 0x00000002 NTLM_RequestTarget = 0x00000004 NTLM_Unknown9 = 0x00000008 NTLM_NegotiateSign = 0x00000010 NTLM_NegotiateSeal = 0x00000020 NTLM_NegotiateDatagram = 0x00000040 NTLM_NegotiateLanManagerKey = 0x00000080 NTLM_Unknown8 = 0x00000100 NTLM_NegotiateNTLM = 0x00000200 NTLM_NegotiateNTOnly = 0x00000400 NTLM_Anonymous = 0x00000800 NTLM_NegotiateOemDomainSupplied = 0x00001000 NTLM_NegotiateOemWorkstationSupplied = 0x00002000 NTLM_Unknown6 = 0x00004000 NTLM_NegotiateAlwaysSign = 0x00008000 NTLM_TargetTypeDomain = 0x00010000 NTLM_TargetTypeServer = 0x00020000 NTLM_TargetTypeShare = 0x00040000 NTLM_NegotiateExtendedSecurity = 0x00080000 NTLM_NegotiateIdentify = 0x00100000 NTLM_Unknown5 = 0x00200000 NTLM_RequestNonNTSessionKey = 0x00400000 NTLM_NegotiateTargetInfo = 0x00800000 NTLM_Unknown4 = 0x01000000 NTLM_NegotiateVersion = 0x02000000 NTLM_Unknown3 = 0x04000000 NTLM_Unknown2 = 0x08000000 NTLM_Unknown1 = 0x10000000 NTLM_Negotiate128 = 0x20000000 NTLM_NegotiateKeyExchange = 0x40000000 NTLM_Negotiate56 = 0x80000000 NTLM_FLAGS = NTLM_NegotiateUnicode | \ NTLM_RequestTarget | \ NTLM_NegotiateSign | \ NTLM_NegotiateNTLM | \ NTLM_NegotiateAlwaysSign | \ NTLM_NegotiateExtendedSecurity | \ NTLM_NegotiateTargetInfo | \ NTLM_NegotiateVersion | \ NTLM_Negotiate128 | \ NTLM_NegotiateKeyExchange def generateNegotiateMessage(): """ References: =========== - [MS-NLMP]: 2.2.1.1 """ s = struct.pack('<8sII8s8s8s', 'NTLMSSP\0', 0x01, NTLM_FLAGS, '\0' * 8, # Domain '\0' * 8, # Workstation '\x06\x00\x72\x17\x00\x00\x00\x0F') # Version [MS-NLMP]: 2.2.2.10 return s def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, request_session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): """ References: =========== - [MS-NLMP]: 2.2.1.3 """ FORMAT = '<8sIHHIHHIHHIHHIHHIHHII' FORMAT_SIZE = struct.calcsize(FORMAT) # [MS-NLMP]: 3.1.5.1.2 # http://grutz.jingojango.net/exploits/davenport-ntlm.html session_key = session_signing_key = request_session_key if challenge_flags & NTLM_NegotiateKeyExchange: session_signing_key = "".join([ random.choice(string.digits+string.ascii_letters) for _ in range(16) ]).encode('ascii') session_key = RC4_encrypt(request_session_key, session_signing_key) lm_response_length = len(lm_response) lm_response_offset = FORMAT_SIZE nt_response_length = len(nt_response) nt_response_offset = lm_response_offset + lm_response_length domain_unicode = domain.encode('UTF-16LE') domain_length = len(domain_unicode) domain_offset = nt_response_offset + nt_response_length padding = '' if domain_offset % 2 != 0: padding = '\0' domain_offset += 1 user_unicode = user.encode('UTF-16LE') user_length = len(user_unicode) user_offset = domain_offset + domain_length workstation_unicode = workstation.encode('UTF-16LE') workstation_length = len(workstation_unicode) workstation_offset = user_offset + user_length session_key_length = len(session_key) session_key_offset = workstation_offset + workstation_length auth_flags = challenge_flags auth_flags &= ~NTLM_NegotiateVersion s = struct.pack(FORMAT, 'NTLMSSP\0', 0x03, lm_response_length, lm_response_length, lm_response_offset, nt_response_length, nt_response_length, nt_response_offset, domain_length, domain_length, domain_offset, user_length, user_length, user_offset, workstation_length, workstation_length, workstation_offset, session_key_length, session_key_length, session_key_offset, auth_flags) return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key, session_signing_key def decodeChallengeMessage(ntlm_data): """ References: =========== - [MS-NLMP]: 2.2.1.2 - [MS-NLMP]: 2.2.2.1 (AV_PAIR) """ FORMAT = '<8sIHHII8s8sHHI' FORMAT_SIZE = struct.calcsize(FORMAT) signature, message_type, \ targetname_len, targetname_maxlen, targetname_offset, \ flags, challenge, _, \ targetinfo_len, targetinfo_maxlen, targetinfo_offset, \ = struct.unpack(FORMAT, ntlm_data[:FORMAT_SIZE]) assert signature == 'NTLMSSP\0' assert message_type == 0x02 return challenge, flags, ntlm_data[targetinfo_offset:targetinfo_offset+targetinfo_len] def generateChallengeResponseV2(password, user, server_challenge, server_info, domain = '', client_challenge = None): client_timestamp = '\0' * 8 if not client_challenge: client_challenge = '' for i in range(0, 8): client_challenge += chr(random.getrandbits(8)) assert len(client_challenge) == 8 d = MD4() d.update(password.encode('UTF-16LE')) ntlm_hash = d.digest() # The NT password hash response_key = hmac.new(ntlm_hash, (user.upper() + domain).encode('UTF-16LE')).digest() # The NTLMv2 password hash. In [MS-NLMP], this is the result of NTOWFv2 and LMOWFv2 functions temp = '\x01\x01' + '\0'*6 + client_timestamp + client_challenge + '\0'*4 + server_info ntproofstr = hmac.new(response_key, server_challenge + temp).digest() nt_challenge_response = ntproofstr + temp lm_challenge_response = hmac.new(response_key, server_challenge + client_challenge).digest() + client_challenge session_key = hmac.new(response_key, ntproofstr).digest() return nt_challenge_response, lm_challenge_response, session_key ################ # NTLMv1 Methods ################ def expandDesKey(key): """Expand the key from a 7-byte password key into a 8-byte DES key""" s = chr(((ord(key[0]) >> 1) & 0x7f) << 1) s = s + chr(((ord(key[0]) & 0x01) << 6 | ((ord(key[1]) >> 2) & 0x3f)) << 1) s = s + chr(((ord(key[1]) & 0x03) << 5 | ((ord(key[2]) >> 3) & 0x1f)) << 1) s = s + chr(((ord(key[2]) & 0x07) << 4 | ((ord(key[3]) >> 4) & 0x0f)) << 1) s = s + chr(((ord(key[3]) & 0x0f) << 3 | ((ord(key[4]) >> 5) & 0x07)) << 1) s = s + chr(((ord(key[4]) & 0x1f) << 2 | ((ord(key[5]) >> 6) & 0x03)) << 1) s = s + chr(((ord(key[5]) & 0x3f) << 1 | ((ord(key[6]) >> 7) & 0x01)) << 1) s = s + chr((ord(key[6]) & 0x7f) << 1) return s def DESL(K, D): """ References: =========== - http://ubiqx.org/cifs/SMB.html (2.8.3.4) - [MS-NLMP]: Section 6 """ d1 = des(expandDesKey(K[0:7])) d2 = des(expandDesKey(K[7:14])) d3 = des(expandDesKey(K[14:16] + '\0' * 5)) return d1.encrypt(D) + d2.encrypt(D) + d3.encrypt(D) def generateChallengeResponseV1(password, server_challenge, has_extended_security = False, client_challenge = None): """ Generate a NTLMv1 response @param password: User password string @param server_challange: A 8-byte challenge string sent from the server @param has_extended_security: A boolean value indicating whether NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is enabled in the NTLM negFlag @param client_challenge: A 8-byte string representing client challenge. If None, it will be generated randomly if needed by the response generation @return: a tuple of ( NT challenge response string, LM challenge response string ) References: =========== - http://ubiqx.org/cifs/SMB.html (2.8.3.3 and 2.8.3.4) - [MS-NLMP]: 3.3.1 """ _password = (password.upper() + '\0' * 14)[:14] d1 = des(expandDesKey(_password[:7])) d2 = des(expandDesKey(_password[7:])) lm_response_key = d1.encrypt("KGS!@#$%") + d2.encrypt("KGS!@#$%") # LM password hash. In [MS-NLMP], this is the result of LMOWFv1 function d = MD4() d.update(password.encode('UTF-16LE')) nt_response_key = d.digest() # In [MS-NLMP], this is the result of NTOWFv1 function if has_extended_security: if not client_challenge: client_challenge = '' for i in range(0, 8): client_challenge += chr(random.getrandbits(8)) assert len(client_challenge) == 8 lm_challenge_response = client_challenge + '\0'*16 nt_challenge_response = DESL(nt_response_key, MD5(server_challenge + client_challenge).digest()[0:8]) else: nt_challenge_response = DESL(nt_response_key, server_challenge) # The result after DESL is the NT response lm_challenge_response = DESL(lm_response_key, server_challenge) # The result after DESL is the LM response d = MD4() d.update(nt_response_key) session_key = d.digest() return nt_challenge_response, lm_challenge_response, session_key ================================================ FILE: python2/smb/security_descriptors.py ================================================ """ This module implements security descriptors, and the partial structures used in them, as specified in [MS-DTYP]. """ import struct # Security descriptor control flags # [MS-DTYP]: 2.4.6 SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001 SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002 SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004 SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008 SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010 SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020 SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040 SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080 SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100 SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200 SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400 SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800 SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000 SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000 SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000 SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000 # ACE types # [MS-DTYP]: 2.4.4.1 ACE_TYPE_ACCESS_ALLOWED = 0x00 ACE_TYPE_ACCESS_DENIED = 0x01 ACE_TYPE_SYSTEM_AUDIT = 0x02 ACE_TYPE_SYSTEM_ALARM = 0x03 ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04 ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05 ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06 ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07 ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08 ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09 ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10 ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11 ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12 ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13 # ACE flags # [MS-DTYP]: 2.4.4.1 ACE_FLAG_OBJECT_INHERIT = 0x01 ACE_FLAG_CONTAINER_INHERIT = 0x02 ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04 ACE_FLAG_INHERIT_ONLY = 0x08 ACE_FLAG_INHERITED = 0x10 ACE_FLAG_SUCCESSFUL_ACCESS = 0x40 ACE_FLAG_FAILED_ACCESS = 0x80 # Pre-defined well-known SIDs # [MS-DTYP]: 2.4.2.4 SID_NULL = "S-1-0-0" SID_EVERYONE = "S-1-1-0" SID_LOCAL = "S-1-2-0" SID_CONSOLE_LOGON = "S-1-2-1" SID_CREATOR_OWNER = "S-1-3-0" SID_CREATOR_GROUP = "S-1-3-1" SID_OWNER_SERVER = "S-1-3-2" SID_GROUP_SERVER = "S-1-3-3" SID_OWNER_RIGHTS = "S-1-3-4" SID_NT_AUTHORITY = "S-1-5" SID_DIALUP = "S-1-5-1" SID_NETWORK = "S-1-5-2" SID_BATCH = "S-1-5-3" SID_INTERACTIVE = "S-1-5-4" SID_SERVICE = "S-1-5-6" SID_ANONYMOUS = "S-1-5-7" SID_PROXY = "S-1-5-8" SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9" SID_PRINCIPAL_SELF = "S-1-5-10" SID_AUTHENTICATED_USERS = "S-1-5-11" SID_RESTRICTED_CODE = "S-1-5-12" SID_TERMINAL_SERVER_USER = "S-1-5-13" SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14" SID_THIS_ORGANIZATION = "S-1-5-15" SID_IUSR = "S-1-5-17" SID_LOCAL_SYSTEM = "S-1-5-18" SID_LOCAL_SERVICE = "S-1-5-19" SID_NETWORK_SERVICE = "S-1-5-20" SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496" SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497" SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544" SID_BUILTIN_USERS = "S-1-5-32-545" SID_BUILTIN_GUESTS = "S-1-5-32-546" SID_POWER_USERS = "S-1-5-32-547" SID_ACCOUNT_OPERATORS = "S-1-5-32-548" SID_SERVER_OPERATORS = "S-1-5-32-549" SID_PRINTER_OPERATORS = "S-1-5-32-550" SID_BACKUP_OPERATORS = "S-1-5-32-551" SID_REPLICATOR = "S-1-5-32-552" SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554" SID_REMOTE_DESKTOP = "S-1-5-32-555" SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556" SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557" SID_PERFMON_USERS = "S-1-5-32-558" SID_PERFLOG_USERS = "S-1-5-32-559" SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560" SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561" SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562" SID_IIS_IUSRS = "S-1-5-32-568" SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569" SID_EVENT_LOG_READERS = "S-1-5-32-573" SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574" SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575" SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576" SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577" SID_HYPER_V_ADMINS = "S-1-5-32-578" SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579" SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580" SID_WRITE_RESTRICTED_CODE = "S-1-5-33" SID_NTLM_AUTHENTICATION = "S-1-5-64-10" SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14" SID_DIGEST_AUTHENTICATION = "S-1-5-64-21" SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1" SID_NT_SERVICE = "S-1-5-80" SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0" SID_LOCAL_ACCOUNT = "S-1-5-113" SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114" SID_OTHER_ORGANIZATION = "S-1-5-1000" SID_ALL_APP_PACKAGES = "S-1-15-2-1" SID_ML_UNTRUSTED = "S-1-16-0" SID_ML_LOW = "S-1-16-4096" SID_ML_MEDIUM = "S-1-16-8192" SID_ML_MEDIUM_PLUS = "S-1-16-8448" SID_ML_HIGH = "S-1-16-12288" SID_ML_SYSTEM = "S-1-16-16384" SID_ML_PROTECTED_PROCESS = "S-1-16-20480" SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1" SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2" SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3" SID_KEY_TRUST_IDENTITY = "S-1-18-4" SID_KEY_PROPERTY_MFA = "S-1-18-5" SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6" class SID(object): """ A Windows security identifier. Represents a single principal, such a user or a group, as a sequence of numbers consisting of the revision, identifier authority, and a variable-length list of subauthorities. See [MS-DTYP]: 2.4.2 """ def __init__(self, revision, identifier_authority, subauthorities): #: Revision, should always be 1. self.revision = revision #: An integer representing the identifier authority. self.identifier_authority = identifier_authority #: A list of integers representing all subauthorities. self.subauthorities = subauthorities def __str__(self): """ String representation, as specified in [MS-DTYP]: 2.4.2.1 """ if self.identifier_authority >= 2**32: id_auth = '%#x' % (self.identifier_authority,) else: id_auth = self.identifier_authority auths = [self.revision, id_auth] + self.subauthorities return 'S-' + '-'.join(str(subauth) for subauth in auths) def __repr__(self): return 'SID(%r)' % (str(self),) @classmethod def from_bytes(cls, data, return_tail=False): revision, subauth_count = struct.unpack('Q', '\x00\x00' + data[2:8])[0] subauth_data = data[8:] subauthorities = [struct.unpack('= size body = data[header_size:size] additional_data = {} # In all ACE types, the mask immediately follows the header. mask = struct.unpack('= size for i in range(count): ace_size = struct.unpack(''), os.linesep )) b.write('Status: 0x%08X %s' % ( self.status, os.linesep )) b.write('Flags: 0x%02X %s' % ( self.flags, os.linesep )) b.write('PID: %d %s' % ( self.pid, os.linesep )) b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, binascii.hexlify(self.data), os.linesep )) return b.getvalue() def reset(self): self.raw_data = '' self.command = 0 self.status = 0 self.flags = 0 self.next_command_offset = 0 self.mid = 0 self.session_id = 0 self.signature = '\0'*16 self.payload = None self.data = '' # For async SMB2 message self.async_id = 0 # For sync SMB2 message self.pid = 0 self.tid = 0 # Not used in this class. Maintained for compatibility with SMBMessage class self.flags2 = 0 self.uid = 0 self.security = 0L self.parameters_data = '' def encode(self): """ Encode this SMB2 message into a series of bytes suitable to be embedded with a NetBIOS session message. AssertionError will be raised if this SMB message has not been initialized with a Payload instance @return: a string containing the encoded SMB2 message """ assert self.payload self.pid = os.getpid() self.payload.prepare(self) headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, '\xFESMB', self.HEADER_SIZE, 0, self.status, self.command, 0, self.flags) + \ struct.pack(self.SYNC_HEADER_STRUCT_FORMAT, self.next_command_offset, self.mid, self.pid, self.tid, self.session_id, self.signature) return headers_data + self.data def decode(self, buf): """ Decodes the SMB message in buf. All fields of the SMB2Message object will be reset to default values before decoding. On errors, do not assume that the fields will be reinstated back to what they are before this method is invoked. References ========== - [MS-SMB2]: 2.2.1 @param buf: data containing one complete SMB2 message @type buf: string @return: a positive integer indicating the number of bytes used in buf to decode this SMB message @raise ProtocolError: raised when decoding fails """ buf_len = len(buf) if buf_len < 64: # All SMB2 headers must be at least 64 bytes. [MS-SMB2]: 2.2.1.1, 2.2.1.2 raise ProtocolError('Not enough data to decode SMB2 header', buf) self.reset() protocol, struct_size, self.credit_charge, self.status, \ self.command, self.credit_re, self.flags = struct.unpack(self.HEADER_STRUCT_FORMAT, buf[:self.HEADER_STRUCT_SIZE]) if protocol != '\xFESMB': raise ProtocolError('Invalid 4-byte SMB2 protocol field', buf) if struct_size != self.HEADER_SIZE: raise ProtocolError('Invalid SMB2 header structure size') if self.isAsync: if buf_len < self.HEADER_STRUCT_SIZE+self.ASYNC_HEADER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB2 header', buf) self.next_command_offset, self.mid, self.async_id, self.session_id, \ self.signature = struct.unpack(self.ASYNC_HEADER_STRUCT_FORMAT, buf[self.HEADER_STRUCT_SIZE:self.HEADER_STRUCT_SIZE+self.ASYNC_HEADER_STRUCT_SIZE]) else: if buf_len < self.HEADER_STRUCT_SIZE+self.SYNC_HEADER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB2 header', buf) self.next_command_offset, self.mid, self.pid, self.tid, self.session_id, \ self.signature = struct.unpack(self.SYNC_HEADER_STRUCT_FORMAT, buf[self.HEADER_STRUCT_SIZE:self.HEADER_STRUCT_SIZE+self.SYNC_HEADER_STRUCT_SIZE]) if self.next_command_offset > 0: self.raw_data = buf[:self.next_command_offset] self.data = buf[self.HEADER_SIZE:self.next_command_offset] else: self.raw_data = buf self.data = buf[self.HEADER_SIZE:] self._decodeCommand() if self.payload: self.payload.decode(self) return len(self.raw_data) def _decodeCommand(self): if self.command == SMB2_COM_READ: self.payload = SMB2ReadResponse() elif self.command == SMB2_COM_WRITE: self.payload = SMB2WriteResponse() elif self.command == SMB2_COM_QUERY_DIRECTORY: self.payload = SMB2QueryDirectoryResponse() elif self.command == SMB2_COM_CREATE: self.payload = SMB2CreateResponse() elif self.command == SMB2_COM_CLOSE: self.payload = SMB2CloseResponse() elif self.command == SMB2_COM_QUERY_INFO: self.payload = SMB2QueryInfoResponse() elif self.command == SMB2_COM_SET_INFO: self.payload = SMB2SetInfoResponse() elif self.command == SMB2_COM_IOCTL: self.payload = SMB2IoctlResponse() elif self.command == SMB2_COM_TREE_CONNECT: self.payload = SMB2TreeConnectResponse() elif self.command == SMB2_COM_SESSION_SETUP: self.payload = SMB2SessionSetupResponse() elif self.command == SMB2_COM_NEGOTIATE: self.payload = SMB2NegotiateResponse() elif self.command == SMB2_COM_ECHO: self.payload = SMB2EchoResponse() @property def isAsync(self): return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): return bool(self.flags & SMB2_FLAGS_SERVER_TO_REDIR) class Structure: def initMessage(self, message): pass def prepare(self, message): raise NotImplementedError def decode(self, message): raise NotImplementedError class SMB2NegotiateResponse(Structure): """ Contains information on the SMB2_NEGOTIATE response from server After calling the decode method, each instance will contain the following attributes, - security_mode (integer) - dialect_revision (integer) - server_guid (string) - max_transact_size (integer) - max_read_size (integer) - max_write_size (integer) - system_time (long) - server_start_time (long) - security_blob (string) References: =========== - [MS-SMB2]: 2.2.4 """ STRUCTURE_FORMAT = " 0 # SMB2_SESSION_FLAG_IS_GUEST @property def isAnonymousSession(self): return (self.session_flags & 0x0002) > 0 # SMB2_SESSION_FLAG_IS_NULL def decode(self, message): assert message.command == SMB2_COM_SESSION_SETUP struct_size, self.session_flags, security_blob_offset, security_blob_len \ = struct.unpack(self.STRUCTURE_FORMAT, message.raw_data[SMB2Message.HEADER_SIZE:SMB2Message.HEADER_SIZE+self.STRUCTURE_SIZE]) self.security_blob = message.raw_data[security_blob_offset:security_blob_offset+security_blob_len] class SMB2TreeConnectRequest(Structure): """ References: =========== - [MS-SMB2]: 2.2.9 """ STRUCTURE_FORMAT = " 0: self.in_data = message.raw_data[input_offset:input_offset+input_len] else: self.in_data = '' if output_len > 0: self.out_data = message.raw_data[output_offset:output_offset+output_len] else: self.out_data = '' class SMB2CloseRequest(Structure): """ References: =========== - [MS-SMB2]: 2.2.15 """ STRUCTURE_FORMAT = "> 24, self.internal_value & 0xFFFF ) @property def hasError(self): return self.internal_value != 0 class SMBMessage: HEADER_STRUCT_FORMAT = "<4sBIBHHQxxHHHHB" HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) log = logging.getLogger('SMB.SMBMessage') protocol = 1 def __init__(self, payload = None): self.reset() if payload: self.payload = payload self.payload.initMessage(self) def __str__(self): b = StringIO() b.write('Command: 0x%02X (%s) %s' % ( self.command, SMB_COMMAND_NAMES.get(self.command, ''), os.linesep )) b.write('Status: %s %s' % ( str(self.status), os.linesep )) b.write('Flags: 0x%02X %s' % ( self.flags, os.linesep )) b.write('Flags2: 0x%04X %s' % ( self.flags2, os.linesep )) b.write('PID: %d %s' % ( self.pid, os.linesep )) b.write('UID: %d %s' % ( self.uid, os.linesep )) b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Security: 0x%016X %s' % ( self.security, os.linesep )) b.write('Parameters: %d bytes %s%s %s' % ( len(self.parameters_data), os.linesep, binascii.hexlify(self.parameters_data), os.linesep )) b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, binascii.hexlify(self.data), os.linesep )) return b.getvalue() def reset(self): self.raw_data = '' self.command = 0 self.status = SMBError() self.flags = 0 self.flags2 = 0 self.pid = 0 self.tid = 0 self.uid = 0 self.mid = 0 self.security = 0L self.parameters_data = '' self.data = '' self.payload = None @property def isReply(self): return bool(self.flags & SMB_FLAGS_REPLY) @property def hasExtendedSecurity(self): return bool(self.flags2 & SMB_FLAGS2_EXTENDED_SECURITY) def encode(self): """ Encode this SMB message into a series of bytes suitable to be embedded with a NetBIOS session message. AssertionError will be raised if this SMB message has not been initialized with a Payload instance @return: a string containing the encoded SMB message """ assert self.payload self.pid = os.getpid() self.payload.prepare(self) parameters_len = len(self.parameters_data) assert parameters_len % 2 == 0 headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, '\xFFSMB', self.command, self.status.internal_value, self.flags, self.flags2, (self.pid >> 16) & 0xFFFF, self.security, self.tid, self.pid & 0xFFFF, self.uid, self.mid, int(parameters_len / 2)) return headers_data + self.parameters_data + struct.pack(' 0 and buf_len < (datalen_offset + 2 + body_len): # Not enough data in buf to decode body raise ProtocolError('Not enough data. Body decoding failed', buf) self.parameters_data = buf[offset:datalen_offset] if body_len > 0: self.data = buf[datalen_offset+2:datalen_offset+2+body_len] self.raw_data = buf self._decodePayload() return self.HEADER_STRUCT_SIZE + params_count * 2 + 2 + body_len def _decodePayload(self): if self.command == SMB_COM_READ_ANDX: self.payload = ComReadAndxResponse() elif self.command == SMB_COM_WRITE_ANDX: self.payload = ComWriteAndxResponse() elif self.command == SMB_COM_TRANSACTION: self.payload = ComTransactionResponse() elif self.command == SMB_COM_TRANSACTION2: self.payload = ComTransaction2Response() elif self.command == SMB_COM_OPEN_ANDX: self.payload = ComOpenAndxResponse() elif self.command == SMB_COM_NT_CREATE_ANDX: self.payload = ComNTCreateAndxResponse() elif self.command == SMB_COM_TREE_CONNECT_ANDX: self.payload = ComTreeConnectAndxResponse() elif self.command == SMB_COM_ECHO: self.payload = ComEchoResponse() elif self.command == SMB_COM_SESSION_SETUP_ANDX: self.payload = ComSessionSetupAndxResponse() elif self.command == SMB_COM_NEGOTIATE: self.payload = ComNegotiateResponse() if self.payload: self.payload.decode(self) class Payload: DEFAULT_ANDX_PARAM_HEADER = '\xFF\x00\x00\x00' DEFAULT_ANDX_PARAM_SIZE = 4 def initMessage(self, message): # SMB_FLAGS2_UNICODE must always be enabled. Without this, almost all the Payload subclasses will need to be # rewritten to check for OEM/Unicode strings which will be tedious. Fortunately, almost all tested CIFS services # support SMB_FLAGS2_UNICODE by default. assert message.payload == self message.flags = SMB_FLAGS_CASE_INSENSITIVE | SMB_FLAGS_CANONICALIZED_PATHS message.flags2 = SMB_FLAGS2_UNICODE | SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_LONG_NAMES | SMB_FLAGS2_EAS if SUPPORT_EXTENDED_SECURITY: message.flags2 |= SMB_FLAGS2_EXTENDED_SECURITY | SMB_FLAGS2_SMB_SECURITY_SIGNATURE def prepare(self, message): raise NotImplementedError def decode(self, message): raise NotImplementedError class ComNegotiateRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.52.1 - [MS-SMB]: 2.2.4.5.1 """ def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_NEGOTIATE def prepare(self, message): assert message.payload == self message.parameters_data = '' if SUPPORT_SMB2: message.data = ''.join(map(lambda s: '\x02'+s+'\x00', DIALECTS + DIALECTS2)) else: message.data = ''.join(map(lambda s: '\x02'+s+'\x00', DIALECTS)) class ComNegotiateResponse(Payload): """ Contains information on the SMB_COM_NEGOTIATE response from server After calling the decode method, each instance will contain the following attributes, - security_mode (integer) - max_mpx_count (integer) - max_number_vcs (integer) - max_buffer_size (long) - max_raw_size (long) - session_key (long) - capabilities (long) - system_time (long) - server_time_zone (integer) - challenge_length (integer) If the underlying SMB message's flag2 does not have SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - challenge (string) - domain (unicode) If the underlying SMB message's flags2 has SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - server_guid (string) - security_blob (string) References: =========== - [MS-SMB]: 2.2.4.5.2.1 - [MS-CIFS]: 2.2.4.52.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: if data_len >= self.challenge_length: self.challenge = message.data[:self.challenge_length] s = '' offset = self.challenge_length while offset < data_len: _s = message.data[offset:offset+2] if _s == '\0\0': self.domain = s.decode('UTF-16LE') break else: s += _s offset += 2 else: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (without security extensions) Challenge field', message.raw_data, message) else: if data_len < 16: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (with security extensions) ServerGUID field', message.raw_data, message) self.server_guid = message.data[:16] self.security_blob = message.data[16:] @property def supportsExtendedSecurity(self): return bool(self.capabilities & CAP_EXTENDED_SECURITY) class ComSessionSetupAndxRequest__WithSecurityExtension(Payload): """ References: =========== - [MS-SMB]: 2.2.4.6.1 """ PAYLOAD_STRUCT_FORMAT = ' 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = '' if offset % 4 != 0: padding2 = '\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransactionResponse(Payload): """ Contains information about a SMB_COM_TRANSACTION response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.33.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComTransaction2Request(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.46.1 """ PAYLOAD_STRUCT_FORMAT = 'HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, params_bytes = '', data_bytes = '', setup_bytes = '', flags = 0, timeout = 0): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) self.max_params_count = max_params_count self.max_data_count = max_data_count self.max_setup_count = max_setup_count self.flags = flags self.timeout = timeout self.params_bytes = params_bytes self.data_bytes = data_bytes self.setup_bytes = setup_bytes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_TRANSACTION2 def prepare(self, message): setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) name = '\0\0' padding0 = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: padding0 = '\0' offset += 1 offset += 2 # For the name field padding1 = '' if offset % 4 != 0: padding1 = '\0'*(4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = '' if offset % 4 != 0: padding2 = '\0'*(4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransaction2Response(Payload): """ Contains information about a SMB_COM_TRANSACTION2 response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.46.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComCloseRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.5.1 """ PAYLOAD_STRUCT_FORMAT = '> 32) # OffsetHigh field defined in [MS-SMB]: 2.2.4.3.1 message.data = '\0' + self.data_bytes class ComWriteAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.43.2 - [MS-SMB]: 2.2.4.3.2 """ PAYLOAD_STRUCT_FORMAT = '> 32), # Note that in [MS-SMB]: 2.2.4.2.1, this field can also act as MaxCountHigh field self.remaining, # In [MS-CIFS]: 2.2.4.42.1, this field must be set to 0x0000 self.offset >> 32) message.data = '' class ComReadAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.42.2 - [MS-SMB]: 2.2.4.2.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: params_bytes_offset = offset else: params_bytes_offset = 0 offset += params_bytes_len padding1 = '' if offset % 4 != 0: padding1 = '\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2), self.function) + \ self.setup_bytes message.data = padding0 + self.params_bytes + padding1 + self.data_bytes class ComNTTransactResponse(Payload): """ Contains information about a SMB_COM_NT_TRANSACT response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.62.2 """ PAYLOAD_STRUCT_FORMAT = '<3sIIIIIIIIBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_NT_TRANSACT if not message.status.hasError: _, self.total_params_count, self.total_data_count, \ params_count, params_offset, params_displ, \ data_count, data_offset, data_displ, setup_count = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_count*2] if params_count > 0: params_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.params_bytes = message.data[params_offset:params_offset+params_count] else: self.params_bytes = '' if data_count > 0: data_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.data_bytes = message.data[data_offset:data_offset+data_count] else: self.data_bytes = '' ================================================ FILE: python2/smb/utils/README.txt ================================================ md4.py and U32.py Both modules downloaded from http://www.oocities.org/rozmanov/python/md4.html. Licensed under LGPL pyDes.py 2.0.0 Downloaded from http://twhiteman.netfirms.com/des.html Licensed under public domain sha256.py Downloaded from http://xbmc-addons.googlecode.com/svn-history/r1686/trunk/scripts/OpenSubtitles_OSD/resources/lib/sha256.py Licensed under MIT ================================================ FILE: python2/smb/utils/U32.py ================================================ # U32.py implements 32-bit unsigned int class for Python # Version 1.0 # Copyright (C) 2001-2002 Dmitry Rozmanov # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # e-mail: dima@xenon.spb.ru # #==================================================================== C = 0x1000000000L #-------------------------------------------------------------------- def norm(n): return n & 0xFFFFFFFFL #==================================================================== class U32: v = 0L #-------------------------------------------------------------------- def __init__(self, value = 0): self.v = C + norm(abs(long(value))) #-------------------------------------------------------------------- def set(self, value = 0): self.v = C + norm(abs(long(value))) #-------------------------------------------------------------------- def __repr__(self): return hex(norm(self.v)) #-------------------------------------------------------------------- def __long__(self): return long(norm(self.v)) #-------------------------------------------------------------------- def __int__(self): return int(norm(self.v)) #-------------------------------------------------------------------- def __chr__(self): return chr(norm(self.v)) #-------------------------------------------------------------------- def __add__(self, b): r = U32() r.v = C + norm(self.v + b.v) return r #-------------------------------------------------------------------- def __sub__(self, b): r = U32() if self.v < b.v: r.v = C + norm(0x100000000L - (b.v - self.v)) else: r.v = C + norm(self.v - b.v) return r #-------------------------------------------------------------------- def __mul__(self, b): r = U32() r.v = C + norm(self.v * b.v) return r #-------------------------------------------------------------------- def __div__(self, b): r = U32() r.v = C + (norm(self.v) / norm(b.v)) return r #-------------------------------------------------------------------- def __mod__(self, b): r = U32() r.v = C + (norm(self.v) % norm(b.v)) return r #-------------------------------------------------------------------- def __neg__(self): return U32(self.v) #-------------------------------------------------------------------- def __pos__(self): return U32(self.v) #-------------------------------------------------------------------- def __abs__(self): return U32(self.v) #-------------------------------------------------------------------- def __invert__(self): r = U32() r.v = C + norm(~self.v) return r #-------------------------------------------------------------------- def __lshift__(self, b): r = U32() r.v = C + norm(self.v << b) return r #-------------------------------------------------------------------- def __rshift__(self, b): r = U32() r.v = C + (norm(self.v) >> b) return r #-------------------------------------------------------------------- def __and__(self, b): r = U32() r.v = C + norm(self.v & b.v) return r #-------------------------------------------------------------------- def __or__(self, b): r = U32() r.v = C + norm(self.v | b.v) return r #-------------------------------------------------------------------- def __xor__(self, b): r = U32() r.v = C + norm(self.v ^ b.v) return r #-------------------------------------------------------------------- def __not__(self): return U32(not norm(self.v)) #-------------------------------------------------------------------- def truth(self): return norm(self.v) #-------------------------------------------------------------------- def __cmp__(self, b): if norm(self.v) > norm(b.v): return 1 elif norm(self.v) < norm(b.v): return -1 else: return 0 #-------------------------------------------------------------------- def __nonzero__(self): return norm(self.v) ================================================ FILE: python2/smb/utils/__init__.py ================================================ def convertFILETIMEtoEpoch(t): return (t - 116444736000000000L) / 10000000.0; ================================================ FILE: python2/smb/utils/md4.py ================================================ # md4.py implements md4 hash class for Python # Version 1.0 # Copyright (C) 2001-2002 Dmitry Rozmanov # # based on md4.c from "the Python Cryptography Toolkit, version 1.0.0 # Copyright (C) 1995, A.M. Kuchling" # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # e-mail: dima@xenon.spb.ru # #==================================================================== # MD4 validation data md4_test= [ ('', 0x31d6cfe0d16ae931b73c59d7e0c089c0L), ("a", 0xbde52cb31de33e46245e05fbdbd6fb24L), ("abc", 0xa448017aaf21d8525fc10ae87aa6729dL), ("message digest", 0xd9130a8164549fe818874806e1c7014bL), ("abcdefghijklmnopqrstuvwxyz", 0xd79e1c308aa5bbcdeea8ed63df412da9L), ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 0x043f8582f241db351ce627e153e7f0e4L), ("12345678901234567890123456789012345678901234567890123456789012345678901234567890", 0xe33b4ddc9c38f2199c3e7b164fcc0536L), ] #==================================================================== from U32 import U32 #-------------------------------------------------------------------- class MD4: A = None B = None C = None D = None count, len1, len2 = None, None, None buf = [] #----------------------------------------------------- def __init__(self): self.A = U32(0x67452301L) self.B = U32(0xefcdab89L) self.C = U32(0x98badcfeL) self.D = U32(0x10325476L) self.count, self.len1, self.len2 = U32(0L), U32(0L), U32(0L) self.buf = [0x00] * 64 #----------------------------------------------------- def __repr__(self): r = 'A = %s, \nB = %s, \nC = %s, \nD = %s.\n' % (self.A.__repr__(), self.B.__repr__(), self.C.__repr__(), self.D.__repr__()) r = r + 'count = %s, \nlen1 = %s, \nlen2 = %s.\n' % (self.count.__repr__(), self.len1.__repr__(), self.len2.__repr__()) for i in range(4): for j in range(16): r = r + '%4s ' % hex(self.buf[i+j]) r = r + '\n' return r #----------------------------------------------------- def make_copy(self): dest = new() dest.len1 = self.len1 dest.len2 = self.len2 dest.A = self.A dest.B = self.B dest.C = self.C dest.D = self.D dest.count = self.count for i in range(self.count): dest.buf[i] = self.buf[i] return dest #----------------------------------------------------- def update(self, str): buf = [] for i in str: buf.append(ord(i)) ilen = U32(len(buf)) # check if the first length is out of range # as the length is measured in bits then multiplay it by 8 if (long(self.len1 + (ilen << 3)) < long(self.len1)): self.len2 = self.len2 + U32(1) self.len1 = self.len1 + (ilen << 3) self.len2 = self.len2 + (ilen >> 29) L = U32(0) bufpos = 0 while (long(ilen) > 0): if (64 - long(self.count)) < long(ilen): L = U32(64 - long(self.count)) else: L = ilen for i in range(int(L)): self.buf[i + int(self.count)] = buf[i + bufpos] self.count = self.count + L ilen = ilen - L bufpos = bufpos + int(L) if (long(self.count) == 64L): self.count = U32(0L) X = [] i = 0 for j in range(16): X.append(U32(self.buf[i]) + (U32(self.buf[i+1]) << 8) + \ (U32(self.buf[i+2]) << 16) + (U32(self.buf[i+3]) << 24)) i = i + 4 A = self.A B = self.B C = self.C D = self.D A = f1(A,B,C,D, 0, 3, X) D = f1(D,A,B,C, 1, 7, X) C = f1(C,D,A,B, 2,11, X) B = f1(B,C,D,A, 3,19, X) A = f1(A,B,C,D, 4, 3, X) D = f1(D,A,B,C, 5, 7, X) C = f1(C,D,A,B, 6,11, X) B = f1(B,C,D,A, 7,19, X) A = f1(A,B,C,D, 8, 3, X) D = f1(D,A,B,C, 9, 7, X) C = f1(C,D,A,B,10,11, X) B = f1(B,C,D,A,11,19, X) A = f1(A,B,C,D,12, 3, X) D = f1(D,A,B,C,13, 7, X) C = f1(C,D,A,B,14,11, X) B = f1(B,C,D,A,15,19, X) A = f2(A,B,C,D, 0, 3, X) D = f2(D,A,B,C, 4, 5, X) C = f2(C,D,A,B, 8, 9, X) B = f2(B,C,D,A,12,13, X) A = f2(A,B,C,D, 1, 3, X) D = f2(D,A,B,C, 5, 5, X) C = f2(C,D,A,B, 9, 9, X) B = f2(B,C,D,A,13,13, X) A = f2(A,B,C,D, 2, 3, X) D = f2(D,A,B,C, 6, 5, X) C = f2(C,D,A,B,10, 9, X) B = f2(B,C,D,A,14,13, X) A = f2(A,B,C,D, 3, 3, X) D = f2(D,A,B,C, 7, 5, X) C = f2(C,D,A,B,11, 9, X) B = f2(B,C,D,A,15,13, X) A = f3(A,B,C,D, 0, 3, X) D = f3(D,A,B,C, 8, 9, X) C = f3(C,D,A,B, 4,11, X) B = f3(B,C,D,A,12,15, X) A = f3(A,B,C,D, 2, 3, X) D = f3(D,A,B,C,10, 9, X) C = f3(C,D,A,B, 6,11, X) B = f3(B,C,D,A,14,15, X) A = f3(A,B,C,D, 1, 3, X) D = f3(D,A,B,C, 9, 9, X) C = f3(C,D,A,B, 5,11, X) B = f3(B,C,D,A,13,15, X) A = f3(A,B,C,D, 3, 3, X) D = f3(D,A,B,C,11, 9, X) C = f3(C,D,A,B, 7,11, X) B = f3(B,C,D,A,15,15, X) self.A = self.A + A self.B = self.B + B self.C = self.C + C self.D = self.D + D #----------------------------------------------------- def digest(self): res = [0x00] * 16 s = [0x00] * 8 padding = [0x00] * 64 padding[0] = 0x80 padlen, oldlen1, oldlen2 = U32(0), U32(0), U32(0) temp = self.make_copy() oldlen1 = temp.len1 oldlen2 = temp.len2 if (56 <= long(self.count)): padlen = U32(56 - long(self.count) + 64) else: padlen = U32(56 - long(self.count)) temp.update(int_array2str(padding[:int(padlen)])) s[0]= (oldlen1) & U32(0xFF) s[1]=((oldlen1) >> 8) & U32(0xFF) s[2]=((oldlen1) >> 16) & U32(0xFF) s[3]=((oldlen1) >> 24) & U32(0xFF) s[4]= (oldlen2) & U32(0xFF) s[5]=((oldlen2) >> 8) & U32(0xFF) s[6]=((oldlen2) >> 16) & U32(0xFF) s[7]=((oldlen2) >> 24) & U32(0xFF) temp.update(int_array2str(s)) res[ 0]= temp.A & U32(0xFF) res[ 1]=(temp.A >> 8) & U32(0xFF) res[ 2]=(temp.A >> 16) & U32(0xFF) res[ 3]=(temp.A >> 24) & U32(0xFF) res[ 4]= temp.B & U32(0xFF) res[ 5]=(temp.B >> 8) & U32(0xFF) res[ 6]=(temp.B >> 16) & U32(0xFF) res[ 7]=(temp.B >> 24) & U32(0xFF) res[ 8]= temp.C & U32(0xFF) res[ 9]=(temp.C >> 8) & U32(0xFF) res[10]=(temp.C >> 16) & U32(0xFF) res[11]=(temp.C >> 24) & U32(0xFF) res[12]= temp.D & U32(0xFF) res[13]=(temp.D >> 8) & U32(0xFF) res[14]=(temp.D >> 16) & U32(0xFF) res[15]=(temp.D >> 24) & U32(0xFF) return int_array2str(res) #==================================================================== # helpers def F(x, y, z): return (((x) & (y)) | ((~x) & (z))) def G(x, y, z): return (((x) & (y)) | ((x) & (z)) | ((y) & (z))) def H(x, y, z): return ((x) ^ (y) ^ (z)) def ROL(x, n): return (((x) << n) | ((x) >> (32-n))) def f1(a, b, c, d, k, s, X): return ROL(a + F(b, c, d) + X[k], s) def f2(a, b, c, d, k, s, X): return ROL(a + G(b, c, d) + X[k] + U32(0x5a827999L), s) def f3(a, b, c, d, k, s, X): return ROL(a + H(b, c, d) + X[k] + U32(0x6ed9eba1L), s) #-------------------------------------------------------------------- # helper function def int_array2str(array): str = '' for i in array: str = str + chr(i) return str #-------------------------------------------------------------------- # To be able to use md4.new() instead of md4.MD4() new = MD4 ================================================ FILE: python2/smb/utils/pyDes.py ================================================ ############################################################################# # Documentation # ############################################################################# # Author: Todd Whiteman # Date: 16th March, 2009 # Verion: 2.0.0 # License: Public Domain - free to do as you wish # Homepage: http://twhiteman.netfirms.com/des.html # # This is a pure python implementation of the DES encryption algorithm. # It's pure python to avoid portability issues, since most DES # implementations are programmed in C (for performance reasons). # # Triple DES class is also implemented, utilising the DES base. Triple DES # is either DES-EDE3 with a 24 byte key, or DES-EDE2 with a 16 byte key. # # See the README.txt that should come with this python module for the # implementation methods used. # # Thanks to: # * David Broadwell for ideas, comments and suggestions. # * Mario Wolff for pointing out and debugging some triple des CBC errors. # * Santiago Palladino for providing the PKCS5 padding technique. # * Shaya for correcting the PAD_PKCS5 triple des CBC errors. # """A pure python implementation of the DES and TRIPLE DES encryption algorithms. Class initialization -------------------- pyDes.des(key, [mode], [IV], [pad], [padmode]) pyDes.triple_des(key, [mode], [IV], [pad], [padmode]) key -> Bytes containing the encryption key. 8 bytes for DES, 16 or 24 bytes for Triple DES mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Length must be 8 bytes. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. I recommend to use PAD_PKCS5 padding, as then you never need to worry about any padding issues, as the padding can be removed unambiguously upon decrypting data that was encrypted using PAD_PKCS5 padmode. Common methods -------------- encrypt(data, [pad], [padmode]) decrypt(data, [pad], [padmode]) data -> Bytes to be encrypted/decrypted pad -> Optional argument. Only when using padmode of PAD_NORMAL. For encryption, adds this characters to the end of the data block when data is not a multiple of 8 bytes. For decryption, will remove the trailing characters that match this pad character from the last 8 bytes of the unencrypted data block. padmode -> Optional argument, set the padding mode, must be one of PAD_NORMAL or PAD_PKCS5). Defaults to PAD_NORMAL. Example ------- from pyDes import * data = "Please encrypt my data" k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) # For Python3, you'll need to use bytes, i.e.: # data = b"Please encrypt my data" # k = des(b"DESCRYPT", CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) assert k.decrypt(d, padmode=PAD_PKCS5) == data See the module source (pyDes.py) for more examples of use. You can also run the pyDes.py file without and arguments to see a simple test. Note: This code was not written for high-end systems needing a fast implementation, but rather a handy portable solution with small usage. """ import sys # _pythonMajorVersion is used to handle Python2 and Python3 differences. _pythonMajorVersion = sys.version_info[0] # Modes of crypting / cyphering ECB = 0 CBC = 1 # Modes of padding PAD_NORMAL = 1 PAD_PKCS5 = 2 # PAD_PKCS5: is a method that will unambiguously remove all padding # characters after decryption, when originally encrypted with # this padding mode. # For a good description of the PKCS5 padding technique, see: # http://www.faqs.org/rfcs/rfc1423.html # The base class shared by des and triple des. class _baseDes(object): def __init__(self, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): if IV: IV = self._guardAgainstUnicode(IV) if pad: pad = self._guardAgainstUnicode(pad) self.block_size = 8 # Sanity checking of arguments. if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if IV and len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") # Set the passed in variables self._mode = mode self._iv = IV self._padding = pad self._padmode = padmode def getKey(self): """getKey() -> bytes""" return self.__key def setKey(self, key): """Will set the crypting key for this object.""" key = self._guardAgainstUnicode(key) self.__key = key def getMode(self): """getMode() -> pyDes.ECB or pyDes.CBC""" return self._mode def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" self._mode = mode def getPadding(self): """getPadding() -> bytes of length 1. Padding character.""" return self._padding def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" if pad is not None: pad = self._guardAgainstUnicode(pad) self._padding = pad def getPadMode(self): """getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" return self._padmode def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" self._padmode = mode def getIV(self): """getIV() -> bytes""" return self._iv def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" if not IV or len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") IV = self._guardAgainstUnicode(IV) self._iv = IV def _padData(self, data, pad, padmode): # Pad data depending on the mode if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode == PAD_NORMAL: if len(data) % self.block_size == 0: # No padding required. return data if not pad: # Get the default padding. pad = self.getPadding() if not pad: raise ValueError("Data must be a multiple of " + str(self.block_size) + " bytes in length. Use padmode=PAD_PKCS5 or set the pad character.") data += (self.block_size - (len(data) % self.block_size)) * pad elif padmode == PAD_PKCS5: pad_len = 8 - (len(data) % self.block_size) if _pythonMajorVersion < 3: data += pad_len * chr(pad_len) else: data += bytes([pad_len] * pad_len) return data def _unpadData(self, data, pad, padmode): # Unpad data depending on the mode. if not data: return data if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if padmode == PAD_NORMAL: if not pad: # Get the default padding. pad = self.getPadding() if pad: data = data[:-self.block_size] + \ data[-self.block_size:].rstrip(pad) elif padmode == PAD_PKCS5: if _pythonMajorVersion < 3: pad_len = ord(data[-1]) else: pad_len = data[-1] data = data[:-pad_len] return data def _guardAgainstUnicode(self, data): # Only accept byte strings or ascii unicode values, otherwise # there is no way to correctly decode the data into bytes. if _pythonMajorVersion < 3: if isinstance(data, unicode): raise ValueError("pyDes can only work with bytes, not Unicode strings.") else: if isinstance(data, str): # Only accept ascii unicode values. try: return data.encode('ascii') except UnicodeEncodeError: pass raise ValueError("pyDes can only work with encoded strings, not Unicode.") return data ############################################################################# # DES # ############################################################################# class des(_baseDes): """DES encryption/decrytpion class Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key,[mode], [IV]) key -> Bytes containing the encryption key, must be exactly 8 bytes mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ # Permutation and translation tables for DES __pc1 = [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 ] # number left rotations of pc1 __left_rotations = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] # permuted choice key (table 2) __pc2 = [ 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 ] # initial permutation IP __ip = [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 ] # Expansion table for turning 32 bit blocks into 48 bits __expansion_table = [ 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0 ] # The (in)famous S-boxes __sbox = [ # S1 [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], # S2 [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], # S3 [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], # S4 [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], # S5 [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], # S6 [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], # S7 [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], # S8 [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] # 32-bit permutation function P used on the output of the S-boxes __p = [ 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23,13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24 ] # final permutation IP^-1 __fp = [ 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24 ] # Type of crypting being done ENCRYPT = 0x00 DECRYPT = 0x01 # Initialisation def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): # Sanity checking of arguments. if len(key) != 8: raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.") _baseDes.__init__(self, mode, IV, pad, padmode) self.key_size = 8 self.L = [] self.R = [] self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16) self.final = [] self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Must be 8 bytes.""" _baseDes.setKey(self, key) self.__create_sub_keys() def __String_to_BitList(self, data): """Turn the string data, into a list of bits (1, 0)'s""" if _pythonMajorVersion < 3: # Turn the strings into integers. Python 3 uses a bytes # class, which already has this behaviour. data = [ord(c) for c in data] l = len(data) * 8 result = [0] * l pos = 0 for ch in data: i = 7 while i >= 0: if ch & (1 << i) != 0: result[pos] = 1 else: result[pos] = 0 pos += 1 i -= 1 return result def __BitList_to_String(self, data): """Turn the list of bits -> data, into a string""" result = [] pos = 0 c = 0 while pos < len(data): c += data[pos] << (7 - (pos % 8)) if (pos % 8) == 7: result.append(c) c = 0 pos += 1 if _pythonMajorVersion < 3: return ''.join([ chr(c) for c in result ]) else: return bytes(result) def __permutate(self, table, block): """Permutate this block with the specified table""" return list(map(lambda x: block[x], table)) # Transform the secret key, so that it is ready for data processing # Create the 16 subkeys, K[1] - K[16] def __create_sub_keys(self): """Create the 16 subkeys K[1] to K[16] from the given key""" key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey())) i = 0 # Split into Left and Right sections self.L = key[:28] self.R = key[28:] while i < 16: j = 0 # Perform circular left shifts while j < des.__left_rotations[i]: self.L.append(self.L[0]) del self.L[0] self.R.append(self.R[0]) del self.R[0] j += 1 # Create one of the 16 subkeys through pc2 permutation self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R) i += 1 # Main part of the encryption algorithm, the number cruncher :) def __des_crypt(self, block, crypt_type): """Crypt the block of data through DES bit-manipulation""" block = self.__permutate(des.__ip, block) self.L = block[:32] self.R = block[32:] # Encryption starts from Kn[1] through to Kn[16] if crypt_type == des.ENCRYPT: iteration = 0 iteration_adjustment = 1 # Decryption starts from Kn[16] down to Kn[1] else: iteration = 15 iteration_adjustment = -1 i = 0 while i < 16: # Make a copy of R[i-1], this will later become L[i] tempR = self.R[:] # Permutate R[i - 1] to start creating R[i] self.R = self.__permutate(des.__expansion_table, self.R) # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration])) B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]] # Optimization: Replaced below commented code with above #j = 0 #B = [] #while j < len(self.R): # self.R[j] = self.R[j] ^ self.Kn[iteration][j] # j += 1 # if j % 6 == 0: # B.append(self.R[j-6:j]) # Permutate B[1] to B[8] using the S-Boxes j = 0 Bn = [0] * 32 pos = 0 while j < 8: # Work out the offsets m = (B[j][0] << 1) + B[j][5] n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4] # Find the permutation value v = des.__sbox[j][(m << 4) + n] # Turn value into bits, add it to result: Bn Bn[pos] = (v & 8) >> 3 Bn[pos + 1] = (v & 4) >> 2 Bn[pos + 2] = (v & 2) >> 1 Bn[pos + 3] = v & 1 pos += 4 j += 1 # Permutate the concatination of B[1] to B[8] (Bn) self.R = self.__permutate(des.__p, Bn) # Xor with L[i - 1] self.R = list(map(lambda x, y: x ^ y, self.R, self.L)) # Optimization: This now replaces the below commented code #j = 0 #while j < len(self.R): # self.R[j] = self.R[j] ^ self.L[j] # j += 1 # L[i] becomes R[i - 1] self.L = tempR i += 1 iteration += iteration_adjustment # Final permutation of R[16]L[16] self.final = self.__permutate(des.__fp, self.R + self.L) return self.final # Data to be encrypted/decrypted def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.") if not self.getPadding(): raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character") else: data += (self.block_size - (len(data) % self.block_size)) * self.getPadding() # print "Len of data: %f" % (len(data) / self.block_size) if self.getMode() == CBC: if self.getIV(): iv = self.__String_to_BitList(self.getIV()) else: raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering") # Split the data into blocks, crypting each one seperately i = 0 dict = {} result = [] #cached = 0 #lines = 0 while i < len(data): # Test code for caching encryption results #lines += 1 #if dict.has_key(data[i:i+8]): #print "Cached result for: %s" % data[i:i+8] # cached += 1 # result.append(dict[data[i:i+8]]) # i += 8 # continue block = self.__String_to_BitList(data[i:i+8]) # Xor with IV if using CBC mode if self.getMode() == CBC: if crypt_type == des.ENCRYPT: block = list(map(lambda x, y: x ^ y, block, iv)) #j = 0 #while j < len(block): # block[j] = block[j] ^ iv[j] # j += 1 processed_block = self.__des_crypt(block, crypt_type) if crypt_type == des.DECRYPT: processed_block = list(map(lambda x, y: x ^ y, processed_block, iv)) #j = 0 #while j < len(processed_block): # processed_block[j] = processed_block[j] ^ iv[j] # j += 1 iv = block else: iv = processed_block else: processed_block = self.__des_crypt(block, crypt_type) # Add the resulting crypted block to our list #d = self.__BitList_to_String(processed_block) #result.append(d) result.append(self.__BitList_to_String(processed_block)) #dict[data[i:i+8]] = d i += 8 # print "Lines: %d, cached: %d" % (lines, cached) # Return the full crypted string if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self.crypt(data, des.DECRYPT) return self._unpadData(data, pad, padmode) ############################################################################# # Triple DES # ############################################################################# class triple_des(_baseDes): """Triple DES encryption/decrytpion class This algorithm uses the DES-EDE3 (when a 24 byte key is supplied) or the DES-EDE2 (when a 16 byte key is supplied) encryption methods. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key, [mode], [IV]) key -> Bytes containing the encryption key, must be either 16 or 24 bytes long mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): _baseDes.__init__(self, mode, IV, pad, padmode) self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Either 16 or 24 bytes long.""" self.key_size = 24 # Use DES-EDE3 mode if len(key) != self.key_size: if len(key) == 16: # Use DES-EDE2 mode self.key_size = 16 else: raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long") if self.getMode() == CBC: if not self.getIV(): # Use the first 8 bytes of the key self._iv = key[:self.block_size] if len(self.getIV()) != self.block_size: raise ValueError("Invalid IV, must be 8 bytes in length") self.__key1 = des(key[:8], self._mode, self._iv, self._padding, self._padmode) self.__key2 = des(key[8:16], self._mode, self._iv, self._padding, self._padmode) if self.key_size == 16: self.__key3 = self.__key1 else: self.__key3 = des(key[16:], self._mode, self._iv, self._padding, self._padmode) _baseDes.setKey(self, key) # Override setter methods to work on all 3 keys. def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" _baseDes.setMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setMode(mode) def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" _baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key.setPadding(pad) def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" _baseDes.setPadMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setPadMode(mode) def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" _baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) # Pad the data accordingly. data = self._padData(data, pad, padmode) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): block = self.__key1.crypt(data[i:i+8], ENCRYPT) block = self.__key2.crypt(block, DECRYPT) block = self.__key3.crypt(block, ENCRYPT) self.__key1.setIV(block) self.__key2.setIV(block) self.__key3.setIV(block) result.append(block) i += 8 if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) else: data = self.__key1.crypt(data, ENCRYPT) data = self.__key2.crypt(data, DECRYPT) return self.__key3.crypt(data, ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting, no pad character is required for PAD_PKCS5. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): iv = data[i:i+8] block = self.__key3.crypt(iv, DECRYPT) block = self.__key2.crypt(block, ENCRYPT) block = self.__key1.crypt(block, DECRYPT) self.__key1.setIV(iv) self.__key2.setIV(iv) self.__key3.setIV(iv) result.append(block) i += 8 if _pythonMajorVersion < 3: data = ''.join(result) else: data = bytes.fromhex('').join(result) else: data = self.__key3.crypt(data, DECRYPT) data = self.__key2.crypt(data, ENCRYPT) data = self.__key1.crypt(data, DECRYPT) return self._unpadData(data, pad, padmode) ================================================ FILE: python2/smb/utils/rc4.py ================================================ def RC4_encrypt(key, data): S = list(range(256)) j = 0 key_len = len(key) for i in list(range(256)): j = (j + S[i] + ord(key[i % key_len])) % 256 S[i], S[j] = S[j], S[i] j = 0 y = 0 out = [] for char in data: j = (j + 1) % 256 y = (y + S[j]) % 256 S[j], S[y] = S[y], S[j] out.append(chr(ord(char) ^ S[(S[j] + S[y]) % 256])) return ''.join(out) ================================================ FILE: python2/smb/utils/sha256.py ================================================ __author__ = 'Thomas Dixon' __license__ = 'MIT' import copy, struct, sys digest_size = 32 blocksize = 1 def new(m=None): return sha256(m) class sha256(object): _k = (0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2) _h = (0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19) _output_size = 8 blocksize = 1 block_size = 64 digest_size = 32 def __init__(self, m=None): self._buffer = '' self._counter = 0 if m is not None: if type(m) is not str: raise TypeError, '%s() argument 1 must be string, not %s' % (self.__class__.__name__, type(m).__name__) self.update(m) def _rotr(self, x, y): return ((x >> y) | (x << (32-y))) & 0xFFFFFFFF def _sha256_process(self, c): w = [0]*64 w[0:15] = struct.unpack('!16L', c) for i in range(16, 64): s0 = self._rotr(w[i-15], 7) ^ self._rotr(w[i-15], 18) ^ (w[i-15] >> 3) s1 = self._rotr(w[i-2], 17) ^ self._rotr(w[i-2], 19) ^ (w[i-2] >> 10) w[i] = (w[i-16] + s0 + w[i-7] + s1) & 0xFFFFFFFF a,b,c,d,e,f,g,h = self._h for i in range(64): s0 = self._rotr(a, 2) ^ self._rotr(a, 13) ^ self._rotr(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) t2 = s0 + maj s1 = self._rotr(e, 6) ^ self._rotr(e, 11) ^ self._rotr(e, 25) ch = (e & f) ^ ((~e) & g) t1 = h + s1 + ch + self._k[i] + w[i] h = g g = f f = e e = (d + t1) & 0xFFFFFFFF d = c c = b b = a a = (t1 + t2) & 0xFFFFFFFF self._h = [(x+y) & 0xFFFFFFFF for x,y in zip(self._h, [a,b,c,d,e,f,g,h])] def update(self, m): if not m: return if type(m) is not str: raise TypeError, '%s() argument 1 must be string, not %s' % (sys._getframe().f_code.co_name, type(m).__name__) self._buffer += m self._counter += len(m) while len(self._buffer) >= 64: self._sha256_process(self._buffer[:64]) self._buffer = self._buffer[64:] def digest(self): mdi = self._counter & 0x3F length = struct.pack('!Q', self._counter<<3) if mdi < 56: padlen = 55-mdi else: padlen = 119-mdi r = self.copy() r.update('\x80'+('\x00'*padlen)+length) return ''.join([struct.pack('!L', i) for i in r._h[:self._output_size]]) def hexdigest(self): return self.digest().encode('hex') def copy(self): return copy.deepcopy(self) ================================================ FILE: python2/tests/DirectSMBConnectionTests/__init__.py ================================================ ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_SMBHandler.py ================================================ # -*- coding: utf-8 -*- import os, urllib, urllib2, time, random from StringIO import StringIO from smb.SMBHandler import SMBHandler import util try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() def test_basic(): # Basic test for smb URLs director = urllib2.build_opener(SMBHandler) fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/rfc1001.txt' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert len(s) == 158437 fh.close() def test_unicode(): # Test smb URLs with unicode paths director = urllib2.build_opener(SMBHandler) fh = director.open(u'smb://%(user)s:%(password)s@%(server_ip)s/smbtest/测试文件夹/垃圾文件.dat' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert len(s) == 256000 fh.close() TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def test_upload(): info = util.getConnectionInfo() info['filename'] = os.sep + 'StoreTest-%d-%d.dat' % ( time.time(), random.randint(0, 10000) ) director = urllib2.build_opener(SMBHandler) upload_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info, data = open(TEST_FILENAME, 'rb')) retr_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info) s = retr_fh.read() md = MD5() md.update(s) assert md.hexdigest() == TEST_DIGEST assert len(s) == TEST_FILESIZE def test_overwrite(): info = util.getConnectionInfo() info['filename'] = os.sep + 'StoreTest-%d-%d.dat' % ( time.time(), random.randint(0, 10000) ) test_s = 'test1234' test_md = MD5() test_md.update(test_s) director = urllib2.build_opener(SMBHandler) upload_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info, data = StringIO(test_s)) retr_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info) s = retr_fh.read() md = MD5() md.update(s) assert md.hexdigest() == test_md.hexdigest() assert len(s) == len(test_s) upload_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info, data = open(TEST_FILENAME, 'rb')) retr_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info) s = retr_fh.read() md = MD5() md.update(s) ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_auth.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn, conn2, conn3 = None, None, None def teardown_func(): global conn, conn2, conn3 if conn: conn.close() if conn2: conn2.close() if conn3: conn3.close(); @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB1(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB1_callable_password(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], lambda: info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB1(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB2(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB2(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, time, random from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_english_directory_SMB1(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2, teardown_func) def test_english_directory_SMB2(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB1, teardown_func) def test_unicode_directory_SMB1(): global conn path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2, teardown_func) def test_unicode_directory_SMB2(): global conn path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_echo.py ================================================ import random from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup conn = None def setup_func(): global conn info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func, teardown_func) def test_echo(): global conn data = '%d' % random.randint(1000, 9999) assert conn.echo(data) == data ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_listpath.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from smb.smb_constants import * from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB1, teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB1, teardown_func) def test_listPathWithManyFiles_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames)==999 @with_setup(setup_func_SMB2, teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB2, teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathWithManyFiles_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames)==999 @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterForDirectory_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterForDirectory_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterForFiles_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterForFiles_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterPattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterPattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterUnicodePattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterUnicodePattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_listshares.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in map(lambda r: r.name.lower(), results) @with_setup(setup_func_SMB2, teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() assert 'smbtest' in map(lambda r: r.name.lower(), results) ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_listsnapshots.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 @with_setup(setup_func_SMB2, teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, time, random from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_rename_english_file_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_english_file_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_unicode_file_SMB1(): global conn old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_unicode_file_SMB2(): global conn old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_english_directory_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_english_directory_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_unicode_directory_SMB1(): global conn old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_unicode_directory_SMB2(): global conn old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() ================================================ FILE: python2/tests/DirectSMBConnectionTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile, random, time from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2, teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1, teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2, teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) ================================================ FILE: python2/tests/DirectSMBConnectionTests/util.py ================================================ import os from ConfigParser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'direct_port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), 'is_direct_tcp': True, } return info ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_auth.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class AuthFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): self.d.callback(True) def onAuthFailed(self): self.d.callback(False) @deferred(timeout=5.0) def test_NTLMv1_auth_SMB1(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv2_auth_SMB1(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv1_auth_SMB2(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv2_auth_SMB2(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, random, time from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class DirectoryFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = '' self.path = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def createDone(self, result): d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): names = map(lambda e: e.filename, entries) assert os.path.basename(self.path.replace('/', os.sep)) in names d = self.deleteDirectory(self.service_name, self.path) d.addCallback(self.deleteDone) d.addErrback(self.d.errback) def deleteDone(self, result): d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): names = map(lambda e: e.filename, entries) assert os.path.basename(self.path.replace('/', os.sep)) not in names self.d.callback(True) def onAuthOK(self): d = self.createDirectory(self.service_name, self.path) d.addCallback(self.createDone) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_english_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_english_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_unicode_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_unicode_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_echo.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from util import getConnectionInfo class EchoFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.echo_data = 'This is an echo test' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(data): assert data == self.echo_data self.d.callback(True) d = self.echo(self.echo_data) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_echo(): info = getConnectionInfo() factory = EchoFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_listpath.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListPathFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names self.d.callback(True) d = self.listPath('smbtest', '/', timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listPath_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listPath_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_listshares.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListSharesFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): assert 'smbtest' in map(lambda r: r.name.lower(), results) self.d.callback(True) self.instance.transport.loseConnection() d = self.listShares(timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listshares_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listshares_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_listsnapshots.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListSnapshotsFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = None self.path = None def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): assert len(results) > 0 self.d.callback(True) self.instance.transport.loseConnection() d = self.listSnapshots(self.service_name, self.path, timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listshares_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listshares_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, random, time from StringIO import StringIO from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class RenameFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service = '' self.new_path = '' self.old_path = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def pathCreated(self, result): d = self.listPath(self.service, os.path.dirname(self.old_path.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.old_path.replace('/', os.sep)) in filenames assert os.path.basename(self.new_path.replace('/', os.sep)) not in filenames d = self.rename(self.service, self.old_path, self.new_path) d.addCallback(self.renameComplete) d.addErrback(self.d.errback) def renameComplete(self, result): d = self.listPath(self.service, os.path.dirname(self.new_path.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.new_path.replace('/', os.sep)) in filenames assert os.path.basename(self.old_path.replace('/', os.sep)) not in filenames self.cleanup() def onAuthFailed(self): self.d.errback('Auth failed') class RenameFileFactory(RenameFactory): def onAuthOK(self): d = self.storeFile(self.service, self.old_path, StringIO('Rename file test')) d.addCallback(self.pathCreated) d.addErrback(self.d.errback) def cleanup(self): d = self.deleteFiles(self.service, self.new_path) d.chainDeferred(self.d) class RenameDirectoryFactory(RenameFactory): def onAuthOK(self): d = self.createDirectory(self.service, self.old_path) d.addCallback(self.pathCreated) d.addErrback(self.d.errback) def cleanup(self): d = self.deleteDirectory(self.service, self.new_path) d.chainDeferred(self.d) @deferred(timeout=30.0) def test_rename_english_file_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_file_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_file_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_file_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() class RetrieveFileFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.temp_fh = tempfile.NamedTemporaryFile(prefix = 'pysmbtest-') self.service = '' self.path = '' self.digest = '' self.offset = 0 self.max_length = -1 self.filesize = 0 def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def fileRetrieved(self, write_result): file_obj, file_attributes, file_size = write_result assert file_obj == self.temp_fh md = MD5() filesize = 0 self.temp_fh.seek(0) while True: s = self.temp_fh.read(8192) if not s: break md.update(s) filesize += len(s) assert self.filesize == filesize assert md.hexdigest() == self.digest self.temp_fh.close() self.d.callback(True) self.instance.transport.loseConnection() def onAuthOK(self): assert self.service assert self.path d = self.retrieveFileFromOffset(self.service, self.path, self.temp_fh, self.offset, self.max_length, timeout = 15) d.addCallback(self.fileRetrieved) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=30.0) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' factory.digest = '5367c2bbf97f521059c78eab65309ad3' factory.filesize = 158437 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' factory.digest = '5367c2bbf97f521059c78eab65309ad3' factory.filesize = 158437 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/Implementing CIFS - SMB.html' factory.digest = '671c5700d279fcbbf958c1bba3c2639e' factory.filesize = 421269 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/Implementing CIFS - SMB.html' factory.digest = '671c5700d279fcbbf958c1bba3c2639e' factory.filesize = 421269 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '8a44c1e80d55e91c92350955cdf83442' factory.filesize = 256000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '8a44c1e80d55e91c92350955cdf83442' factory.filesize = 256000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' factory.filesize = 156000 factory.offset = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' factory.filesize = 156000 factory.offset = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' factory.filesize = 100000 factory.offset = 100000 factory.max_length = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' factory.filesize = 100000 factory.offset = 100000 factory.max_length = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '746f60a96b39b712a7b6e17ddde19986' factory.filesize = 10 factory.offset = 100000 factory.max_length = 10 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '746f60a96b39b712a7b6e17ddde19986' factory.filesize = 10 factory.offset = 100000 factory.max_length = 10 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' factory.filesize = 0 factory.offset = 100000 factory.max_length = 0 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' factory.filesize = 0 factory.offset = 100000 factory.max_length = 0 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, time, random from StringIO import StringIO from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() class StoreFilesFactory(SMBProtocolFactory): """ A super test factory that tests store file, list files, retrieve file and delete file functionlities in sequence. """ TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = '' self.filename = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def storeComplete(self, result): file_obj, filesize = result file_obj.close() assert filesize == self.TEST_FILESIZE d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.filename.replace('/', os.sep)) in filenames for entry in entries: if os.path.basename(self.filename.replace('/', os.sep)) == entry.filename: # The following asserts will fail if the remote machine's time is not in sync with the test machine's time assert abs(entry.create_time - time.time()) < 3 assert abs(entry.last_access_time - time.time()) < 3 assert abs(entry.last_write_time - time.time()) < 3 assert abs(entry.last_attr_change_time - time.time()) < 3 break d = self.retrieveFile(self.service_name, self.filename, StringIO()) d.addCallback(self.retrieveComplete) d.addErrback(self.d.errback) def retrieveComplete(self, result): file_obj, file_attributes, file_size = result md = MD5() md.update(file_obj.getvalue()) file_obj.close() assert file_size == self.TEST_FILESIZE assert md.hexdigest() == self.TEST_DIGEST d = self.deleteFiles(self.service_name, self.filename) d.addCallback(self.deleteComplete) d.addErrback(self.d.errback) def deleteComplete(self, result): d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.filename.replace('/', os.sep)) not in filenames self.d.callback(True) self.instance.transport.loseConnection() def onAuthOK(self): d = self.storeFile(self.service_name, self.filename, open(self.TEST_FILENAME, 'rb')) d.addCallback(self.storeComplete) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=30.0) def test_store_long_filename_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_long_filename_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_unicode_filename_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_unicode_filename_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/DirectSMBTwistedTests/util.py ================================================ import os from ConfigParser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'direct_port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), 'is_direct_tcp': True, } return info ================================================ FILE: python2/tests/NetBIOSTests/__init__.py ================================================ ================================================ FILE: python2/tests/NetBIOSTests/test_queryname.py ================================================ from nmb.NetBIOS import NetBIOS from nose.tools import with_setup conn = None def teardown_func(): global conn conn.close() @with_setup(teardown = teardown_func) def test_broadcast(): global conn conn = NetBIOS() assert conn.queryName('MICHAEL-I5PC', timeout = 10) ================================================ FILE: python2/tests/NetBIOSTwistedTests/__init__.py ================================================ ================================================ FILE: python2/tests/NetBIOSTwistedTests/test_queryname.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from nmb.NetBIOSProtocol import NBNSProtocol from nose.tools import with_setup @deferred(timeout=15.0) def test_broadcast(): def cb(results): assert results def cleanup(r): p.transport.stopListening() p = NBNSProtocol() d = p.queryName('MICHAEL-I5PC', timeout = 10) d.addCallback(cb) d.addBoth(cleanup) return d ================================================ FILE: python2/tests/README.md ================================================ Steps to Follow to Run the Unit Tests ===================================== ## Step 1: Install system dependencies ## If you are using Ubuntu 20.04 LTS, you can install the system dependencies with the following command ``` $> apt-get install virtualenv python-dev gcc g++ make automake autoconf ``` For other distributions, you can use their package managers and install the system dependencies (although the package names might differ slightly). ## Step 2: Setup python virtualenv ## We will create a python2 virtualenv and install the python dependencies for testing in the "venv2" folder. ``` $> cd /python2 $> virtualenv -p /usr/bin/python2 venv2 $> source venv2/bin/activate $venv2> pip install nose pyasn1 twisted ``` ## Step 3: Setup shared folder on your remote SMB server ## Prepare a shared folder called "smbtest" on your remote SMB server (Windows or Samba). Then, download [smbtest.zip](https://miketeo.net/files/Projects/pysmb/smbtest.zip) and unzip the contents of this zip file in the shared folder. You should also configure a user on the SMB server with read-write access to the "smbtest" folder. ## Step 4: Update connection details in connection.ini ## In the same folder where you are viewing this readme file, there should be an ini file called "connection.ini". Edit this file's connection details to match the shared folder's access information. ## Step 5: Run the unit tests in the python2 folder ## Before running the tests, the venv2 virtualenv must be activated. ``` $> cd /python2 $> source venv2/bin/activate ``` To run all the tests: ``` $venv2> nosetests -v tests ``` To selectively run some tests: ``` $venv2> nosetests -v tests/SMBConnectionTests $venv2> nosetests -v tests/SMBConnectionTests/test_rename.py $venv2> nosetests -v tests/SMBConnectionTests/test_rename.py:test_rename_english_file_SMB1 ``` For more information, please consult the [documentation for nose](https://nose.readthedocs.io/). ================================================ FILE: python2/tests/SMBConnectionTests/__init__.py ================================================ ================================================ FILE: python2/tests/SMBConnectionTests/test_SMBHandler.py ================================================ # -*- coding: utf-8 -*- import os, urllib, urllib2, time, random from StringIO import StringIO from smb.SMBHandler import SMBHandler import util try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() def test_basic(): # Basic test for smb URLs director = urllib2.build_opener(SMBHandler) fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/rfc1001.txt' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert len(s) == 158437 fh.close() def test_unicode(): # Test smb URLs with unicode paths director = urllib2.build_opener(SMBHandler) fh = director.open(u'smb://%(user)s:%(password)s@%(server_ip)s/smbtest/测试文件夹/垃圾文件.dat' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert len(s) == 256000 fh.close() TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def test_upload(): info = util.getConnectionInfo() info['filename'] = os.sep + 'StoreTest-%d-%d.dat' % ( time.time(), random.randint(0, 10000) ) director = urllib2.build_opener(SMBHandler) upload_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info, data = open(TEST_FILENAME, 'rb')) retr_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info) s = retr_fh.read() md = MD5() md.update(s) assert md.hexdigest() == TEST_DIGEST assert len(s) == TEST_FILESIZE ================================================ FILE: python2/tests/SMBConnectionTests/test_auth.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn, conn2, conn3 = None, None, None def teardown_func(): global conn, conn2, conn3 if conn: conn.close() if conn2: conn2.close() if conn3: conn3.close(); @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) assert not conn3.connect(info['server_ip'], info['server_port']) ================================================ FILE: python2/tests/SMBConnectionTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, time, random from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_english_directory_SMB1(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2, teardown_func) def test_english_directory_SMB2(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB1, teardown_func) def test_unicode_directory_SMB1(): global conn path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2, teardown_func) def test_unicode_directory_SMB2(): global conn path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = map(lambda e: e.filename, entries) assert os.path.basename(path.replace('/', os.sep)) not in names ================================================ FILE: python2/tests/SMBConnectionTests/test_deletepattern.py ================================================ # -*- coding: utf-8 -*- import os, time, random from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_delete_without_subfolder_SMB1(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt') results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*') results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB1, teardown_func) def test_delete_with_subfolder_SMB1(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' not in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB2, teardown_func) def test_delete_without_subfolder_SMB2(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt') results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*') results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB2, teardown_func) def test_delete_with_subfolder_SMB2(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) assert 'aaTest.Folder' not in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames ================================================ FILE: python2/tests/SMBConnectionTests/test_echo.py ================================================ import random from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup conn = None def setup_func(): global conn info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func, teardown_func) def test_echo(): global conn data = '%d' % random.randint(1000, 9999) assert conn.echo(data) == data ================================================ FILE: python2/tests/SMBConnectionTests/test_getattributes.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB2, teardown_func) def test_getAttributes_SMB2(): global conn info = conn.getAttributes('smbtest', '/Test Folder with Long Name/') assert info.isDirectory info = conn.getAttributes('smbtest', '/rfc1001.txt') assert not info.isDirectory assert info.file_size == 158437 assert info.alloc_size == 159744 info = conn.getAttributes('smbtest', u'/\u6d4b\u8bd5\u6587\u4ef6\u5939') assert info.isDirectory @with_setup(setup_func_SMB1, teardown_func) def test_getAttributes_SMB1(): global conn info = conn.getAttributes('smbtest', '/Test Folder with Long Name/') assert info.isDirectory info = conn.getAttributes('smbtest', '/rfc1001.txt') assert not info.isDirectory assert info.file_size == 158437 assert info.alloc_size == 159744 info = conn.getAttributes('smbtest', u'/\u6d4b\u8bd5\u6587\u4ef6\u5939') assert info.isDirectory ================================================ FILE: python2/tests/SMBConnectionTests/test_listpath.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from smb.smb_constants import * from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB1, teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB1, teardown_func) def test_listPathWithManyFiles_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames)==999 @with_setup(setup_func_SMB2, teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB2, teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathWithManyFiles_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames)==999 @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterForDirectory_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterForDirectory_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterForFiles_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterForFiles_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterPattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterPattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterUnicodePattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterUnicodePattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB1, teardown_func) def test_listPathFilterEmptyList_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) @with_setup(setup_func_SMB2, teardown_func) def test_listPathFilterEmptyList_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) ================================================ FILE: python2/tests/SMBConnectionTests/test_listshares.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in map(lambda r: r.name.lower(), results) @with_setup(setup_func_SMB2, teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() assert 'smbtest' in map(lambda r: r.name.lower(), results) ================================================ FILE: python2/tests/SMBConnectionTests/test_listsnapshots.py ================================================ from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 @with_setup(setup_func_SMB2, teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 ================================================ FILE: python2/tests/SMBConnectionTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, time, random from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_rename_english_file_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_english_file_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_unicode_file_SMB1(): global conn old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_unicode_file_SMB2(): global conn old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, StringIO('Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_english_directory_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_english_directory_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB1, teardown_func) def test_rename_unicode_directory_SMB1(): global conn old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2, teardown_func) def test_rename_unicode_directory_SMB2(): global conn old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) ================================================ FILE: python2/tests/SMBConnectionTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFile('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB1, teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() @with_setup(setup_func_SMB2, teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = StringIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', u'/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() ================================================ FILE: python2/tests/SMBConnectionTests/test_security.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB2, teardown_func) def test_security_SMB2(): global conn # TODO: Need a way to setup the environment on the remote server and perform some verification on the returned results. attributes = conn.getSecurity('smbtest', '/rfc1001.txt') ================================================ FILE: python2/tests/SMBConnectionTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile, random, time from StringIO import StringIO from smb.SMBConnection import SMBConnection from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1, teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1, teardown_func) def test_store_from_offset_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) buf = StringIO('0123456789') filesize = conn.storeFile('smbtest', filename, buf) assert filesize == 10 buf = StringIO('aa') pos = conn.storeFileFromOffset('smbtest', filename, buf, 5) assert pos == 7 buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == 10 assert buf.getvalue() == '01234aa789' buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2, teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1, teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2, teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = map(lambda e: e.filename, entries) assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2, teardown_func) def test_store_from_offset_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) buf = StringIO('0123456789') filesize = conn.storeFile('smbtest', filename, buf) assert filesize == 10 buf = StringIO('aa') pos = conn.storeFileFromOffset('smbtest', filename, buf, 5) assert pos == 7 buf = StringIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == 10 assert buf.getvalue() == '01234aa789' buf.close() conn.deleteFiles('smbtest', filename) ================================================ FILE: python2/tests/SMBConnectionTests/test_with_context.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from .util import getConnectionInfo def test_context(): info = getConnectionInfo() with SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) as conn: assert conn.connect(info['server_ip'], info['server_port']) assert conn.sock is None ================================================ FILE: python2/tests/SMBConnectionTests/util.py ================================================ import os from ConfigParser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), 'domain': cp.get('user', 'domain') } return info ================================================ FILE: python2/tests/SMBTwistedTests/__init__.py ================================================ ================================================ FILE: python2/tests/SMBTwistedTests/test_auth.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class AuthFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): self.d.callback(True) def onAuthFailed(self): self.d.callback(False) @deferred(timeout=5.0) def test_NTLMv1_auth_SMB1(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv2_auth_SMB1(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv1_auth_SMB2(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=5.0) def test_NTLMv2_auth_SMB2(): def result(auth_passed): assert auth_passed smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.d.addCallback(result) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, random, time from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class DirectoryFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = '' self.path = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def createDone(self, result): d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): names = map(lambda e: e.filename, entries) assert os.path.basename(self.path.replace('/', os.sep)) in names d = self.deleteDirectory(self.service_name, self.path) d.addCallback(self.deleteDone) d.addErrback(self.d.errback) def deleteDone(self, result): d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): names = map(lambda e: e.filename, entries) assert os.path.basename(self.path.replace('/', os.sep)) not in names self.d.callback(True) def onAuthOK(self): d = self.createDirectory(self.service_name, self.path) d.addCallback(self.createDone) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_english_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_english_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_unicode_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_unicode_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = os.sep + u'文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_echo.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from util import getConnectionInfo class EchoFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.echo_data = 'This is an echo test' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(data): assert data == self.echo_data self.d.callback(True) d = self.echo(self.echo_data) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_echo(): info = getConnectionInfo() factory = EchoFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_getattributes.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class GetAttributesFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.path = '' self.is_directory = False def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(info): assert info.isDirectory == self.is_directory self.d.callback(True) d = self.getAttributes('smbtest', self.path, timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_getAttributes_SMB1_test1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = '/Test Folder with Long Name/' factory.is_directory = True reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_getAttributes_SMB1_test2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = '/rfc1001.txt' factory.is_directory = False reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_getAttributes_SMB1_test3(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = u'/\u6d4b\u8bd5\u6587\u4ef6\u5939' factory.is_directory = True reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_getAttributes_SMB2_test1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = '/Test Folder with Long Name/' factory.is_directory = True reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_getAttributes_SMB2_test2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = '/rfc1001.txt' factory.is_directory = False reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_getAttributes_SMB2_test3(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.path = u'/\u6d4b\u8bd5\u6587\u4ef6\u5939' factory.is_directory = True reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_listpath.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListPathFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert ( u'\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( u'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( u'TestDir1', True ) in filenames # Test short English folder names assert ( u'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( u'rfc1001.txt', False ) in filenames # Test short English file names self.d.callback(True) d = self.listPath('smbtest', '/', timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listPath_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listPath_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_listshares.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListSharesFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): assert 'smbtest' in map(lambda r: r.name.lower(), results) self.d.callback(True) self.instance.transport.loseConnection() d = self.listShares(timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listshares_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listshares_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_listsnapshots.py ================================================ from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class ListSnapshotsFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = None self.path = None def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def onAuthOK(self): def cb(results): assert len(results) > 0 self.d.callback(True) self.instance.transport.loseConnection() d = self.listSnapshots(self.service_name, self.path, timeout = 15) d.addCallback(cb) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=15.0) def test_listshares_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=15.0) def test_listshares_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, random, time from StringIO import StringIO from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo class RenameFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service = '' self.new_path = '' self.old_path = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def pathCreated(self, result): d = self.listPath(self.service, os.path.dirname(self.old_path.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.old_path.replace('/', os.sep)) in filenames assert os.path.basename(self.new_path.replace('/', os.sep)) not in filenames d = self.rename(self.service, self.old_path, self.new_path) d.addCallback(self.renameComplete) d.addErrback(self.d.errback) def renameComplete(self, result): d = self.listPath(self.service, os.path.dirname(self.new_path.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.new_path.replace('/', os.sep)) in filenames assert os.path.basename(self.old_path.replace('/', os.sep)) not in filenames self.cleanup() def onAuthFailed(self): self.d.errback('Auth failed') class RenameFileFactory(RenameFactory): def onAuthOK(self): d = self.storeFile(self.service, self.old_path, StringIO('Rename file test')) d.addCallback(self.pathCreated) d.addErrback(self.d.errback) def cleanup(self): d = self.deleteFiles(self.service, self.new_path) d.chainDeferred(self.d) class RenameDirectoryFactory(RenameFactory): def onAuthOK(self): d = self.createDirectory(self.service, self.old_path) d.addCallback(self.pathCreated) d.addErrback(self.d.errback) def cleanup(self): d = self.deleteDirectory(self.service, self.new_path) d.chainDeferred(self.d) @deferred(timeout=30.0) def test_rename_english_file_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_file_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_file_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_file_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_english_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_directory_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_rename_unicode_directory_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.old_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) factory.new_path = u'/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() class RetrieveFileFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.temp_fh = tempfile.NamedTemporaryFile(prefix = 'pysmbtest-') self.service = '' self.path = '' self.digest = '' self.offset = 0 self.max_length = -1 self.filesize = 0 def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def fileRetrieved(self, write_result): file_obj, file_attributes, file_size = write_result assert file_obj == self.temp_fh md = MD5() filesize = 0 self.temp_fh.seek(0) while True: s = self.temp_fh.read(8192) if not s: break md.update(s) filesize += len(s) assert self.filesize == filesize assert md.hexdigest() == self.digest self.temp_fh.close() self.d.callback(True) self.instance.transport.loseConnection() def onAuthOK(self): assert self.service assert self.path d = self.retrieveFileFromOffset(self.service, self.path, self.temp_fh, self.offset, self.max_length, timeout = 15) d.addCallback(self.fileRetrieved) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=30.0) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' factory.digest = '5367c2bbf97f521059c78eab65309ad3' factory.filesize = 158437 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' factory.digest = '5367c2bbf97f521059c78eab65309ad3' factory.filesize = 158437 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/Implementing CIFS - SMB.html' factory.digest = '671c5700d279fcbbf958c1bba3c2639e' factory.filesize = 421269 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/Implementing CIFS - SMB.html' factory.digest = '671c5700d279fcbbf958c1bba3c2639e' factory.filesize = 421269 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '8a44c1e80d55e91c92350955cdf83442' factory.filesize = 256000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '8a44c1e80d55e91c92350955cdf83442' factory.filesize = 256000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' factory.filesize = 156000 factory.offset = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' factory.filesize = 156000 factory.offset = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' factory.filesize = 100000 factory.offset = 100000 factory.max_length = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' factory.filesize = 100000 factory.offset = 100000 factory.max_length = 100000 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '746f60a96b39b712a7b6e17ddde19986' factory.filesize = 10 factory.offset = 100000 factory.max_length = 10 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = '746f60a96b39b712a7b6e17ddde19986' factory.filesize = 10 factory.offset = 100000 factory.max_length = 10 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' factory.filesize = 0 factory.offset = 100000 factory.max_length = 0 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = u'/测试文件夹/垃圾文件.dat' factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' factory.filesize = 0 factory.offset = 100000 factory.max_length = 0 reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, time, random from StringIO import StringIO from nose.twistedtools import reactor, deferred from twisted.internet import defer from smb.SMBProtocol import SMBProtocolFactory from smb import smb_structs from util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() class StoreFilesFactory(SMBProtocolFactory): """ A super test factory that tests store file, list files, retrieve file and delete file functionlities in sequence. """ TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) self.d = defer.Deferred() self.d.addBoth(self.testDone) self.service_name = '' self.filename = '' def testDone(self, r): if self.instance: self.instance.transport.loseConnection() return r def storeComplete(self, result): file_obj, filesize = result file_obj.close() assert filesize == self.TEST_FILESIZE d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) d.addCallback(self.listComplete) d.addErrback(self.d.errback) def listComplete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.filename.replace('/', os.sep)) in filenames for entry in entries: if os.path.basename(self.filename.replace('/', os.sep)) == entry.filename: # The following asserts will fail if the remote machine's time is not in sync with the test machine's time assert abs(entry.create_time - time.time()) < 3 assert abs(entry.last_access_time - time.time()) < 3 assert abs(entry.last_write_time - time.time()) < 3 assert abs(entry.last_attr_change_time - time.time()) < 3 break d = self.retrieveFile(self.service_name, self.filename, StringIO()) d.addCallback(self.retrieveComplete) d.addErrback(self.d.errback) def retrieveComplete(self, result): file_obj, file_attributes, file_size = result md = MD5() md.update(file_obj.getvalue()) file_obj.close() assert file_size == self.TEST_FILESIZE assert md.hexdigest() == self.TEST_DIGEST d = self.deleteFiles(self.service_name, self.filename) d.addCallback(self.deleteComplete) d.addErrback(self.d.errback) def deleteComplete(self, result): d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) d.addCallback(self.list2Complete) d.addErrback(self.d.errback) def list2Complete(self, entries): filenames = map(lambda e: e.filename, entries) assert os.path.basename(self.filename.replace('/', os.sep)) not in filenames self.d.callback(True) self.instance.transport.loseConnection() def onAuthOK(self): d = self.storeFile(self.service_name, self.filename, open(self.TEST_FILENAME, 'rb')) d.addCallback(self.storeComplete) d.addErrback(self.d.errback) def onAuthFailed(self): self.d.errback('Auth failed') @deferred(timeout=30.0) def test_store_long_filename_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_long_filename_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_unicode_filename_SMB1(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = False factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d @deferred(timeout=30.0) def test_store_unicode_filename_SMB2(): info = getConnectionInfo() smb_structs.SUPPORT_SMB2 = True factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) factory.service_name = 'smbtest' factory.filename = os.sep + u'上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) reactor.connectTCP(info['server_ip'], info['server_port'], factory) return factory.d ================================================ FILE: python2/tests/SMBTwistedTests/util.py ================================================ import os from ConfigParser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), } return info ================================================ FILE: python2/tests/__init__.py ================================================ ================================================ FILE: python2/tests/connection.ini ================================================ [server] name = SERVER ip = 192.168.1.1 port = 139 direct_port = 445 [client] name = TESTCLIENT [user] name = myuser password = mypassword domain = ================================================ FILE: python2/tests/test_ntlm.py ================================================ import binascii from smb import ntlm def test_NTLMv1_without_extended_security(): password = 'Password' server_challenge = '\x01\x23\x45\x67\x89\xab\xcd\xef' nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(password, server_challenge, has_extended_security = False, client_challenge = '\xAA'*8) assert binascii.hexlify(nt_challenge_response).lower() == '67 c4 30 11 f3 02 98 a2 ad 35 ec e6 4f 16 33 1c 44 bd be d9 27 84 1f 94'.replace(' ', '') # [MS-NLMP]: 4.2.2.2.1 assert binascii.hexlify(lm_challenge_response).lower() == '98 de f7 b8 7f 88 aa 5d af e2 df 77 96 88 a1 72 de f1 1c 7d 5c cd ef 13'.replace(' ', '') # [MS-NLMP]: 4.2.2.2.2 def test_NTLMv1_with_extended_security(): password = 'Password' server_challenge = '\x01\x23\x45\x67\x89\xab\xcd\xef' nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(password, server_challenge, has_extended_security = True, client_challenge = '\xAA'*8) assert binascii.hexlify(nt_challenge_response).lower() == '75 37 f8 03 ae 36 71 28 ca 45 82 04 bd e7 ca f8 1e 97 ed 26 83 26 72 32'.replace(' ', '') # [MS-NLMP]: 4.2.3.2.2 assert binascii.hexlify(lm_challenge_response).lower() == 'aa aa aa aa aa aa aa aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'.replace(' ', '') # [MS-NLMP]: 4.2.3.2.1 def test_NTLMv2(): user = 'User' password = 'Password' domain = 'Domain' server_challenge = '\x01\x23\x45\x67\x89\xab\xcd\xef' server_avpair = binascii.unhexlify('01 00 0c 00 53 00 65 00 72 00 76 00 65 00 72 00'.replace(' ', '')) domain_avpair = binascii.unhexlify('02 00 0c 00 44 00 6f 00 6d 00 61 00 69 00 6e 00'.replace(' ', '')) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(password, user, server_challenge, server_avpair + domain_avpair + '\0'*4, domain, client_challenge = '\xAA'*8) assert binascii.hexlify(lm_challenge_response).lower() == '86 c3 50 97 ac 9c ec 10 25 54 76 4a 57 cc cc 19 aa aa aa aa aa aa aa aa'.replace(' ', '') # [MS-NLMP]: 4.2.4.2.1 ================================================ FILE: python2/tests/test_security_descriptors.py ================================================ import binascii from smb import security_descriptors as sd from smb import smb_constants as sc def test_sid_string_representation(): sid = sd.SID(1, 5, [2, 3, 4]) assert str(sid) == "S-1-5-2-3-4" sid = sd.SID(1, 2**32 + 3, []) assert str(sid) == "S-1-0x100000003" sid = sd.SID(1, 2**32, [3, 2, 1]) assert str(sid) == "S-1-0x100000000-3-2-1" def test_sid_binary_parsing(): raw_sid = binascii.unhexlify(""" 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, ' \n')) assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" raw_sid += "garbage" assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" sid, tail = sd.SID.from_bytes(raw_sid, return_tail=True) assert str(sid) == "S-1-5-21-717312990-3403304746-849770945-1201" assert tail == "garbage" def test_ace_binary_parsing(): raw_ace = binascii.unhexlify(""" 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 6e 04 00 00 """.translate(None, ' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1134" assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES | sc.FILE_WRITE_ATTRIBUTES) assert not ace.additional_data raw_ace = binascii.unhexlify(""" 00 13 18 00 a9 00 12 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 """.translate(None, ' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-32-545" assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert ace.flags == (sd.ACE_FLAG_INHERITED | sd.ACE_FLAG_CONTAINER_INHERIT | sd.ACE_FLAG_OBJECT_INHERIT) assert ace.mask == (sc.SYNCHRONIZE | sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) assert not ace.additional_data raw_ace = binascii.unhexlify(""" 01 03 24 00 a9 00 02 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 6c 04 00 00 """.translate(None, ' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1132" assert ace.type == sd.ACE_TYPE_ACCESS_DENIED assert ace.flags == (sd.ACE_FLAG_CONTAINER_INHERIT | sd.ACE_FLAG_OBJECT_INHERIT) assert ace.mask == (sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) assert not ace.additional_data def test_acl_binary_parsing(): raw_acl = binascii.unhexlify(""" 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, ' \n')) acl = sd.ACL.from_bytes(raw_acl) assert acl.revision == 2 assert len(acl.aces) == 4 ace = acl.aces[0] assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert str(ace.sid) == "S-1-5-32-545" assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_READ_ATTRIBUTES) ace = acl.aces[3] assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1201" assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES | sc.FILE_WRITE_ATTRIBUTES) def test_descriptor_binary_parsing(): raw_descriptor = binascii.unhexlify(""" 01 00 04 84 14 00 00 00 30 00 00 00 00 00 00 00 4c 00 00 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 01 02 00 00 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, ' \n')) descriptor = sd.SecurityDescriptor.from_bytes(raw_descriptor) assert descriptor.flags == (sd.SECURITY_DESCRIPTOR_SELF_RELATIVE | sd.SECURITY_DESCRIPTOR_DACL_PRESENT | sd.SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED) assert descriptor.dacl is not None assert descriptor.sacl is None assert str(descriptor.owner) == "S-1-5-21-717312990-3403304746-849770945-1201" assert str(descriptor.group) == "S-1-5-21-717312990-3403304746-849770945-513" acl = descriptor.dacl assert acl.revision == 2 assert len(acl.aces) == 4 assert str(acl.aces[0].sid) == sd.SID_BUILTIN_USERS assert str(acl.aces[1].sid) == sd.SID_LOCAL_SYSTEM assert str(acl.aces[2].sid) == sd.SID_BUILTIN_ADMINISTRATORS assert str(acl.aces[3].sid) == "S-1-5-21-717312990-3403304746-849770945-1201" ================================================ FILE: python2/tests/test_securityblob.py ================================================ import binascii from smb import securityblob def test_NTLMSSP_NEGOTIATE_encoding(): ntlm_data = binascii.unhexlify('4e544c4d5353500001000000978208e200000000000000000000000000000000060072170000000f') # The NTLM negotiate message blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) TARGET = binascii.unhexlify(""" 60 48 06 06 2b 06 01 05 05 02 a0 3e 30 3c a0 0e 30 0c 06 0a 2b 06 01 04 01 82 37 02 02 0a a2 2a 04 28 4e 54 4c 4d 53 53 50 00 01 00 00 00 97 82 08 e2 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 72 17 00 00 00 0f """.replace(' ', '').replace('\n', '')) assert blob == TARGET def test_NTLMSSP_CHALLENGE_decoding(): blob = binascii.unhexlify(""" a1 81 be 30 81 bb a0 03 0a 01 01 a1 0c 06 0a 2b 06 01 04 01 82 37 02 02 0a a2 81 a5 04 81 a2 4e 54 4c 4d 53 53 50 00 02 00 00 00 0a 00 0a 00 38 00 00 00 15 82 8a e2 32 81 ce 29 7f de 3f 80 00 00 00 00 00 00 00 00 60 00 60 00 42 00 00 00 06 01 00 00 00 00 00 0f 43 00 45 00 54 00 55 00 53 00 02 00 0a 00 43 00 45 00 54 00 55 00 53 00 01 00 0a 00 43 00 45 00 54 00 55 00 53 00 04 00 16 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 03 00 22 00 63 00 65 00 74 00 75 00 73 00 2e 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 00 00 00 00""".replace(' ', '').replace('\n', '')) RESPONSE_TOKENS = binascii.unhexlify(""" 4e 54 4c 4d 53 53 50 00 02 00 00 00 0a 00 0a 00 38 00 00 00 15 82 8a e2 32 81 ce 29 7f de 3f 80 00 00 00 00 00 00 00 00 60 00 60 00 42 00 00 00 06 01 00 00 00 00 00 0f 43 00 45 00 54 00 55 00 53 00 02 00 0a 00 43 00 45 00 54 00 55 00 53 00 01 00 0a 00 43 00 45 00 54 00 55 00 53 00 04 00 16 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 03 00 22 00 63 00 65 00 74 00 75 00 73 00 2e 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 00 00 00 00 """.replace(' ', '').replace('\n', '')) result, response_tokens = securityblob.decodeChallengeSecurityBlob(blob) assert result == securityblob.RESULT_ACCEPT_INCOMPLETE assert response_tokens == RESPONSE_TOKENS def test_NTLMSSP_AUTH_encoding(): ntlm_data = binascii.unhexlify(""" 4e 54 4c 4d 53 53 50 00 03 00 00 00 01 00 01 00 70 00 00 00 00 00 00 00 71 00 00 00 00 00 00 00 58 00 00 00 00 00 00 00 58 00 00 00 18 00 18 00 58 00 00 00 10 00 10 00 71 00 00 00 15 8a 88 e2 06 00 72 17 00 00 00 0f 06 49 3b c4 f6 2a 2b be 61 a6 81 e7 cc 58 37 b4 4d 00 49 00 43 00 48 00 41 00 45 00 4c 00 2d 00 49 00 35 00 50 00 43 00 00 a7 0d b4 74 c3 d8 14 c9 df 3d 80 6d 87 94 42 bc """.replace(' ', '').replace('\n', '')) TARGET = binascii.unhexlify(""" a1 81 8a 30 81 87 a2 81 84 04 81 81 4e 54 4c 4d 53 53 50 00 03 00 00 00 01 00 01 00 70 00 00 00 00 00 00 00 71 00 00 00 00 00 00 00 58 00 00 00 00 00 00 00 58 00 00 00 18 00 18 00 58 00 00 00 10 00 10 00 71 00 00 00 15 8a 88 e2 06 00 72 17 00 00 00 0f 06 49 3b c4 f6 2a 2b be 61 a6 81 e7 cc 58 37 b4 4d 00 49 00 43 00 48 00 41 00 45 00 4c 00 2d 00 49 00 35 00 50 00 43 00 00 a7 0d b4 74 c3 d8 14 c9 df 3d 80 6d 87 94 42 bc """.replace(' ', '').replace('\n', '')) blob = securityblob.generateAuthSecurityBlob(ntlm_data) assert blob == TARGET def test_auth_response_decoding(): blob = binascii.unhexlify("a1 07 30 05 a0 03 0a 01 00".replace(' ', '')) result = securityblob.decodeAuthResponseSecurityBlob(blob) assert result == securityblob.RESULT_ACCEPT_COMPLETED ================================================ FILE: python3/nmb/NetBIOS.py ================================================ import os, logging, random, socket, time, select from .base import NBNS, NotConnectedError from .nmb_constants import TYPE_CLIENT, TYPE_SERVER, TYPE_WORKSTATION class NetBIOS(NBNS): log = logging.getLogger('NMB.NetBIOS') def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.broadcast: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) if listen_port: self.sock.bind(( '', listen_port )) def close(self): """ Close the underlying and free resources. The NetBIOS instance should not be used to perform any operations after this method returns. :return: None """ self.sock.close() self.sock = None def write(self, data, ip, port): assert self.sock, 'Socket is already closed' self.sock.sendto(data, ( ip, port )) def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) return self._pollForNetBIOSPacket(trn_id, timeout) def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A list of string containing the names of the machine at *ip*. On timeout, returns None. """ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNetNameQuery(trn_id, False) self.write(data, ip, port) ret = self._pollForQueryPacket(trn_id, timeout) if ret: return list(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) else: return None # # Protected Methods # def _pollForNetBIOSPacket(self, wait_trn_id, timeout): end_time = time.time() - timeout while True: try: _timeout = time.time()-end_time if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodePacket(data) if trn_id == wait_trn_id: return ret except select.error as ex: if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex # # Contributed by Jason Anderson # def _pollForQueryPacket(self, wait_trn_id, timeout): end_time = time.time() - timeout while True: try: _timeout = time.time()-end_time if _timeout <= 0: return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: raise NotConnectedError trn_id, ret = self.decodeIPQueryPacket(data) if trn_id == wait_trn_id: return ret except select.error as ex: if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex ================================================ FILE: python3/nmb/NetBIOSProtocol.py ================================================ import os, logging, random, socket, time from twisted.internet import reactor, defer from twisted.internet.protocol import DatagramProtocol from .base import NBNS class NetBIOSTimeout(Exception): """Raised in NBNSProtocol via Deferred.errback method when queryName method has timeout waiting for reply""" pass class NBNSProtocol(DatagramProtocol, NBNS): log = logging.getLogger('NMB.NBNSProtocol') def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NBNSProtocol instance. This automatically calls reactor.listenUDP method to start listening for incoming packets, so you **must not** call the listenUDP method again. :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number. """ self.broadcast = broadcast self.pending_trns = { } # TRN ID -> ( expiry_time, name, Deferred instance ) self.transport = reactor.listenUDP(listen_port, self) if self.broadcast: self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) reactor.callLater(1, self.cleanupPendingTrns) def datagramReceived(self, data, from_info): host, port = from_info trn_id, ret = self.decodePacket(data) # pending transaction exists for trn_id - handle it and remove from queue if trn_id in self.pending_trns: _, ip, d = self.pending_trns.pop(trn_id) if ip is NAME_QUERY: # decode as query packet trn_id, ret = self.decodeIPQueryPacket(data) d.callback(ret) def write(self, data, ip, port): # We don't use the transport.write method directly as it keeps raising DeprecationWarning for ip='' self.transport.getHandle().sendto(data, ( ip, port )) def queryName(self, name, ip = '', port = 137, timeout = 30): """ Send a query on the network and hopes that if machine matching the *name* will reply with its IP address. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the returned Deferred instance will be called with a NetBIOSTimeout exception. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNameQuery(trn_id, name) if self.broadcast and not ip: ip = '' elif not ip: self.log.warning('queryName: ip parameter is empty. OS might not transmit this query to the network') self.write(data, ip, port) d = defer.Deferred() self.pending_trns[trn_id] = ( time.time()+timeout, name, d ) return d def queryIPForName(self, ip, port = 137, timeout = 30): """ Send a query to the machine with *ip* and hopes that the machine will reply back with its name. The implementation of this function is contributed by Jason Anderson. :param string ip: If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query. :param integer port: The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing. :param integer/float timeout: Number of seconds to wait for a reply, after which the method will return None :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of names of the machine at *ip*. On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) while True: if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF data = self.prepareNetNameQuery(trn_id) self.write(data, ip, port) d = defer.Deferred() d2 = defer.Deferred() d2.addErrback(d.errback) def stripCode(ret): if ret is not None: # got valid response. Somehow the callback is also called when there is an error. d.callback(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) d2.addCallback(stripCode) self.pending_trns[trn_id] = ( time.time()+timeout, NAME_QUERY, d2 ) return d def stopProtocol(self): DatagramProtocol.stopProtocol(self) def cleanupPendingTrns(self): now = time.time() # reply should have been received in the past # info is tuple of ( expiry_time, name, d ) expired = filter(lambda trn_id, info: info[0] < now, self.pending_trns.iteritems()) # remove expired items from dict + call errback def expire_item(item): trn_id, (expiry_time, name, d) = item del self.pending_trns[trn_id] try: d.errback(NetBIOSTimeout(name)) except: pass map(expire_item, expired) if self.transport: reactor.callLater(1, self.cleanupPendingTrns) ================================================ FILE: python3/nmb/__init__.py ================================================ ================================================ FILE: python3/nmb/base.py ================================================ import struct, logging, random from .nmb_constants import * from .nmb_structs import * from .utils import encode_name class NMBSession: log = logging.getLogger('NMB.NMBSession') def __init__(self, my_name, remote_name, host_type = TYPE_SERVER, is_direct_tcp = False): self.my_name = my_name.upper() self.remote_name = remote_name.upper() self.host_type = host_type self.data_buf = b'' if is_direct_tcp: self.data_nmb = DirectTCPSessionMessage() self.sendNMBPacket = self._sendNMBPacket_DirectTCP else: self.data_nmb = NMBSessionMessage() self.sendNMBPacket = self._sendNMBPacket_NetBIOS # # Overridden Methods # def write(self, data): raise NotImplementedError def onNMBSessionMessage(self, flags, data): pass def onNMBSessionOK(self): pass def onNMBSessionFailed(self): pass # # Public Methods # def feedData(self, data): self.data_buf = self.data_buf + data offset = 0 while True: length = self.data_nmb.decode(self.data_buf, offset) if length == 0: break elif length > 0: offset += length self._processNMBSessionPacket(self.data_nmb) else: raise NMBError if offset > 0: self.data_buf = self.data_buf[offset:] def sendNMBMessage(self, data): self.sendNMBPacket(SESSION_MESSAGE, data) def requestNMBSession(self): my_name_encoded = encode_name(self.my_name, TYPE_WORKSTATION) remote_name_encoded = encode_name(self.remote_name, self.host_type) self.sendNMBPacket(SESSION_REQUEST, remote_name_encoded + my_name_encoded) # # Protected Methods # def _processNMBSessionPacket(self, packet): if packet.type == SESSION_MESSAGE: self.onNMBSessionMessage(packet.flags, packet.data) elif packet.type == POSITIVE_SESSION_RESPONSE: self.onNMBSessionOK() elif packet.type == NEGATIVE_SESSION_RESPONSE: self.onNMBSessionFailed() elif packet.type == SESSION_KEEPALIVE: # Discard keepalive packets - [RFC1002]: 5.2.2.1 pass else: self.log.warning('Unrecognized NMB session type: 0x%02x', packet.type) def _sendNMBPacket_NetBIOS(self, packet_type, data): length = len(data) assert length <= 0x01FFFF flags = 0 if length > 0xFFFF: flags |= 0x01 length &= 0xFFFF self.write(struct.pack('>BBH', packet_type, flags, length) + data) def _sendNMBPacket_DirectTCP(self, packet_type, data): length = len(data) assert length <= 0x00FFFFFF self.write(struct.pack('>I', length) + data) class NBNS: log = logging.getLogger('NMB.NBNS') HEADER_STRUCT_FORMAT = '>HHHHHH' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def write(self, data, ip, port): raise NotImplementedError def decodePacket(self, data): if len(data) < self.HEADER_STRUCT_SIZE: raise Exception trn_id, code, question_count, answer_count, authority_count, additional_count = \ struct.unpack(self.HEADER_STRUCT_FORMAT, data[:self.HEADER_STRUCT_SIZE]) is_response = bool((code >> 15) & 0x01) opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F if opcode == 0x0000 and is_response: name_len = data[self.HEADER_STRUCT_SIZE] # Constant 2 for the padding bytes before/after the Name and constant 8 for the Type, # Class and TTL fields in the Answer section after the Name: offset = self.HEADER_STRUCT_SIZE + 2 + name_len + 8 record_count = (struct.unpack('>H', data[offset:offset+2])[0]) // 6 offset += 4 # Constant 4 for the Data Length and Flags field ret = [] for i in range(0, record_count): ret.append('%d.%d.%d.%d' % struct.unpack('4B', (data[offset:offset + 4]))) offset += 6 return trn_id, ret else: return trn_id, None def prepareNameQuery(self, trn_id, name, is_broadcast = True): header = struct.pack(self.HEADER_STRUCT_FORMAT, trn_id, (is_broadcast and 0x0110) or 0x0100, 1, 0, 0, 0) payload = encode_name(name, 0x20) + b'\x00\x20\x00\x01' return header + payload # # Contributed by Jason Anderson # def decodeIPQueryPacket(self, data): if len(data) < self.HEADER_STRUCT_SIZE: raise Exception trn_id, code, question_count, answer_count, authority_count, additional_count = struct.unpack(self.HEADER_STRUCT_FORMAT, data[:self.HEADER_STRUCT_SIZE]) is_response = bool((code >> 15) & 0x01) opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F try: numnames = data[self.HEADER_STRUCT_SIZE + 44] if numnames > 0: ret = [ ] offset = self.HEADER_STRUCT_SIZE + 45 for i in range(0, numnames): mynme = data[offset:offset + 15] mynme = mynme.strip() ret.append(( str(mynme, 'ascii'), data[offset+15] )) offset += 18 return trn_id, ret except IndexError: pass return trn_id, None # # Contributed by Jason Anderson # def prepareNetNameQuery(self, trn_id, is_broadcast = True): header = struct.pack(self.HEADER_STRUCT_FORMAT, trn_id, (is_broadcast and 0x0010) or 0x0000, 1, 0, 0, 0) payload = encode_name('*', 0) + b'\x00\x21\x00\x01' return header + payload ================================================ FILE: python3/nmb/nmb_constants.py ================================================ # Default port for NetBIOS name service NETBIOS_NS_PORT = 137 # Default port for NetBIOS session service NETBIOS_SESSION_PORT = 139 # Owner Node Type Constants NODE_B = 0x00 NODE_P = 0x01 NODE_M = 0x10 NODE_RESERVED = 0x11 # Name Type Constants TYPE_UNKNOWN = 0x01 TYPE_WORKSTATION = 0x00 TYPE_CLIENT = 0x03 TYPE_SERVER = 0x20 TYPE_DOMAIN_MASTER = 0x1B TYPE_MASTER_BROWSER = 0x1D TYPE_BROWSER = 0x1E TYPE_NAMES = { TYPE_UNKNOWN: 'Unknown', TYPE_WORKSTATION: 'Workstation', TYPE_CLIENT: 'Client', TYPE_SERVER: 'Server', TYPE_MASTER_BROWSER: 'Master Browser', TYPE_BROWSER: 'Browser Server', TYPE_DOMAIN_MASTER: 'Domain Master' } # Values for Session Packet Type field in Session Packets SESSION_MESSAGE = 0x00 SESSION_REQUEST = 0x81 POSITIVE_SESSION_RESPONSE = 0x82 NEGATIVE_SESSION_RESPONSE = 0x83 REGTARGET_SESSION_RESPONSE = 0x84 SESSION_KEEPALIVE = 0x85 ================================================ FILE: python3/nmb/nmb_structs.py ================================================ import struct class NMBError(Exception): pass class NotConnectedError(NMBError): """ Raisd when the underlying NMB connection has been disconnected or not connected yet """ pass class NMBSessionMessage: HEADER_STRUCT_FORMAT = '>BBH' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def __init__(self): self.reset() def reset(self): self.type = 0 self.flags = 0 self.data = '' def decode(self, data, offset): data_len = len(data) if data_len < offset + self.HEADER_STRUCT_SIZE: # Not enough data for decoding return 0 self.reset() self.type, self.flags, length = struct.unpack(self.HEADER_STRUCT_FORMAT, data[offset:offset+self.HEADER_STRUCT_SIZE]) if self.flags & 0x01: length |= 0x010000 if data_len < offset + self.HEADER_STRUCT_SIZE + length: return 0 self.data = data[offset+self.HEADER_STRUCT_SIZE:offset+self.HEADER_STRUCT_SIZE+length] return self.HEADER_STRUCT_SIZE + length class DirectTCPSessionMessage(NMBSessionMessage): HEADER_STRUCT_FORMAT = '>I' HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) def decode(self, data, offset): data_len = len(data) if data_len < offset + self.HEADER_STRUCT_SIZE: # Not enough data for decoding return 0 self.reset() length = struct.unpack(self.HEADER_STRUCT_FORMAT, data[offset:offset+self.HEADER_STRUCT_SIZE])[0] if length >> 24 != 0: raise NMBError("Invalid protocol header for Direct TCP session message") if data_len < offset + self.HEADER_STRUCT_SIZE + length: return 0 self.data = data[offset+self.HEADER_STRUCT_SIZE:offset+self.HEADER_STRUCT_SIZE+length] return self.HEADER_STRUCT_SIZE + length ================================================ FILE: python3/nmb/utils.py ================================================ import string, re def encode_name(name, type, scope = None): """ Perform first and second level encoding of name as specified in RFC 1001 (Section 4) """ if name == '*': name = name + '\0' * 15 elif len(name) > 15: name = name[:15] + chr(type) else: name = name.ljust(15) + chr(type) def _do_first_level_encoding(m): s = ord(m.group(0)) return string.ascii_uppercase[s >> 4] + string.ascii_uppercase[s & 0x0f] encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name) if scope: encoded_scope = '' for s in string.split(scope, '.'): encoded_scope = encoded_scope + chr(len(s)) + s return bytes(encoded_name + encoded_scope + '\0', 'ascii') else: return bytes(encoded_name + '\0', 'ascii') def decode_name(name): name_length = ord(name[0]) assert name_length == 32 def _do_first_level_decoding(m): s = m.group(0) return chr(((ord(s[0]) - ord('A')) << 4) | (ord(s[1]) - ord('A'))) decoded_name = re.sub('..', _do_first_level_decoding, name[1:33]) if name[33] == '\0': return 34, decoded_name, '' else: decoded_domain = '' offset = 34 while 1: domain_length = ord(name[offset]) if domain_length == 0: break decoded_domain = '.' + name[offset:offset + domain_length] offset = offset + domain_length return offset + 1, decoded_name, decoded_domain ================================================ FILE: python3/smb/SMBConnection.py ================================================ import os, logging, select, socket, types, typing, struct, errno from tqdm import tqdm from .smb_constants import * from .smb_structs import * from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout class SMBConnection(SMB): log = logging.getLogger('SMB.SMBConnection') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. The default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ SMB.__init__(self, username, password, my_name, remote_name, domain, use_ntlm_v2, sign_options, is_direct_tcp) self.sock = None self.auth_result = None self.is_busy = False self.is_direct_tcp = is_direct_tcp # # SMB (and its superclass) Methods # def onAuthOK(self): self.auth_result = True def onAuthFailed(self): self.auth_result = False def write(self, data): assert self.sock data_len = len(data) total_sent = 0 while total_sent < data_len: sent = self.sock.send(data[total_sent:]) if sent == 0: raise NotConnectedError('Server disconnected') total_sent = total_sent + sent # # Support for "with" context # def __enter__(self): return self def __exit__(self, *args): self.close() # # Misc Properties # @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.is_using_smb2 # # Public Methods # def connect(self, ip, port = 139, sock_family = None, timeout = 60): """ Establish the SMB connection to the remote SMB/CIFS server. You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication. :param port: Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445. :param sock_family: In Python 3.x, use *None* as we can infer the socket family from the provided *ip*. In Python 2.x, it must be either *socket.AF_INET* or *socket.AF_INET6*. :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise. """ if self.sock: self.sock.close() self.auth_result = None if sock_family: self.sock = socket.socket(sock_family) self.sock.settimeout(timeout) self.sock.connect(( ip, port )) else: self.sock = socket.create_connection(( ip, port ), timeout = timeout) self.is_busy = True try: if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() while self.auth_result is None: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return self.auth_result def close(self): """ Terminate the SMB connection (if it has been started) and release any sources held by the underlying socket. """ if self.sock: self.sock.close() self.sock = None def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :return: A list of :doc:`smb.base.SharedDevice` instances describing the shared resource """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listShares(cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile` instances. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listPath(service_name, path, cb, eb, search = search, pattern = pattern, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(entries): self.is_busy = False results.extend(entries) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._listSnapshots(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A :doc:`smb.base.SharedFile` instance containing the attributes of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def getSecurity(self, service_name, path, timeout = 30): """ Retrieve the security descriptor of the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(info): self.is_busy = False results.append(info) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._getSecurity(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def retrieveFile(self, service_name, path, file_obj, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you wish to specify the offset to read from the remote *path* and/or the number of bytes to write to the *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout, show_progress = show_progress, tqdm_kwargs = tqdm_kwargs) def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* up to *max_length* number of bytes. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the method returns immediately after the file is opened successfully for reading. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1:]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._retrieveFileFromOffset(service_name, path, file_obj, cb, eb, offset, max_length, timeout = timeout, show_progress=show_progress, tqdm_kwargs=tqdm_kwargs) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def storeFile(self, service_name, path, file_obj, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Store the contents of the *file_obj* at *path* on the *service_name*. If the file already exists on the remote server, it will be truncated and overwritten. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: Number of bytes uploaded """ return self.storeFileFromOffset(service_name, path, file_obj, 0, True, timeout, show_progress = show_progress, tqdm_kwargs = tqdm_kwargs) def storeFileFromOffset(self, service_name, path, file_obj, offset = 0, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = {}): """ Store the contents of the *file_obj* at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be raised. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. :param offset: Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0. :param truncate: Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False. :param bool show_progress: If True, a progress bar will be shown to reflect the current file operation progress. :return: the file position where the next byte will be written. """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r[1]) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._storeFileFromOffset(service_name, path, file_obj, cb, eb, offset, truncate = truncate, timeout = timeout, show_progress=show_progress, tqdm_kwargs=tqdm_kwargs) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) Note: this function is currently only implemented for SMB2! :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def createDirectory(self, service_name, path, timeout = 30): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._createDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def deleteDirectory(self, service_name, path, timeout = 30): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._deleteDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def rename(self, service_name, old_path, new_path, timeout = 30): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): self.is_busy = False def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._rename(service_name, old_path, new_path, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: raise NotConnectedError('Not connected to server') results = [ ] def cb(r): self.is_busy = False results.append(r) def eb(failure): self.is_busy = False raise failure self.is_busy = True try: self._echo(data, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: self.is_busy = False return results[0] # # Protected Methods # def _poll_for_data(self, expiry_time, read_len, data, timeout, poller): while read_len > 0: try: if expiry_time < time.time(): raise SMBTimeout if poller: ready = poller.poll(timeout * 1000) else: ready, _, _ = select.select([self.sock.fileno()], [], [], timeout) if not ready: raise SMBTimeout d = self.sock.recv(read_len) if len(d) == 0: raise NotConnectedError data += d read_len -= len(d) except select.error as ex: if getattr(ex, "errno", None) not in (errno.EINTR, errno.EAGAIN): raise ex return data, read_len def _pollForNetBIOSPacket(self, timeout): if os.name == "posix": poller = select.poll() poller.register(self.sock, select.POLLIN) else: poller = None expiry_time = time.time() + timeout read_len = 4 data = b"" data, read_len = self._poll_for_data( expiry_time=expiry_time, read_len=read_len, data=data, timeout=timeout, poller=poller, ) type, flags, length = struct.unpack(">BBH", data) if flags & 0x01: length = length | 0x10000 data, read_len = self._poll_for_data( expiry_time=expiry_time, read_len=length, data=data, timeout=timeout, poller=poller, ) self.feedData(data) ================================================ FILE: python3/smb/SMBHandler.py ================================================ import os, sys, socket, urllib.request, urllib.error, urllib.parse, mimetypes, email, tempfile from urllib.parse import (unwrap, unquote, splittype, splithost, quote, splitport, splittag, splitattr, splituser, splitpasswd, splitvalue) from urllib.response import addinfourl from urllib.request import ftpwrapper from nmb.NetBIOS import NetBIOS from smb.SMBConnection import SMBConnection from io import BytesIO USE_NTLM = True MACHINE_NAME = None class SMBHandler(urllib.request.BaseHandler): def smb_open(self, req): global USE_NTLM, MACHINE_NAME if not req.host: raise urllib.error.URLError('SMB error: no host given') host, port = splitport(req.host) if port is None: port = 139 else: port = int(port) # username/password handling user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = user or '' domain = '' if ';' in user: domain, user = user.split(';', 1) passwd = passwd or '' myname = MACHINE_NAME or self.generateClientMachineName() server_name,host = host.split(',') if ',' in host else [None,host] if server_name is None: n = NetBIOS() names = n.queryIPForName(host) if names: server_name = names[0] else: raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name') path, attrs = splitattr(req.selector) if path.startswith('/'): path = path[1:] dirs = path.split('/') dirs = list(map(unquote, dirs)) service, path = dirs[0], '/'.join(dirs[1:]) try: conn = SMBConnection(user, passwd, myname, server_name, domain=domain, use_ntlm_v2 = USE_NTLM) conn.connect(host, port) headers = email.message.Message() if req.data: filelen = conn.storeFile(service, path, req.data) headers.add_header('Content-length', '0') fp = BytesIO(b"") else: fp = self.createTempFile() file_attrs, retrlen = conn.retrieveFile(service, path, fp) fp.seek(0) mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers.add_header('Content-type', mtype) if retrlen is not None and retrlen >= 0: headers.add_header('Content-length', '%d' % retrlen) return addinfourl(fp, headers, req.get_full_url()) except Exception as ex: raise urllib.error.URLError('smb error: %s' % ex).with_traceback(sys.exc_info()[2]) def createTempFile(self): return tempfile.TemporaryFile() def generateClientMachineName(self): hostname = socket.gethostname() if hostname: return hostname.split('.')[0] return 'SMB%d' % os.getpid() ================================================ FILE: python3/smb/SMBProtocol.py ================================================ import os, logging, time from twisted.internet import reactor, defer from twisted.internet.protocol import ClientFactory, Protocol from .smb_constants import * from .smb_structs import * from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout __all__ = [ 'SMBProtocolFactory', 'NotConnectedError', 'NotReadyError' ] class SMBProtocol(Protocol, SMB): log = logging.getLogger('SMB.SMBProtocol') # # Protocol Methods # def connectionMade(self): self.factory.instance = self if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() def connectionLost(self, reason): if self.factory.instance == self: self.instance = None def dataReceived(self, data): self.feedData(data) # # SMB (and its superclass) Methods # def write(self, data): self.transport.write(data) def onAuthOK(self): if self.factory.instance == self: self.factory.onAuthOK() reactor.callLater(1, self._cleanupPendingRequests) def onAuthFailed(self): if self.factory.instance == self: self.factory.onAuthFailed() def onNMBSessionFailed(self): self.log.error('Cannot establish NetBIOS session. You might have provided a wrong remote_name') # # Protected Methods # def _cleanupPendingRequests(self): if self.factory.instance == self: now = time.time() to_remove = [] for mid, r in self.pending_requests.items(): if r.expiry_time < now: try: r.errback(SMBTimeout()) except Exception: pass to_remove.append(mid) for mid in to_remove: del self.pending_requests[mid] reactor.callLater(1, self._cleanupPendingRequests) class SMBProtocolFactory(ClientFactory): protocol = SMBProtocol log = logging.getLogger('SMB.SMBFactory') #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. SIGN_NEVER = 0 #: SMB messages will be signed when remote server supports signing but not requires signing. SIGN_WHEN_SUPPORTED = 1 #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBProtocolFactory instance. You will pass this instance to *reactor.connectTCP()* which will then instantiate the TCP connection to the remote SMB/CIFS server. Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. File operations can only be proceeded after the connection has been authenticated successfully. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string. :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only "guess" or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2. :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*. If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing. If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If *SIGN_NEVER* (value=0), SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing. :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ self.username = username self.password = password self.my_name = my_name self.remote_name = remote_name self.domain = domain self.use_ntlm_v2 = use_ntlm_v2 self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.instance = None #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly. # # Public Property # @property def isReady(self): """A convenient property to return True if the underlying SMB connection has connected to remote server, has successfully authenticated itself and is ready for file operations.""" return bool(self.instance and self.instance.has_authenticated) @property def isUsingSMB2(self): """A convenient property to return True if the underlying SMB connection is using SMB2 protocol.""" return self.instance and self.instance.is_using_smb2 # # Public Methods for Callbacks # def onAuthOK(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. File operations can proceed when this method has been called. """ pass def onAuthFailed(self): """ Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling. This method will be called when the server has replied that the SMB connection has been successfully authenticated. If you want to retry authenticating from this method, 1. Disconnect the underlying SMB connection (call ``self.instance.transport.loseConnection()``) 2. Create a new SMBProtocolFactory subclass instance with different user credientials or different NTLM algorithm flag. 3. Call ``reactor.connectTCP`` with the new instance to re-establish the SMB connection """ pass # # Public Methods # def listShares(self, timeout = 30): """ Retrieve a list of shared resources on remote server. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedDevice` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listShares(d.callback, d.errback, timeout) return d def listPath(self, service_name, path, search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile` instances. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listPath(service_name, path, d.callback, d.errback, search = search, pattern = pattern, timeout = timeout) return d def listSnapshots(self, service_name, path, timeout = 30): """ Retrieve a list of available snapshots (a.k.a. shadow copies) for *path*. Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of python *datetime.DateTime* instances in GMT/UTC time zone """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._listSnapshots(service_name, path, d.callback, d.errback, timeout = timeout) return d def getAttributes(self, service_name, path, timeout = 30): """ Retrieve information about the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a :doc:`smb.base.SharedFile` instance containing the attributes of the file. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._getAttributes(service_name, path, d.callback, d.errback, timeout = timeout) return d def retrieveFile(self, service_name, path, file_obj, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. Use *retrieveFileFromOffset()* method if you need to specify the offset to read from the remote *path* and/or the maximum number of bytes to write to the *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout) def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the *Deferred* callback is invoked immediately after the file is opened successfully for reading. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._retrieveFileFromOffset(service_name, path, file_obj, d.callback, d.errback, offset, max_length, timeout = timeout) return d def storeFile(self, service_name, path, file_obj, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. The meaning of the *timeout* parameter will be different from other file operation methods. As the uploaded file usually exceeeds the maximum size of each SMB/CIFS data message, it will be packetized into a series of messages (usually about 60kBytes). The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and acknowledged by the remote SMB/CIFS server. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure` will be called in the returned *Deferred* errback. :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *file_obj*, number of bytes uploaded ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout) return d def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path_file_pattern* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteFiles(service_name, path_file_pattern, delete_matching_folders, d.callback, d.errback, timeout = timeout) return d def createDirectory(self, service_name, path): """ Creates a new directory *path* on the *service_name*. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._createDirectory(service_name, path, d.callback, d.errback) return d def deleteDirectory(self, service_name, path): """ Delete the empty folder at *path* on *service_name* :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._deleteDirectory(service_name, path, d.callback, d.errback) return d def rename(self, service_name, old_path, new_path): """ Rename a file or folder at *old_path* to *new_path* shared at *service_name*. Note that this method cannot be used to rename file/folder across different shared folders *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path. :param string/unicode service_name: Contains the name of the shared folder. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *old_path*, *new_path* ). """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._rename(service_name, old_path, new_path, d.callback, d.errback) return d def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ if not self.instance: raise NotConnectedError('Not connected to server') d = defer.Deferred() self.instance._echo(data, d.callback, d.errback, timeout) return d def closeConnection(self): """ Disconnect from the remote SMB/CIFS server. The TCP connection will be closed at the earliest opportunity after this method returns. :return: None """ if not self.instance: raise NotConnectedError('Not connected to server') self.instance.transport.loseConnection() # # ClientFactory methods # (Do not touch these unless you know what you are doing) # def buildProtocol(self, addr): p = self.protocol(self.username, self.password, self.my_name, self.remote_name, self.domain, self.use_ntlm_v2, self.sign_options, self.is_direct_tcp) p.factory = self return p ================================================ FILE: python3/smb/__init__.py ================================================ ================================================ FILE: python3/smb/base.py ================================================ import logging, binascii, time, hmac from datetime import datetime from tqdm import tqdm from .smb_constants import * from .smb2_constants import * from .smb_structs import * from .smb2_structs import * from .security_descriptors import SecurityDescriptor from nmb.base import NMBSession from .utils import convertFILETIMEtoEpoch from . import ntlm, securityblob from .strategy import DataFaultToleranceStrategy try: import hashlib sha256 = hashlib.sha256 except ImportError: from .utils import sha256 class NotReadyError(Exception): """Raised when SMB connection is not ready (i.e. not authenticated or authentication failed)""" pass class NotConnectedError(Exception): """Raised when underlying SMB connection has been disconnected or not connected yet""" pass class SMBTimeout(Exception): """Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete.""" pass class SMB(NMBSession): """ This class represents a "connection" to the remote SMB/CIFS server. It is not meant to be used directly in an application as it does not have any network transport implementations. For application use, please refer to - L{SMBProtocol.SMBProtocolFactory} if you are using Twisted framework In [MS-CIFS], this class will contain attributes of Client, Client.Connection and Client.Session abstract data models. References: =========== - [MS-CIFS]: 3.2.1 """ log = logging.getLogger('SMB.SMB') SIGN_NEVER = 0 SIGN_WHEN_SUPPORTED = 1 SIGN_WHEN_REQUIRED = 2 def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) self.username = username self._password = password self.domain = domain self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages self.has_negotiated = False self.has_authenticated = False self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2 self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2 self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2 self.mid = 0 self.uid = 0 self.next_signing_id = 2 #: Similar to ClientNextSendSequenceNumber as described in [MS-CIFS] 3.2.1.2 # SMB1 and SMB2 attributes # Note that the interpretations of the values may differ between SMB1 and SMB2 protocols self.capabilities = 0 self.security_mode = 0 #: Initialized from the SecurityMode field of the SMB_COM_NEGOTIATE message # SMB1 attributes # Most of the following attributes will be initialized upon receipt of SMB_COM_NEGOTIATE message from server (via self._updateServerInfo_SMB1 method) self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1 self.max_raw_size = 0 self.max_buffer_size = 0 #: Similar to MaxBufferSize as described in [MS-CIFS] 3.2.1.1 self.max_mpx_count = 0 #: Similar to MaxMpxCount as described in [MS-CIFS] 3.2.1.1 # SMB2 attributes self.max_read_size = 0 #: Similar to MaxReadSize as described in [MS-SMB2] 2.2.4 self.max_write_size = 0 #: Similar to MaxWriteSize as described in [MS-SMB2] 2.2.4 self.max_transact_size = 0 #: Similar to MaxTransactSize as described in [MS-SMB2] 2.2.4 self.session_id = 0 #: Similar to SessionID as described in [MS-SMB2] 2.2.4. This will be set in _updateState_SMB2 method # tqdm attributes for tracking progress self.pbar = None #: If not None, it means there is an active tqdm progress bar being shown self._setupSMB1Methods() self.log.info('Authentication with remote machine "%s" for user "%s" will be using NTLM %s authentication (%s extended security)', self.remote_name, self.username, (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') @property def password(self): if callable(self._password): return self._password() return self._password # # NMBSession Methods # def onNMBSessionOK(self): self._sendSMBMessage(SMBMessage(ComNegotiateRequest())) def onNMBSessionFailed(self): pass def onNMBSessionMessage(self, flags, data): while True: try: i = self.smb_message.decode(data) except SMB2ProtocolHeaderError: self.log.info('Now switching over to SMB2 protocol communication') self.is_using_smb2 = True self.mid = 0 # Must reset messageID counter, or else remote SMB2 server will disconnect self._setupSMB2Methods() self.smb_message = self._klassSMBMessage() i = self.smb_message.decode(data) next_message_offset = 0 if self.is_using_smb2: next_message_offset = self.smb_message.next_command_offset if i > 0: if not self.is_using_smb2: self.log.debug('Received SMB message "%s" (command:0x%2X flags:0x%02X flags2:0x%04X TID:%d UID:%d)', SMB_COMMAND_NAMES.get(self.smb_message.command, ''), self.smb_message.command, self.smb_message.flags, self.smb_message.flags2, self.smb_message.tid, self.smb_message.uid) else: self.log.debug('Received SMB2 message "%s" (command:0x%04X flags:0x%04x)', SMB2_COMMAND_NAMES.get(self.smb_message.command, ''), self.smb_message.command, self.smb_message.flags) if self._updateState(self.smb_message): # We need to create a new instance instead of calling reset() because the instance could be captured in the message history. self.smb_message = self._klassSMBMessage() if next_message_offset > 0: data = data[next_message_offset:] else: break # # Public Methods for Overriding in Subclasses # def onAuthOK(self): pass def onAuthFailed(self): pass # # Protected Methods # def _setupSMB1Methods(self): self._klassSMBMessage = SMBMessage self._updateState = self._updateState_SMB1 self._updateServerInfo = self._updateServerInfo_SMB1 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB1 self._sendSMBMessage = self._sendSMBMessage_SMB1 self._handleSessionChallenge = self._handleSessionChallenge_SMB1 self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 self._storeFile = self._storeFile_SMB1 self._storeFileFromOffset = self._storeFileFromOffset_SMB1 self._deleteFiles = self._deleteFiles_SMB1 self._resetFileAttributes = self._resetFileAttributes_SMB1 self._createDirectory = self._createDirectory_SMB1 self._deleteDirectory = self._deleteDirectory_SMB1 self._rename = self._rename_SMB1 self._echo = self._echo_SMB1 def _setupSMB2Methods(self): self._klassSMBMessage = SMB2Message self._updateState = self._updateState_SMB2 self._updateServerInfo = self._updateServerInfo_SMB2 self._handleNegotiateResponse = self._handleNegotiateResponse_SMB2 self._sendSMBMessage = self._sendSMBMessage_SMB2 self._handleSessionChallenge = self._handleSessionChallenge_SMB2 self._listShares = self._listShares_SMB2 self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 self._getSecurity = self._getSecurity_SMB2 self._getAttributes = self._getAttributes_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 self._storeFile = self._storeFile_SMB2 self._storeFileFromOffset = self._storeFileFromOffset_SMB2 self._deleteFiles = self._deleteFiles_SMB2 self._resetFileAttributes = self._resetFileAttributes_SMB2 self._createDirectory = self._createDirectory_SMB2 self._deleteDirectory = self._deleteDirectory_SMB2 self._rename = self._rename_SMB2 self._echo = self._echo_SMB2 def _getNextRPCCallID(self): self.next_rpc_call_id += 1 return self.next_rpc_call_id # # SMB2 Methods Family # def _sendSMBMessage_SMB2(self, smb_message): if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: smb_message.flags |= SMB2_FLAGS_SIGNED raw_data = smb_message.encode() smb_message.signature = hmac.new(self.signing_session_key, raw_data, sha256).digest()[:16] smb_message.raw_data = smb_message.encode() self.log.debug('MID is %d. Signature is %s. Total raw message is %d bytes', smb_message.mid, binascii.hexlify(smb_message.signature), len(smb_message.raw_data)) else: smb_message.raw_data = smb_message.encode() self.sendNMBMessage(smb_message.raw_data) def _getNextMID_SMB2(self): self.mid += 1 return self.mid def _updateState_SMB2(self, message): if message.isReply: if message.command == SMB2_COM_NEGOTIATE: if message.status == 0: self.has_negotiated = True self.log.info('SMB2 dialect negotiation successful') self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB2_COM_NEGOTIATE' % message.status, message.raw_data, message) elif message.command == SMB2_COM_SESSION_SETUP: if message.status == 0: self.session_id = message.session_id try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') # [MS-SMB2]: 3.2.5.3.1 # If the security subsystem indicates that the session was established by an anonymous user, # Session.SigningRequired MUST be set to FALSE. # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired # MUST be set to FALSE. if message.payload.isGuestSession or message.payload.isAnonymousSession: self.is_signing_active = False self.log.info('Signing disabled because session is guest/anonymous') self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED self.session_id = message.session_id try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE or message.status == 0xc0000064 # STATUS_NO_SUCH_USER or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account or password has expired.') self.onAuthFailed() elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Account has been disabled.') self.onAuthFailed() elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Not allowed.') self.onAuthFailed() elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Domain not trusted.') self.onAuthFailed() elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) if message.isAsync: if message.status == 0x00000103: # STATUS_PENDING req = self.pending_requests.pop(message.mid, None) if req: self.async_requests[message.async_id] = req else: # All other status including SUCCESS req = self.async_requests.pop(message.async_id, None) if req: req.callback(message, **req.kwargs) return True else: req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB2(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_transact_size = payload.max_transact_size self.max_read_size = payload.max_read_size self.max_write_size = payload.max_write_size self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication def _handleNegotiateResponse_SMB2(self, message): ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) def _handleSessionChallenge_SMB2(self, message, ntlm_token): server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob))) if self.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & SMB2_NEGOTIATE_SIGNING_ENABLED: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = session_signing_key if self.log.isEnabledFor(logging.DEBUG): self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _listShares_SMB2(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMB2Message(SMB2CreateRequest('srvsvc', file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE | FILE_OPEN_NO_RECALL, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: call_id = self._getNextRPCCallID() # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(b' ', b'')) + \ struct.pack(' data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name, _, file_id = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset2:offset2+filename_length]) short_name = DataFaultToleranceStrategy.data_bytes_decode(short_name[:short_name_length]) accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset else: break return b'' def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files callback([ ]) else: errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getAttributes_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: p = create_message.payload filename = self._extractLastPathComponent(path) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, filename, filename) closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) def closeFid(tid, fid, info = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, info = info, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['info'] is not None: callback(kwargs['info']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get attributes for %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, info_type = SMB2_INFO_SECURITY, file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 input_buf = '', output_buf_len = self.max_transact_size)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) def queryCB(query_message, **kwargs): self._pushToArray(messages_history, query_message) if query_message.status == 0: security = SecurityDescriptor.from_bytes(query_message.payload.data) closeFid(kwargs['tid'], kwargs['fid'], result = security) else: closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def closeFid(tid, fid, result = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['result'] is not None: callback(kwargs['result']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout) def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] results = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 input_buf = b'', output_buf_len = 4096)) m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) self._pushToArray(messages_history, m) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): self._pushToArray(messages_history, info_message) if info_message.status == 0: file_len = struct.unpack(' file_len: if self.pbar: self.pbar.close() self.pbar = None closeFid(info_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], 0 )) # Note that this is a tuple of 3-elements else: remaining_len = max_length if remaining_len < 0: remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset if show_progress: tqdm_kwargs.setdefault("total", remaining_len) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Downloading {path}") self.pbar = tqdm(**tqdm_kwargs) sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) m = SMB2Message(SMB2ReadRequest(fid, offset, read_count)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) def readCB(read_message, **kwargs): # To avoid crazy memory usage when retrieving large files, we do not save every read_message in messages_history. if read_message.status == 0: data_len = read_message.payload.data_length file_obj.write(read_message.payload.data) remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) if self.pbar: self.pbar.update(data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: self._pushToArray(messages_history, read_message) closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, ret = ret, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['ret'] is not None: callback(kwargs['ret']) elif kwargs['error'] is not None: errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _storeFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): self._storeFileFromOffset_SMB2(service_name, path, file_obj, callback, errback, 0, True, timeout) def _storeFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] if show_progress: total_bytes = os.stat(file_obj.name).st_size tqdm_kwargs.setdefault("total", total_bytes) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Uploading {path}") self.pbar = tqdm(**tqdm_kwargs) def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 10 00 04 00 00 00 18 00 08 00 00 00 41 6c 53 69 00 00 00 00 85 62 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = ATTR_ARCHIVE, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, create_disp = FILE_OVERWRITE_IF if truncate else FILE_OPEN_IF, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): create_message.tid = kwargs['tid'] self._pushToArray(messages_history, create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): write_count = self.max_write_size data = file_obj.read(write_count) data_len = len(data) if data_len > 0: m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) if self.pbar: self.pbar.update(data_len) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, write_message) closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid, error = None, offset = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, fid = fid, offset = offset, error = error) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['offset'] is not None: callback(( file_obj, kwargs['offset'] )) # Note that this is a tuple of 2-elements elif kwargs['error'] is not None: errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_NON_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): open_message.tid = kwargs['tid'] self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(open_message.tid, open_message.payload.fid) elif open_message.status == 0xc0000034: # STATUS_OBJECT_NAME_NOT_FOUND callback(path) elif open_message.status == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = b'\x01')) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendCreate(tid) def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_WRITE_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = 0, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendReset(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation data = struct.pack('qqqqii', 0, 0, 0, 0, file_attributes, 0))) # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def resetCB(reset_message, **kwargs): self._pushToArray(messages_history, reset_message) if reset_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path_file_pattern) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Reset failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _createDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_EA | FILE_WRITE_EA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | READ_CONTROL | DELETE | SYNCHRONIZE, share_access = 0, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_CREATE, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): callback(path) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] messages_history = [ ] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_DIRECTORY_FILE, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if open_message.status == 0: sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendDelete(tid, fid): m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = b'\x01')) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if delete_message.status == 0: closeFid(kwargs['tid'], kwargs['fid'], status = 0) else: closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, status = status) self._pushToArray(messages_history, m) def closeCB(close_message, **kwargs): if kwargs['status'] == 0: callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if connect_message.status == 0: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _rename_SMB2(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout messages_history = [ ] new_path = new_path.replace('/', '\\') if new_path.startswith('\\'): new_path = new_path[1:] if new_path.endswith('\\'): new_path = new_path[:-1] old_path = old_path.replace('/', '\\') if old_path.startswith('\\'): old_path = old_path[1:] if old_path.endswith('\\'): old_path = old_path[:-1] def sendCreate(tid): create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(old_path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SYNCHRONOUS_IO_NONALERT, create_disp = FILE_OPEN, create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if create_message.status == 0: sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) def sendRename(tid, fid): data = b'\x00'*16 + struct.pack('= 0xFFFF: # MID cannot be 0xFFFF. [MS-CIFS]: 2.2.1.6.2 # We don't use MID of 0 as MID can be reused for SMB_COM_TRANSACTION2_SECONDARY messages # where if mid=0, _sendSMBMessage will re-assign new MID values again self.mid = 1 return self.mid def _updateState_SMB1(self, message): if message.isReply: if message.command == SMB_COM_NEGOTIATE: if not message.status.hasError: self.has_negotiated = True self.log.info('SMB dialect negotiation successful (ExtendedSecurity:%s)', message.hasExtendedSecurity) self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_NEGOTIATE' % message.status.internal_value, message.raw_data, message) elif message.command == SMB_COM_SESSION_SETUP_ANDX: if message.hasExtendedSecurity: if not message.status.hasError: try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (with extended security) successful!') self.onAuthOK() else: raise ProtocolError('SMB_COM_SESSION_SETUP_ANDX status is 0 but security blob negResult value is %d' % result, message.raw_data, message) except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status.internal_value == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Please check username and password.') self.onAuthFailed() elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account or password has expired.') self.onAuthFailed() elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') self.onAuthFailed() elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Account has been disabled.') self.onAuthFailed() elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Not allowed.') self.onAuthFailed() elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Domain not trusted.') self.onAuthFailed() elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE self.has_authenticated = False self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, message.raw_data, message) else: if message.status.internal_value == 0: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid self.has_authenticated = True self.log.info('Authentication (without extended security) successful!') self.onAuthOK() else: self.has_authenticated = False self.log.info('Authentication (without extended security) failed. Please check username and password') self.onAuthFailed() elif message.command == SMB_COM_TREE_CONNECT_ANDX: try: req = self.pending_requests[message.mid] except KeyError: pass else: if not message.status.hasError: self.connected_trees[req.kwargs['path']] = message.tid req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) return True def _updateServerInfo_SMB1(self, payload): self.capabilities = payload.capabilities self.security_mode = payload.security_mode self.max_raw_size = payload.max_raw_size self.max_buffer_size = payload.max_buffer_size self.max_mpx_count = payload.max_mpx_count self.use_plaintext_authentication = not bool(payload.security_mode & NEGOTIATE_ENCRYPT_PASSWORDS) if self.use_plaintext_authentication: self.log.warning('Remote server only supports plaintext authentication. Your password can be stolen easily over the network.') def _handleSessionChallenge_SMB1(self, message, ntlm_token): assert message.hasExtendedSecurity if message.uid and not self.uid: self.uid = message.uid server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token) if self.use_ntlm_v2: self.log.info('Performing NTLMv2 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password, self.username, server_challenge, server_info, self.domain) else: self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) ntlm_data, signing_session_key = ntlm.generateAuthenticateMessage(server_flags, nt_challenge_response, lm_challenge_response, session_key, self.username, self.domain, self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response)) blob = securityblob.generateAuthSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(0, blob))) if self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRE: self.log.info('Server requires all SMB messages to be signed') self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER) elif self.security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLE: self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") self.signing_session_key = signing_session_key if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: self.signing_challenge_response = blob else: self.log.info("SMB signing deactivated. SMB messages will NOT be signed.") def _handleNegotiateResponse_SMB1(self, message): if message.uid and not self.uid: self.uid = message.uid if message.hasExtendedSecurity or message.payload.supportsExtendedSecurity: ntlm_data = ntlm.generateNegotiateMessage() blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(message.payload.session_key, blob))) else: nt_password, _, _ = ntlm.generateChallengeResponseV1(self.password, message.payload.challenge, False) self.log.info('Performing NTLMv1 authentication (without extended security) with challenge "%s" and hashed password of "%s"', binascii.hexlify(message.payload.challenge), binascii.hexlify(nt_password)) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__NoSecurityExtension(message.payload.session_key, self.username, nt_password, True, self.domain))) def _listShares_SMB1(self, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = 'IPC$' messages_history = [ ] def connectSrvSvc(tid): m = SMBMessage(ComNTCreateAndxRequest('\\srvsvc', flags = NT_CREATE_REQUEST_EXTENDED_RESPONSE, access_mask = READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_READ_EA | FILE_APPEND_DATA | FILE_WRITE_DATA | FILE_READ_DATA, share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, create_disp = FILE_OPEN, create_options = FILE_OPEN_NO_RECALL | FILE_NON_DIRECTORY_FILE, impersonation = SEC_IMPERSONATE, security_flags = 0)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) self._pushToArray(messages_history, m) def connectSrvSvcCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: call_id = self._getNextRPCCallID() # See [MS-CIFS]: 2.2.5.6.1 for more information on TRANS_TRANSACT_NMPIPE (0x0026) parameters setup_bytes = struct.pack(' data_length: return data_bytes[offset:] next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ short_name_length, _, short_name = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset2:offset2+filename_length]) short_name = DataFaultToleranceStrategy.data_bytes_decode(short_name) accept_result = False if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) else: accept_result = (file_attributes & search) > 0 if accept_result: results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset else: break return b'' def findFirstCB(find_message, **kwargs): self._pushToArray(messages_history, find_message) if not find_message.status.hasError: if 'total_count' not in kwargs: # TRANS2_FIND_FIRST2 response. [MS-CIFS]: 2.2.6.2.2 sid, search_count, end_of_search, _, last_name_offset = struct.unpack(' 0: tqdm_kwargs.setdefault("total", max_length) tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Downloading {path}") self.pbar = tqdm(**tqdm_kwargs) sendRead(open_message.tid, open_message.payload.fid, starting_offset, open_message.payload.file_attributes, 0, max_length) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, file_attributes, read_len, remaining_len): read_count = self.max_raw_size - 2 m = SMBMessage(ComReadAndxRequest(fid = fid, offset = offset, max_return_bytes_count = read_count, min_return_bytes_count = min(0xFFFF, read_count))) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, fid = fid, offset = offset, file_attributes = file_attributes, read_len = read_len, remaining_len = remaining_len) def readCB(read_message, **kwargs): # To avoid crazy memory usage when retrieving large files, we do not save every read_message in messages_history. if not read_message.status.hasError: read_len = kwargs['read_len'] remaining_len = kwargs['remaining_len'] data_len = read_message.payload.data_length if max_length > 0: if data_len > remaining_len: file_obj.write(read_message.payload.data[:remaining_len]) read_len += remaining_len remaining_len = 0 else: file_obj.write(read_message.payload.data) remaining_len -= data_len read_len += data_len else: file_obj.write(read_message.payload.data) read_len += data_len if self.pbar: self.pbar.update(data_len) if (max_length > 0 and remaining_len <= 0) or data_len < (self.max_raw_size - 2): if self.pbar: self.pbar.close() self.pbar = None closeFid(read_message.tid, kwargs['fid']) callback(( file_obj, kwargs['file_attributes'], read_len )) # Note that this is a tuple of 3-elements else: sendRead(read_message.tid, kwargs['fid'], kwargs['offset']+data_len, kwargs['file_attributes'], read_len, remaining_len) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, read_message) closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _storeFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30, show_progress = False, tqdm_kwargs = { }): self._storeFileFromOffset_SMB1(service_name, path, file_obj, callback, errback, 0, True, timeout, show_progress, tqdm_kwargs) def _storeFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30, show_progress = False, tqdm_kwargs = { }): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0041, # Sharing mode: Deny nothing to others + Open for writing open_mode = 0x0012 if truncate else 0x0011, # Create file if file does not exist. Overwrite or append depending on truncate parameter. search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: if show_progress: tqdm_kwargs.setdefault("unit", "B") tqdm_kwargs.setdefault("unit_scale", True) tqdm_kwargs.setdefault("unit_divisor", 1024) tqdm_kwargs.setdefault("desc", f"Uploading {path}") self.pbar = tqdm(**tqdm_kwargs) sendWrite(open_message.tid, open_message.payload.fid, starting_offset) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): # [MS-SMB] 2.2.4.5.2.2: The total SMB message size (inclusive of SMB header) must be not exceed the max_buffer_size. write_count = min(self.max_buffer_size-64, 0xFFFF-64) # SMB header is 32-bytes. We factor in another 32-bytes for the message parameter block data_bytes = file_obj.read(write_count) data_len = len(data_bytes) if data_len > 0: m = SMBMessage(ComWriteAndxRequest(fid = fid, offset = offset, data_bytes = data_bytes)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) else: if self.pbar: self.pbar.close() self.pbar = None closeFid(tid, fid) callback(( file_obj, offset )) # Note that this is a tuple of 2-elements def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if not write_message.status.hasError: if self.pbar: self.pbar.update(kwargs['offset']) sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) else: if self.pbar: self.pbar.close() self.pbar = None self._pushToArray(messages_history, write_message) closeFid(write_message.tid, kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid): m = SMBMessage(ComCloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) self._pushToArray(messages_history, m) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendOpen(connect_message.tid) else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendOpen(self.connected_trees[service_name]) def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] else: path_components = path.split('\\') if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: path = '\\'.join(path_components[:-1]) pattern = path_components[-1] messages_history, files_queue = [ ], [ ] if pattern is None: path_components = path.split('\\') if len(path_components) > 1: files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) else: files_queue.append(( '', path )) def deleteCB(path): if files_queue: p, filename = files_queue.pop(0) if filename: if p: filename = p + '\\' + filename self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) else: self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) else: callback(path_file_pattern) def listCB(files_list): files_queue.extend(files_list) deleteCB(None) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: if files_queue: deleteCB(None) else: self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): folder_queue = [ ] files_list = [ ] current_path = [ path ] search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL def listCB(results): files = [ ] for f in filter(lambda x: x.filename not in [ '.', '..' ], results): if f.isDirectory: if delete_matching_folders: folder_queue.append(current_path[0]+'\\'+f.filename) else: files.append(( current_path[0], f.filename )) if current_path[0]!=path and delete_matching_folders: files.append(( current_path[0], None )) if files: files_list[0:0] = files if folder_queue: p = folder_queue.pop() current_path[0] = p self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) else: callback(files_list) self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteRequest(filename_pattern = path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) elif delete_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE # If there are no matching files, we just treat as success instead of failing callback(path) elif delete_message.status.internal_value == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) elif delete_message.status.internal_value == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) sendDelete(tid) def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendCreate(tid): m = SMBMessage(ComCreateDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) self._pushToArray(messages_history, m) def createCB(create_message, **kwargs): self._pushToArray(messages_history, create_message) if not create_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendCreate(self.connected_trees[service_name]) def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') path = path.replace('/', '\\') messages_history = [ ] def sendDelete(tid): m = SMBMessage(ComDeleteDirectoryRequest(path)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) self._pushToArray(messages_history, m) def deleteCB(delete_message, **kwargs): self._pushToArray(messages_history, delete_message) if not delete_message.status.hasError: callback(path) else: errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendDelete(self.connected_trees[service_name]) def _rename_SMB1(self, service_name, old_path, new_path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') new_path = new_path.replace('/', '\\') old_path = old_path.replace('/', '\\') messages_history = [ ] def sendRename(tid): m = SMBMessage(ComRenameRequest(old_path = old_path, new_path = new_path, search_attributes = SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback) self._pushToArray(messages_history, m) def renameCB(rename_message, **kwargs): self._pushToArray(messages_history, rename_message) if not rename_message.status.hasError: callback(( old_path, new_path )) # Note that this is a tuple of 2-elements else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): self._pushToArray(messages_history, connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendRename(connect_message.tid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) self._pushToArray(messages_history, m) else: sendRename(self.connected_trees[service_name]) def _listSnapshots_SMB1(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout path = path.replace('/', '\\') if not path.endswith('\\'): path += '\\' messages_history = [ ] results = [ ] def sendOpen(tid): m = SMBMessage(ComOpenAndxRequest(filename = path, access_mode = 0x0040, # Sharing mode: Deny nothing to others open_mode = 0x0001, # Failed if file does not exist search_attributes = 0, timeout = timeout * 1000)) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, openCB, errback) self._pushToArray(messages_history, m) def openCB(open_message, **kwargs): self._pushToArray(messages_history, open_message) if not open_message.status.hasError: sendEnumSnapshots(open_message.tid, open_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open path' % ( path, service_name ), messages_history)) def sendEnumSnapshots(tid, fid): # [MS-CIFS]: 2.2.7.2 # [MS-SMB]: 2.2.7.2.1 setup_bytes = struct.pack(' 10: messages_history.pop(0) messages_history.append(message) class SharedDevice: """ Contains information about a single shared device on the remote server. The following attributes are available: * name : An unicode string containing the name of the shared device * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 # They are used to identify the type of shared resource from the results from the NetrShareEnum in Server Service RPC DISK_TREE = 0x00 PRINT_QUEUE = 0x01 COMM_DEVICE = 0x02 IPC = 0x03 def __init__(self, type, name, comments): self._type = type self.name = name #: An unicode string containing the name of the shared device self.comments = comments #: An unicode string containing the user description of the shared device @property def type(self): """ Returns one of the following integral constants. - SharedDevice.DISK_TREE - SharedDevice.PRINT_QUEUE - SharedDevice.COMM_DEVICE - SharedDevice.IPC """ return self._type & 0xFFFF @property def isSpecial(self): """ Returns True if this shared device is a special share reserved for interprocess communication (IPC$) or remote administration of the server (ADMIN$). Can also refer to administrative shares such as C$, D$, E$, and so forth """ return bool(self._type & 0x80000000) @property def isTemporary(self): """ Returns True if this is a temporary share that is not persisted for creation each time the file server initializes. """ return bool(self._type & 0x40000000) def __unicode__(self): return 'Shared device: %s (type:0x%02x comments:%s)' % (self.name, self.type, self.comments ) class SharedFile: """ Contain information about a file/folder entry that is shared on the shared device. As an application developer, you should not need to instantiate a *SharedFile* instance directly in your application. These *SharedFile* instances are usually returned via a call to *listPath* method in :doc:`smb.SMBProtocol.SMBProtocolFactory`. If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). The following attributes are available: * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server * file_size : File size in number of bytes * alloc_size : Total number of bytes allocated to store this file * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): """A convenience property to return True if this file resource is a directory on the remote server""" return bool(self.file_attributes & ATTR_DIRECTORY) @property def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) @property def isNormal(self): """ A convenient property to return True if this is a normal file. Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption. """ return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) def __unicode__(self): return 'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory ) class _PendingRequest: def __init__(self, mid, expiry_time, callback, errback, **kwargs): self.mid = mid self.expiry_time = expiry_time self.callback = callback self.errback = errback self.kwargs = kwargs ================================================ FILE: python3/smb/ntlm.py ================================================ import types, hmac, binascii, struct, random, string from .utils.rc4 import RC4_encrypt from .utils.pyDes import des try: import hashlib hashlib.new('md4') def MD4(): return hashlib.new('md4') except ( ImportError, ValueError ): from .utils.md4 import MD4 try: import hashlib def MD5(s): return hashlib.md5(s) except ImportError: import md5 def MD5(s): return md5.new(s) ################ # NTLMv2 Methods ################ # The following constants are defined in accordance to [MS-NLMP]: 2.2.2.5 NTLM_NegotiateUnicode = 0x00000001 NTLM_NegotiateOEM = 0x00000002 NTLM_RequestTarget = 0x00000004 NTLM_Unknown9 = 0x00000008 NTLM_NegotiateSign = 0x00000010 NTLM_NegotiateSeal = 0x00000020 NTLM_NegotiateDatagram = 0x00000040 NTLM_NegotiateLanManagerKey = 0x00000080 NTLM_Unknown8 = 0x00000100 NTLM_NegotiateNTLM = 0x00000200 NTLM_NegotiateNTOnly = 0x00000400 NTLM_Anonymous = 0x00000800 NTLM_NegotiateOemDomainSupplied = 0x00001000 NTLM_NegotiateOemWorkstationSupplied = 0x00002000 NTLM_Unknown6 = 0x00004000 NTLM_NegotiateAlwaysSign = 0x00008000 NTLM_TargetTypeDomain = 0x00010000 NTLM_TargetTypeServer = 0x00020000 NTLM_TargetTypeShare = 0x00040000 NTLM_NegotiateExtendedSecurity = 0x00080000 NTLM_NegotiateIdentify = 0x00100000 NTLM_Unknown5 = 0x00200000 NTLM_RequestNonNTSessionKey = 0x00400000 NTLM_NegotiateTargetInfo = 0x00800000 NTLM_Unknown4 = 0x01000000 NTLM_NegotiateVersion = 0x02000000 NTLM_Unknown3 = 0x04000000 NTLM_Unknown2 = 0x08000000 NTLM_Unknown1 = 0x10000000 NTLM_Negotiate128 = 0x20000000 NTLM_NegotiateKeyExchange = 0x40000000 NTLM_Negotiate56 = 0x80000000 NTLM_FLAGS = NTLM_NegotiateUnicode | \ NTLM_RequestTarget | \ NTLM_NegotiateSign | \ NTLM_NegotiateNTLM | \ NTLM_NegotiateAlwaysSign | \ NTLM_NegotiateExtendedSecurity | \ NTLM_NegotiateTargetInfo | \ NTLM_NegotiateVersion | \ NTLM_Negotiate128 | \ NTLM_NegotiateKeyExchange def generateNegotiateMessage(): """ References: =========== - [MS-NLMP]: 2.2.1.1 """ s = struct.pack('<8sII8s8s8s', b'NTLMSSP\0', 0x01, NTLM_FLAGS, b'\0' * 8, # Domain b'\0' * 8, # Workstation b'\x06\x00\x72\x17\x00\x00\x00\x0F') # Version [MS-NLMP]: 2.2.2.10 return s def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, request_session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): """ References: =========== - [MS-NLMP]: 2.2.1.3 """ FORMAT = '<8sIHHIHHIHHIHHIHHIHHII' FORMAT_SIZE = struct.calcsize(FORMAT) # [MS-NLMP]: 3.1.5.1.2 # http://grutz.jingojango.net/exploits/davenport-ntlm.html session_key = session_signing_key = request_session_key if challenge_flags & NTLM_NegotiateKeyExchange: session_signing_key = "".join([ random.choice(string.digits+string.ascii_letters) for _ in range(16) ]).encode('ascii') session_key = RC4_encrypt(request_session_key, session_signing_key) lm_response_length = len(lm_response) lm_response_offset = FORMAT_SIZE nt_response_length = len(nt_response) nt_response_offset = lm_response_offset + lm_response_length domain_unicode = domain.encode('UTF-16LE') domain_length = len(domain_unicode) domain_offset = nt_response_offset + nt_response_length padding = b'' if domain_offset % 2 != 0: padding = b'\0' domain_offset += 1 user_unicode = user.encode('UTF-16LE') user_length = len(user_unicode) user_offset = domain_offset + domain_length workstation_unicode = workstation.encode('UTF-16LE') workstation_length = len(workstation_unicode) workstation_offset = user_offset + user_length session_key_length = len(session_key) session_key_offset = workstation_offset + workstation_length auth_flags = challenge_flags auth_flags &= ~NTLM_NegotiateVersion s = struct.pack(FORMAT, b'NTLMSSP\0', 0x03, lm_response_length, lm_response_length, lm_response_offset, nt_response_length, nt_response_length, nt_response_offset, domain_length, domain_length, domain_offset, user_length, user_length, user_offset, workstation_length, workstation_length, workstation_offset, session_key_length, session_key_length, session_key_offset, auth_flags) return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key, session_signing_key def decodeChallengeMessage(ntlm_data): """ References: =========== - [MS-NLMP]: 2.2.1.2 - [MS-NLMP]: 2.2.2.1 (AV_PAIR) """ FORMAT = '<8sIHHII8s8sHHI' FORMAT_SIZE = struct.calcsize(FORMAT) signature, message_type, \ targetname_len, targetname_maxlen, targetname_offset, \ flags, challenge, _, \ targetinfo_len, targetinfo_maxlen, targetinfo_offset, \ = struct.unpack(FORMAT, bytes(ntlm_data[:FORMAT_SIZE])) assert signature == b'NTLMSSP\0' assert message_type == 0x02 return challenge, flags, bytes(ntlm_data[targetinfo_offset:targetinfo_offset+targetinfo_len]) def generateChallengeResponseV2(password, user, server_challenge, server_info, domain = '', client_challenge = None): client_timestamp = b'\0' * 8 if not client_challenge: client_challenge = bytes([ random.getrandbits(8) for i in range(0, 8) ]) assert len(client_challenge) == 8 d = MD4() d.update(password.encode('UTF-16LE')) ntlm_hash = d.digest() # The NT password hash response_key = hmac.new(ntlm_hash, (user.upper() + domain).encode('UTF-16LE'), 'md5').digest() # The NTLMv2 password hash. In [MS-NLMP], this is the result of NTOWFv2 and LMOWFv2 functions temp = b'\x01\x01' + b'\0'*6 + client_timestamp + client_challenge + b'\0'*4 + server_info ntproofstr = hmac.new(response_key, server_challenge + temp, 'md5').digest() nt_challenge_response = ntproofstr + temp lm_challenge_response = hmac.new(response_key, server_challenge + client_challenge, 'md5').digest() + client_challenge session_key = hmac.new(response_key, ntproofstr, 'md5').digest() return nt_challenge_response, lm_challenge_response, session_key ################ # NTLMv1 Methods ################ def expandDesKey(key): """Expand the key from a 7-byte password key into a 8-byte DES key""" s = [ ((key[0] >> 1) & 0x7f) << 1, ((key[0] & 0x01) << 6 | ((key[1] >> 2) & 0x3f)) << 1, ((key[1] & 0x03) << 5 | ((key[2] >> 3) & 0x1f)) << 1, ((key[2] & 0x07) << 4 | ((key[3] >> 4) & 0x0f)) << 1, ((key[3] & 0x0f) << 3 | ((key[4] >> 5) & 0x07)) << 1, ((key[4] & 0x1f) << 2 | ((key[5] >> 6) & 0x03)) << 1, ((key[5] & 0x3f) << 1 | ((key[6] >> 7) & 0x01)) << 1, (key[6] & 0x7f) << 1 ] return bytes(s) def DESL(K, D): """ References: =========== - http://ubiqx.org/cifs/SMB.html (2.8.3.4) - [MS-NLMP]: Section 6 """ d1 = des(expandDesKey(K[0:7])) d2 = des(expandDesKey(K[7:14])) d3 = des(expandDesKey(K[14:16] + b'\0' * 5)) return d1.encrypt(D) + d2.encrypt(D) + d3.encrypt(D) def generateChallengeResponseV1(password, server_challenge, has_extended_security = False, client_challenge = None): """ Generate a NTLMv1 response @param password: User password string @param server_challange: A 8-byte challenge string sent from the server @param has_extended_security: A boolean value indicating whether NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is enabled in the NTLM negFlag @param client_challenge: A 8-byte string representing client challenge. If None, it will be generated randomly if needed by the response generation @return: a tuple of ( NT challenge response string, LM challenge response string ) References: =========== - http://ubiqx.org/cifs/SMB.html (2.8.3.3 and 2.8.3.4) - [MS-NLMP]: 3.3.1 """ _password = bytes((password.upper() + '\0' * 14)[:14], 'ascii') d1 = des(expandDesKey(_password[:7])) d2 = des(expandDesKey(_password[7:])) lm_response_key = d1.encrypt(b"KGS!@#$%") + d2.encrypt(b"KGS!@#$%") # LM password hash. In [MS-NLMP], this is the result of LMOWFv1 function d = MD4() d.update(password.encode('UTF-16LE')) nt_response_key = d.digest() # In [MS-NLMP], this is the result of NTOWFv1 function if has_extended_security: if not client_challenge: client_challenge = bytes([ random.getrandbits(8) for i in range(0, 8) ]) assert len(client_challenge) == 8 lm_challenge_response = client_challenge + b'\0'*16 nt_challenge_response = DESL(nt_response_key, MD5(server_challenge + client_challenge).digest()[0:8]) else: nt_challenge_response = DESL(nt_response_key, server_challenge) # The result after DESL is the NT response lm_challenge_response = DESL(lm_response_key, server_challenge) # The result after DESL is the LM response d = MD4() d.update(nt_response_key) session_key = d.digest() return nt_challenge_response, lm_challenge_response, session_key ================================================ FILE: python3/smb/security_descriptors.py ================================================ """ This module implements security descriptors, and the partial structures used in them, as specified in [MS-DTYP]. """ import struct # Security descriptor control flags # [MS-DTYP]: 2.4.6 SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001 SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002 SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004 SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008 SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010 SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020 SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040 SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080 SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100 SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200 SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400 SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800 SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000 SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000 SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000 SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000 # ACE types # [MS-DTYP]: 2.4.4.1 ACE_TYPE_ACCESS_ALLOWED = 0x00 ACE_TYPE_ACCESS_DENIED = 0x01 ACE_TYPE_SYSTEM_AUDIT = 0x02 ACE_TYPE_SYSTEM_ALARM = 0x03 ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04 ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05 ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06 ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07 ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08 ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09 ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10 ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11 ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12 ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13 # ACE flags # [MS-DTYP]: 2.4.4.1 ACE_FLAG_OBJECT_INHERIT = 0x01 ACE_FLAG_CONTAINER_INHERIT = 0x02 ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04 ACE_FLAG_INHERIT_ONLY = 0x08 ACE_FLAG_INHERITED = 0x10 ACE_FLAG_SUCCESSFUL_ACCESS = 0x40 ACE_FLAG_FAILED_ACCESS = 0x80 # Pre-defined well-known SIDs # [MS-DTYP]: 2.4.2.4 SID_NULL = "S-1-0-0" SID_EVERYONE = "S-1-1-0" SID_LOCAL = "S-1-2-0" SID_CONSOLE_LOGON = "S-1-2-1" SID_CREATOR_OWNER = "S-1-3-0" SID_CREATOR_GROUP = "S-1-3-1" SID_OWNER_SERVER = "S-1-3-2" SID_GROUP_SERVER = "S-1-3-3" SID_OWNER_RIGHTS = "S-1-3-4" SID_NT_AUTHORITY = "S-1-5" SID_DIALUP = "S-1-5-1" SID_NETWORK = "S-1-5-2" SID_BATCH = "S-1-5-3" SID_INTERACTIVE = "S-1-5-4" SID_SERVICE = "S-1-5-6" SID_ANONYMOUS = "S-1-5-7" SID_PROXY = "S-1-5-8" SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9" SID_PRINCIPAL_SELF = "S-1-5-10" SID_AUTHENTICATED_USERS = "S-1-5-11" SID_RESTRICTED_CODE = "S-1-5-12" SID_TERMINAL_SERVER_USER = "S-1-5-13" SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14" SID_THIS_ORGANIZATION = "S-1-5-15" SID_IUSR = "S-1-5-17" SID_LOCAL_SYSTEM = "S-1-5-18" SID_LOCAL_SERVICE = "S-1-5-19" SID_NETWORK_SERVICE = "S-1-5-20" SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496" SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497" SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544" SID_BUILTIN_USERS = "S-1-5-32-545" SID_BUILTIN_GUESTS = "S-1-5-32-546" SID_POWER_USERS = "S-1-5-32-547" SID_ACCOUNT_OPERATORS = "S-1-5-32-548" SID_SERVER_OPERATORS = "S-1-5-32-549" SID_PRINTER_OPERATORS = "S-1-5-32-550" SID_BACKUP_OPERATORS = "S-1-5-32-551" SID_REPLICATOR = "S-1-5-32-552" SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554" SID_REMOTE_DESKTOP = "S-1-5-32-555" SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556" SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557" SID_PERFMON_USERS = "S-1-5-32-558" SID_PERFLOG_USERS = "S-1-5-32-559" SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560" SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561" SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562" SID_IIS_IUSRS = "S-1-5-32-568" SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569" SID_EVENT_LOG_READERS = "S-1-5-32-573" SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574" SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575" SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576" SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577" SID_HYPER_V_ADMINS = "S-1-5-32-578" SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579" SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580" SID_WRITE_RESTRICTED_CODE = "S-1-5-33" SID_NTLM_AUTHENTICATION = "S-1-5-64-10" SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14" SID_DIGEST_AUTHENTICATION = "S-1-5-64-21" SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1" SID_NT_SERVICE = "S-1-5-80" SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0" SID_LOCAL_ACCOUNT = "S-1-5-113" SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114" SID_OTHER_ORGANIZATION = "S-1-5-1000" SID_ALL_APP_PACKAGES = "S-1-15-2-1" SID_ML_UNTRUSTED = "S-1-16-0" SID_ML_LOW = "S-1-16-4096" SID_ML_MEDIUM = "S-1-16-8192" SID_ML_MEDIUM_PLUS = "S-1-16-8448" SID_ML_HIGH = "S-1-16-12288" SID_ML_SYSTEM = "S-1-16-16384" SID_ML_PROTECTED_PROCESS = "S-1-16-20480" SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1" SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2" SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3" SID_KEY_TRUST_IDENTITY = "S-1-18-4" SID_KEY_PROPERTY_MFA = "S-1-18-5" SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6" class SID(object): """ A Windows security identifier. Represents a single principal, such a user or a group, as a sequence of numbers consisting of the revision, identifier authority, and a variable-length list of subauthorities. See [MS-DTYP]: 2.4.2 """ def __init__(self, revision, identifier_authority, subauthorities): #: Revision, should always be 1. self.revision = revision #: An integer representing the identifier authority. self.identifier_authority = identifier_authority #: A list of integers representing all subauthorities. self.subauthorities = subauthorities def __str__(self): """ String representation, as specified in [MS-DTYP]: 2.4.2.1 """ if self.identifier_authority >= 2**32: id_auth = '%#x' % (self.identifier_authority,) else: id_auth = self.identifier_authority auths = [self.revision, id_auth] + self.subauthorities return 'S-' + '-'.join(str(subauth) for subauth in auths) def __repr__(self): return 'SID(%r)' % (str(self),) @classmethod def from_bytes(cls, data, return_tail=False): revision, subauth_count = struct.unpack('Q', b'\x00\x00' + data[2:8])[0] subauth_data = data[8:] subauthorities = [struct.unpack('= size body = data[header_size:size] additional_data = {} # In all ACE types, the mask immediately follows the header. mask = struct.unpack('= size for i in range(count): ace_size = struct.unpack(''), os.linesep )) b.write('Status: 0x%08X %s' % ( self.status, os.linesep )) b.write('Flags: 0x%02X %s' % ( self.flags, os.linesep )) b.write('PID: %d %s' % ( self.pid, os.linesep )) b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, str(binascii.hexlify(self.data)), os.linesep )) return b.getvalue() def reset(self): self.raw_data = b'' self.command = 0 self.status = 0 self.flags = 0 self.next_command_offset = 0 self.mid = 0 self.session_id = 0 self.signature = b'\0'*16 self.payload = None self.data = b'' # For async SMB2 message self.async_id = 0 # For sync SMB2 message self.pid = 0 self.tid = 0 # Not used in this class. Maintained for compatibility with SMBMessage class self.flags2 = 0 self.uid = 0 self.security = 0 self.parameters_data = b'' def encode(self): """ Encode this SMB2 message into a series of bytes suitable to be embedded with a NetBIOS session message. AssertionError will be raised if this SMB message has not been initialized with a Payload instance @return: a string containing the encoded SMB2 message """ assert self.payload self.pid = os.getpid() self.payload.prepare(self) headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, b'\xFESMB', self.HEADER_SIZE, 0, self.status, self.command, 0, self.flags) + \ struct.pack(self.SYNC_HEADER_STRUCT_FORMAT, self.next_command_offset, self.mid, self.pid, self.tid, self.session_id, self.signature) return headers_data + self.data def decode(self, buf): """ Decodes the SMB message in buf. All fields of the SMB2Message object will be reset to default values before decoding. On errors, do not assume that the fields will be reinstated back to what they are before this method is invoked. References ========== - [MS-SMB2]: 2.2.1 @param buf: data containing one complete SMB2 message @type buf: string @return: a positive integer indicating the number of bytes used in buf to decode this SMB message @raise ProtocolError: raised when decoding fails """ buf_len = len(buf) if buf_len < 64: # All SMB2 headers must be at least 64 bytes. [MS-SMB2]: 2.2.1.1, 2.2.1.2 raise ProtocolError('Not enough data to decode SMB2 header', buf) self.reset() protocol, struct_size, self.credit_charge, self.status, \ self.command, self.credit_re, self.flags = struct.unpack(self.HEADER_STRUCT_FORMAT, buf[:self.HEADER_STRUCT_SIZE]) if protocol != b'\xFESMB': raise ProtocolError('Invalid 4-byte SMB2 protocol field', buf) if struct_size != self.HEADER_SIZE: raise ProtocolError('Invalid SMB2 header structure size') if self.isAsync: if buf_len < self.HEADER_STRUCT_SIZE+self.ASYNC_HEADER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB2 header', buf) self.next_command_offset, self.mid, self.async_id, self.session_id, \ self.signature = struct.unpack(self.ASYNC_HEADER_STRUCT_FORMAT, buf[self.HEADER_STRUCT_SIZE:self.HEADER_STRUCT_SIZE+self.ASYNC_HEADER_STRUCT_SIZE]) else: if buf_len < self.HEADER_STRUCT_SIZE+self.SYNC_HEADER_STRUCT_SIZE: raise ProtocolError('Not enough data to decode SMB2 header', buf) self.next_command_offset, self.mid, self.pid, self.tid, self.session_id, \ self.signature = struct.unpack(self.SYNC_HEADER_STRUCT_FORMAT, buf[self.HEADER_STRUCT_SIZE:self.HEADER_STRUCT_SIZE+self.SYNC_HEADER_STRUCT_SIZE]) if self.next_command_offset > 0: self.raw_data = buf[:self.next_command_offset] self.data = buf[self.HEADER_SIZE:self.next_command_offset] else: self.raw_data = buf self.data = buf[self.HEADER_SIZE:] self._decodeCommand() if self.payload: self.payload.decode(self) return len(self.raw_data) def _decodeCommand(self): if self.command == SMB2_COM_READ: self.payload = SMB2ReadResponse() elif self.command == SMB2_COM_WRITE: self.payload = SMB2WriteResponse() elif self.command == SMB2_COM_QUERY_DIRECTORY: self.payload = SMB2QueryDirectoryResponse() elif self.command == SMB2_COM_CREATE: self.payload = SMB2CreateResponse() elif self.command == SMB2_COM_CLOSE: self.payload = SMB2CloseResponse() elif self.command == SMB2_COM_QUERY_INFO: self.payload = SMB2QueryInfoResponse() elif self.command == SMB2_COM_SET_INFO: self.payload = SMB2SetInfoResponse() elif self.command == SMB2_COM_IOCTL: self.payload = SMB2IoctlResponse() elif self.command == SMB2_COM_TREE_CONNECT: self.payload = SMB2TreeConnectResponse() elif self.command == SMB2_COM_SESSION_SETUP: self.payload = SMB2SessionSetupResponse() elif self.command == SMB2_COM_NEGOTIATE: self.payload = SMB2NegotiateResponse() elif self.command == SMB2_COM_ECHO: self.payload = SMB2EchoResponse() @property def isAsync(self): return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): return bool(self.flags & SMB2_FLAGS_SERVER_TO_REDIR) class Structure: def initMessage(self, message): pass def prepare(self, message): raise NotImplementedError def decode(self, message): raise NotImplementedError class SMB2NegotiateResponse(Structure): """ Contains information on the SMB2_NEGOTIATE response from server After calling the decode method, each instance will contain the following attributes, - security_mode (integer) - dialect_revision (integer) - server_guid (string) - max_transact_size (integer) - max_read_size (integer) - max_write_size (integer) - system_time (long) - server_start_time (long) - security_blob (string) References: =========== - [MS-SMB2]: 2.2.4 """ STRUCTURE_FORMAT = " 0 # SMB2_SESSION_FLAG_IS_GUEST @property def isAnonymousSession(self): return (self.session_flags & 0x0002) > 0 # SMB2_SESSION_FLAG_IS_NULL def decode(self, message): assert message.command == SMB2_COM_SESSION_SETUP struct_size, self.session_flags, security_blob_offset, security_blob_len \ = struct.unpack(self.STRUCTURE_FORMAT, message.raw_data[SMB2Message.HEADER_SIZE:SMB2Message.HEADER_SIZE+self.STRUCTURE_SIZE]) self.security_blob = message.raw_data[security_blob_offset:security_blob_offset+security_blob_len] class SMB2TreeConnectRequest(Structure): """ References: =========== - [MS-SMB2]: 2.2.9 """ STRUCTURE_FORMAT = " 0: self.in_data = message.raw_data[input_offset:input_offset+input_len] else: self.in_data = b'' if output_len > 0: self.out_data = message.raw_data[output_offset:output_offset+output_len] else: self.out_data = b'' class SMB2CloseRequest(Structure): """ References: =========== - [MS-SMB2]: 2.2.15 """ STRUCTURE_FORMAT = "> 24, self.internal_value & 0xFFFF ) @property def hasError(self): return self.internal_value != 0 class SMBMessage: HEADER_STRUCT_FORMAT = "<4sBIBHHQxxHHHHB" HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT) log = logging.getLogger('SMB.SMBMessage') protocol = 1 def __init__(self, payload = None): self.reset() if payload: self.payload = payload self.payload.initMessage(self) def __str__(self): b = StringIO() b.write('Command: 0x%02X (%s) %s' % ( self.command, SMB_COMMAND_NAMES.get(self.command, ''), os.linesep )) b.write('Status: %s %s' % ( str(self.status), os.linesep )) b.write('Flags: 0x%02X %s' % ( self.flags, os.linesep )) b.write('Flags2: 0x%04X %s' % ( self.flags2, os.linesep )) b.write('PID: %d %s' % ( self.pid, os.linesep )) b.write('UID: %d %s' % ( self.uid, os.linesep )) b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Security: 0x%016X %s' % ( self.security, os.linesep )) b.write('Parameters: %d bytes %s%s %s' % ( len(self.parameters_data), os.linesep, str(binascii.hexlify(self.parameters_data)), os.linesep )) b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, str(binascii.hexlify(self.data)), os.linesep )) return b.getvalue() def reset(self): self.raw_data = b'' self.command = 0 self.status = SMBError() self.flags = 0 self.flags2 = 0 self.pid = 0 self.tid = 0 self.uid = 0 self.mid = 0 self.security = 0 self.parameters_data = b'' self.data = b'' self.payload = None @property def isAsync(self): return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): return bool(self.flags & SMB_FLAGS_REPLY) @property def hasExtendedSecurity(self): return bool(self.flags2 & SMB_FLAGS2_EXTENDED_SECURITY) def encode(self): """ Encode this SMB message into a series of bytes suitable to be embedded with a NetBIOS session message. AssertionError will be raised if this SMB message has not been initialized with a Payload instance @return: a string containing the encoded SMB message """ assert self.payload self.pid = os.getpid() self.payload.prepare(self) parameters_len = len(self.parameters_data) assert parameters_len % 2 == 0 headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, b'\xFFSMB', self.command, self.status.internal_value, self.flags, self.flags2, (self.pid >> 16) & 0xFFFF, self.security, self.tid, self.pid & 0xFFFF, self.uid, self.mid, int(parameters_len / 2)) return headers_data + self.parameters_data + struct.pack(' 0 and buf_len < (datalen_offset + 2 + body_len): # Not enough data in buf to decode body raise ProtocolError('Not enough data. Body decoding failed', buf) self.parameters_data = buf[offset:datalen_offset] if body_len > 0: self.data = buf[datalen_offset+2:datalen_offset+2+body_len] self.raw_data = buf self._decodePayload() return self.HEADER_STRUCT_SIZE + params_count * 2 + 2 + body_len def _decodePayload(self): if self.command == SMB_COM_READ_ANDX: self.payload = ComReadAndxResponse() elif self.command == SMB_COM_WRITE_ANDX: self.payload = ComWriteAndxResponse() elif self.command == SMB_COM_TRANSACTION: self.payload = ComTransactionResponse() elif self.command == SMB_COM_TRANSACTION2: self.payload = ComTransaction2Response() elif self.command == SMB_COM_OPEN_ANDX: self.payload = ComOpenAndxResponse() elif self.command == SMB_COM_NT_CREATE_ANDX: self.payload = ComNTCreateAndxResponse() elif self.command == SMB_COM_TREE_CONNECT_ANDX: self.payload = ComTreeConnectAndxResponse() elif self.command == SMB_COM_ECHO: self.payload = ComEchoResponse() elif self.command == SMB_COM_SESSION_SETUP_ANDX: self.payload = ComSessionSetupAndxResponse() elif self.command == SMB_COM_NEGOTIATE: self.payload = ComNegotiateResponse() if self.payload: self.payload.decode(self) class Payload: DEFAULT_ANDX_PARAM_HEADER = b'\xFF\x00\x00\x00' DEFAULT_ANDX_PARAM_SIZE = 4 def initMessage(self, message): # SMB_FLAGS2_UNICODE must always be enabled. Without this, almost all the Payload subclasses will need to be # rewritten to check for OEM/Unicode strings which will be tedious. Fortunately, almost all tested CIFS services # support SMB_FLAGS2_UNICODE by default. assert message.payload == self message.flags = SMB_FLAGS_CASE_INSENSITIVE | SMB_FLAGS_CANONICALIZED_PATHS message.flags2 = SMB_FLAGS2_UNICODE | SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_LONG_NAMES if SUPPORT_EXTENDED_SECURITY: message.flags2 |= SMB_FLAGS2_EXTENDED_SECURITY def prepare(self, message): raise NotImplementedError def decode(self, message): raise NotImplementedError class ComNegotiateRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.52.1 - [MS-SMB]: 2.2.4.5.1 """ def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_NEGOTIATE def prepare(self, message): assert message.payload == self message.parameters_data = b'' if SUPPORT_SMB2: message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS + DIALECTS2]) else: message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS]) class ComNegotiateResponse(Payload): """ Contains information on the SMB_COM_NEGOTIATE response from server After calling the decode method, each instance will contain the following attributes, - security_mode (integer) - max_mpx_count (integer) - max_number_vcs (integer) - max_buffer_size (long) - max_raw_size (long) - session_key (long) - capabilities (long) - system_time (long) - server_time_zone (integer) - challenge_length (integer) If the underlying SMB message's flag2 does not have SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - challenge (string) - domain (unicode) If the underlying SMB message's flags2 has SMB_FLAGS2_EXTENDED_SECURITY bit enabled, then the instance will have the following additional attributes, - server_guid (string) - security_blob (string) References: =========== - [MS-SMB]: 2.2.4.5.2.1 - [MS-CIFS]: 2.2.4.52.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: if data_len >= self.challenge_length: self.challenge = message.data[:self.challenge_length] s = b'' offset = self.challenge_length while offset < data_len: _s = message.data[offset:offset+2] if _s == b'\0\0': self.domain = DataFaultToleranceStrategy.data_bytes_decode(s)#.decode('UTF-16LE') break else: s += _s offset += 2 else: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (without security extensions) Challenge field', message.raw_data, message) else: if data_len < 16: raise ProtocolError('Not enough data to decode SMB_COM_NEGOTIATE (with security extensions) ServerGUID field', message.raw_data, message) self.server_guid = message.data[:16] self.security_blob = message.data[16:] @property def supportsExtendedSecurity(self): return bool(self.capabilities & CAP_EXTENDED_SECURITY) class ComSessionSetupAndxRequest__WithSecurityExtension(Payload): """ References: =========== - [MS-SMB]: 2.2.4.6.1 """ PAYLOAD_STRUCT_FORMAT = ' 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = b'' if offset % 4 != 0: padding2 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransactionResponse(Payload): """ Contains information about a SMB_COM_TRANSACTION response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.33.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComTransaction2Request(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.46.1 """ PAYLOAD_STRUCT_FORMAT = 'HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, params_bytes = b'', data_bytes = b'', setup_bytes = b'', flags = 0, timeout = 0): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) self.max_params_count = max_params_count self.max_data_count = max_data_count self.max_setup_count = max_setup_count self.flags = flags self.timeout = timeout self.params_bytes = params_bytes self.data_bytes = data_bytes self.setup_bytes = setup_bytes def initMessage(self, message): Payload.initMessage(self, message) message.command = SMB_COM_TRANSACTION2 def prepare(self, message): setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) name = b'\0\0' padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: padding0 = b'\0' offset += 1 offset += 2 # For the name field padding1 = b'' if offset % 4 != 0: padding1 = b'\0'*(4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset offset += params_bytes_len else: params_bytes_offset = 0 padding2 = b'' if offset % 4 != 0: padding2 = b'\0'*(4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.flags, self.timeout, 0x0000, # Reserved2. Must be 0x0000 params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2)) + \ self.setup_bytes message.data = padding0 + name + padding1 + self.params_bytes + padding2 + self.data_bytes class ComTransaction2Response(Payload): """ Contains information about a SMB_COM_TRANSACTION2 response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.46.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: setup_bytes_len = setup_count * 2 if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE + setup_bytes_len: raise ProtocolError('Not enough data to decode SMB_COM_TRANSACTION parameters', message.raw_data, message) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_bytes_len] else: self.setup_bytes = '' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count * 2 + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if params_bytes_len > 0: self.params_bytes = message.data[params_bytes_offset-offset:params_bytes_offset-offset+params_bytes_len] else: self.params_bytes = '' if data_bytes_len > 0: self.data_bytes = message.data[data_bytes_offset-offset:data_bytes_offset-offset+data_bytes_len] else: self.data_bytes = '' class ComCloseRequest(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.5.1 """ PAYLOAD_STRUCT_FORMAT = '> 32) # OffsetHigh field defined in [MS-SMB]: 2.2.4.3.1 message.data = b'\0' + self.data_bytes class ComWriteAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.43.2 - [MS-SMB]: 2.2.4.3.2 """ PAYLOAD_STRUCT_FORMAT = '> 32), # Note that in [MS-SMB]: 2.2.4.2.1, this field can also act as MaxCountHigh field self.remaining, # In [MS-CIFS]: 2.2.4.42.1, this field must be set to 0x0000 self.offset >> 32) message.data = b'' class ComReadAndxResponse(Payload): """ References: =========== - [MS-CIFS]: 2.2.4.42.2 - [MS-SMB]: 2.2.4.2.2 """ PAYLOAD_STRUCT_FORMAT = ' 0: params_bytes_offset = offset else: params_bytes_offset = 0 offset += params_bytes_len padding1 = b'' if offset % 4 != 0: padding1 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset else: data_bytes_offset = 0 message.parameters_data = \ struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.max_setup_count, 0x00, # Reserved1. Must be 0x00 self.total_params_count, self.total_data_count, self.max_params_count, self.max_data_count, params_bytes_len, params_bytes_offset, data_bytes_len, data_bytes_offset, int(setup_bytes_len / 2), self.function) + \ self.setup_bytes message.data = padding0 + self.params_bytes + padding1 + self.data_bytes class ComNTTransactResponse(Payload): """ Contains information about a SMB_COM_NT_TRANSACT response from the server After decoding, each instance contains the following attributes: - total_params_count (integer) - total_data_count (integer) - setup_bytes (string) - data_bytes (string) - params_bytes (string) References: =========== - [MS-CIFS]: 2.2.4.62.2 """ PAYLOAD_STRUCT_FORMAT = '<3sIIIIIIIIBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) def decode(self, message): assert message.command == SMB_COM_NT_TRANSACT if not message.status.hasError: _, self.total_params_count, self.total_data_count, \ params_count, params_offset, params_displ, \ data_count, data_offset, data_displ, setup_count = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) self.setup_bytes = message.parameters_data[self.PAYLOAD_STRUCT_SIZE:self.PAYLOAD_STRUCT_SIZE+setup_count*2] if params_count > 0: params_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.params_bytes = message.data[params_offset:params_offset+params_count] else: self.params_bytes = b'' if data_count > 0: data_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.data_bytes = message.data[data_offset:data_offset+data_count] else: self.data_bytes = b'' ================================================ FILE: python3/smb/strategy.py ================================================ class DataStrategyBase(): DATABYTES_CODEC = 'UTF-16LE' class DataFaultToleranceStrategy(): @staticmethod def data_bytes_decode(databytes): return databytes.decode(DataStrategyBase.DATABYTES_CODEC, 'ignore') class DataStrategy(): @staticmethod def data_bytes_decode(databytes): return databytes.decode(DataStrategyBase.DATABYTES_CODEC) ================================================ FILE: python3/smb/utils/U32.py ================================================ # U32.py implements 32-bit unsigned int class for Python # Version 1.0 # Copyright (C) 2001-2002 Dmitry Rozmanov # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # e-mail: dima@xenon.spb.ru # #==================================================================== C = 0x1000000000 #-------------------------------------------------------------------- def norm(n): return n & 0xFFFFFFFF #==================================================================== class U32: v = 0 #-------------------------------------------------------------------- def __init__(self, value = 0): self.v = C + norm(abs(int(value))) #-------------------------------------------------------------------- def set(self, value = 0): self.v = C + norm(abs(int(value))) #-------------------------------------------------------------------- def __repr__(self): return hex(norm(self.v)) #-------------------------------------------------------------------- def __long__(self): return int(norm(self.v)) #-------------------------------------------------------------------- def __int__(self): return int(norm(self.v)) __index__ = __int__ #-------------------------------------------------------------------- def __chr__(self): return chr(norm(self.v)) #-------------------------------------------------------------------- def __add__(self, b): r = U32() r.v = C + norm(self.v + b.v) return r #-------------------------------------------------------------------- def __sub__(self, b): r = U32() if self.v < b.v: r.v = C + norm(0x100000000 - (b.v - self.v)) else: r.v = C + norm(self.v - b.v) return r #-------------------------------------------------------------------- def __mul__(self, b): r = U32() r.v = C + norm(self.v * b.v) return r #-------------------------------------------------------------------- def __div__(self, b): r = U32() r.v = C + (norm(self.v) / norm(b.v)) return r #-------------------------------------------------------------------- def __mod__(self, b): r = U32() r.v = C + (norm(self.v) % norm(b.v)) return r #-------------------------------------------------------------------- def __neg__(self): return U32(self.v) #-------------------------------------------------------------------- def __pos__(self): return U32(self.v) #-------------------------------------------------------------------- def __abs__(self): return U32(self.v) #-------------------------------------------------------------------- def __invert__(self): r = U32() r.v = C + norm(~self.v) return r #-------------------------------------------------------------------- def __lshift__(self, b): r = U32() r.v = C + norm(self.v << b) return r #-------------------------------------------------------------------- def __rshift__(self, b): r = U32() r.v = C + (norm(self.v) >> b) return r #-------------------------------------------------------------------- def __and__(self, b): r = U32() r.v = C + norm(self.v & b.v) return r #-------------------------------------------------------------------- def __or__(self, b): r = U32() r.v = C + norm(self.v | b.v) return r #-------------------------------------------------------------------- def __xor__(self, b): r = U32() r.v = C + norm(self.v ^ b.v) return r #-------------------------------------------------------------------- def __not__(self): return U32(not norm(self.v)) #-------------------------------------------------------------------- def truth(self): return norm(self.v) #-------------------------------------------------------------------- def __cmp__(self, b): if norm(self.v) > norm(b.v): return 1 elif norm(self.v) < norm(b.v): return -1 else: return 0 #-------------------------------------------------------------------- def __bool__(self): return norm(self.v) ================================================ FILE: python3/smb/utils/__init__.py ================================================ def convertFILETIMEtoEpoch(t): return (t - 116444736000000000) / 10000000.0; ================================================ FILE: python3/smb/utils/md4.py ================================================ # md4.py implements md4 hash class for Python # Version 1.0 # Copyright (C) 2001-2002 Dmitry Rozmanov # # based on md4.c from "the Python Cryptography Toolkit, version 1.0.0 # Copyright (C) 1995, A.M. Kuchling" # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # e-mail: dima@xenon.spb.ru # #==================================================================== #==================================================================== from .U32 import U32 #-------------------------------------------------------------------- class MD4: A = None B = None C = None D = None count, len1, len2 = None, None, None buf = [] #----------------------------------------------------- def __init__(self): self.A = U32(0x67452301) self.B = U32(0xefcdab89) self.C = U32(0x98badcfe) self.D = U32(0x10325476) self.count, self.len1, self.len2 = U32(0), U32(0), U32(0) self.buf = [0x00] * 64 #----------------------------------------------------- def __repr__(self): r = 'A = %s, \nB = %s, \nC = %s, \nD = %s.\n' % (self.A.__repr__(), self.B.__repr__(), self.C.__repr__(), self.D.__repr__()) r = r + 'count = %s, \nlen1 = %s, \nlen2 = %s.\n' % (self.count.__repr__(), self.len1.__repr__(), self.len2.__repr__()) for i in range(4): for j in range(16): r = r + '%4s ' % hex(self.buf[i+j]) r = r + '\n' return r #----------------------------------------------------- def make_copy(self): dest = new() dest.len1 = self.len1 dest.len2 = self.len2 dest.A = self.A dest.B = self.B dest.C = self.C dest.D = self.D dest.count = self.count for i in range(int(self.count)): dest.buf[i] = self.buf[i] return dest #----------------------------------------------------- def update(self, str): if isinstance(str, bytes): buf = list(str) else: buf = [ord(i) for i in str] ilen = U32(len(buf)) # check if the first length is out of range # as the length is measured in bits then multiplay it by 8 if (int(self.len1 + (ilen << 3)) < int(self.len1)): self.len2 = self.len2 + U32(1) self.len1 = self.len1 + (ilen << 3) self.len2 = self.len2 + (ilen >> 29) L = U32(0) bufpos = 0 while (int(ilen) > 0): if (64 - int(self.count)) < int(ilen): L = U32(64 - int(self.count)) else: L = ilen for i in range(int(L)): self.buf[i + int(self.count)] = buf[i + bufpos] self.count = self.count + L ilen = ilen - L bufpos = bufpos + int(L) if (int(self.count) == 64): self.count = U32(0) X = [] i = 0 for j in range(16): X.append(U32(self.buf[i]) + (U32(self.buf[i+1]) << 8) + \ (U32(self.buf[i+2]) << 16) + (U32(self.buf[i+3]) << 24)) i = i + 4 A = self.A B = self.B C = self.C D = self.D A = f1(A,B,C,D, 0, 3, X) D = f1(D,A,B,C, 1, 7, X) C = f1(C,D,A,B, 2,11, X) B = f1(B,C,D,A, 3,19, X) A = f1(A,B,C,D, 4, 3, X) D = f1(D,A,B,C, 5, 7, X) C = f1(C,D,A,B, 6,11, X) B = f1(B,C,D,A, 7,19, X) A = f1(A,B,C,D, 8, 3, X) D = f1(D,A,B,C, 9, 7, X) C = f1(C,D,A,B,10,11, X) B = f1(B,C,D,A,11,19, X) A = f1(A,B,C,D,12, 3, X) D = f1(D,A,B,C,13, 7, X) C = f1(C,D,A,B,14,11, X) B = f1(B,C,D,A,15,19, X) A = f2(A,B,C,D, 0, 3, X) D = f2(D,A,B,C, 4, 5, X) C = f2(C,D,A,B, 8, 9, X) B = f2(B,C,D,A,12,13, X) A = f2(A,B,C,D, 1, 3, X) D = f2(D,A,B,C, 5, 5, X) C = f2(C,D,A,B, 9, 9, X) B = f2(B,C,D,A,13,13, X) A = f2(A,B,C,D, 2, 3, X) D = f2(D,A,B,C, 6, 5, X) C = f2(C,D,A,B,10, 9, X) B = f2(B,C,D,A,14,13, X) A = f2(A,B,C,D, 3, 3, X) D = f2(D,A,B,C, 7, 5, X) C = f2(C,D,A,B,11, 9, X) B = f2(B,C,D,A,15,13, X) A = f3(A,B,C,D, 0, 3, X) D = f3(D,A,B,C, 8, 9, X) C = f3(C,D,A,B, 4,11, X) B = f3(B,C,D,A,12,15, X) A = f3(A,B,C,D, 2, 3, X) D = f3(D,A,B,C,10, 9, X) C = f3(C,D,A,B, 6,11, X) B = f3(B,C,D,A,14,15, X) A = f3(A,B,C,D, 1, 3, X) D = f3(D,A,B,C, 9, 9, X) C = f3(C,D,A,B, 5,11, X) B = f3(B,C,D,A,13,15, X) A = f3(A,B,C,D, 3, 3, X) D = f3(D,A,B,C,11, 9, X) C = f3(C,D,A,B, 7,11, X) B = f3(B,C,D,A,15,15, X) self.A = self.A + A self.B = self.B + B self.C = self.C + C self.D = self.D + D #----------------------------------------------------- def digest(self): res = [0x00] * 16 s = [0x00] * 8 padding = [0x00] * 64 padding[0] = 0x80 padlen, oldlen1, oldlen2 = U32(0), U32(0), U32(0) temp = self.make_copy() oldlen1 = temp.len1 oldlen2 = temp.len2 if (56 <= int(self.count)): padlen = U32(56 - int(self.count) + 64) else: padlen = U32(56 - int(self.count)) temp.update(bytes(padding[:int(padlen)])) s[0]= (oldlen1) & U32(0xFF) s[1]=((oldlen1) >> 8) & U32(0xFF) s[2]=((oldlen1) >> 16) & U32(0xFF) s[3]=((oldlen1) >> 24) & U32(0xFF) s[4]= (oldlen2) & U32(0xFF) s[5]=((oldlen2) >> 8) & U32(0xFF) s[6]=((oldlen2) >> 16) & U32(0xFF) s[7]=((oldlen2) >> 24) & U32(0xFF) temp.update(bytes(s)) res[ 0]= temp.A & U32(0xFF) res[ 1]=(temp.A >> 8) & U32(0xFF) res[ 2]=(temp.A >> 16) & U32(0xFF) res[ 3]=(temp.A >> 24) & U32(0xFF) res[ 4]= temp.B & U32(0xFF) res[ 5]=(temp.B >> 8) & U32(0xFF) res[ 6]=(temp.B >> 16) & U32(0xFF) res[ 7]=(temp.B >> 24) & U32(0xFF) res[ 8]= temp.C & U32(0xFF) res[ 9]=(temp.C >> 8) & U32(0xFF) res[10]=(temp.C >> 16) & U32(0xFF) res[11]=(temp.C >> 24) & U32(0xFF) res[12]= temp.D & U32(0xFF) res[13]=(temp.D >> 8) & U32(0xFF) res[14]=(temp.D >> 16) & U32(0xFF) res[15]=(temp.D >> 24) & U32(0xFF) return bytes(res) #==================================================================== # helpers def F(x, y, z): return (((x) & (y)) | ((~x) & (z))) def G(x, y, z): return (((x) & (y)) | ((x) & (z)) | ((y) & (z))) def H(x, y, z): return ((x) ^ (y) ^ (z)) def ROL(x, n): return (((x) << n) | ((x) >> (32-n))) def f1(a, b, c, d, k, s, X): return ROL(a + F(b, c, d) + X[k], s) def f2(a, b, c, d, k, s, X): return ROL(a + G(b, c, d) + X[k] + U32(0x5a827999), s) def f3(a, b, c, d, k, s, X): return ROL(a + H(b, c, d) + X[k] + U32(0x6ed9eba1), s) #-------------------------------------------------------------------- # To be able to use md4.new() instead of md4.MD4() new = MD4 ================================================ FILE: python3/smb/utils/pyDes.py ================================================ ############################################################################# # Documentation # ############################################################################# # Author: Todd Whiteman # Date: 16th March, 2009 # Verion: 2.0.0 # License: Public Domain - free to do as you wish # Homepage: http://twhiteman.netfirms.com/des.html # # This is a pure python implementation of the DES encryption algorithm. # It's pure python to avoid portability issues, since most DES # implementations are programmed in C (for performance reasons). # # Triple DES class is also implemented, utilising the DES base. Triple DES # is either DES-EDE3 with a 24 byte key, or DES-EDE2 with a 16 byte key. # # See the README.txt that should come with this python module for the # implementation methods used. # # Thanks to: # * David Broadwell for ideas, comments and suggestions. # * Mario Wolff for pointing out and debugging some triple des CBC errors. # * Santiago Palladino for providing the PKCS5 padding technique. # * Shaya for correcting the PAD_PKCS5 triple des CBC errors. # """A pure python implementation of the DES and TRIPLE DES encryption algorithms. Class initialization -------------------- pyDes.des(key, [mode], [IV], [pad], [padmode]) pyDes.triple_des(key, [mode], [IV], [pad], [padmode]) key -> Bytes containing the encryption key. 8 bytes for DES, 16 or 24 bytes for Triple DES mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Length must be 8 bytes. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. I recommend to use PAD_PKCS5 padding, as then you never need to worry about any padding issues, as the padding can be removed unambiguously upon decrypting data that was encrypted using PAD_PKCS5 padmode. Common methods -------------- encrypt(data, [pad], [padmode]) decrypt(data, [pad], [padmode]) data -> Bytes to be encrypted/decrypted pad -> Optional argument. Only when using padmode of PAD_NORMAL. For encryption, adds this characters to the end of the data block when data is not a multiple of 8 bytes. For decryption, will remove the trailing characters that match this pad character from the last 8 bytes of the unencrypted data block. padmode -> Optional argument, set the padding mode, must be one of PAD_NORMAL or PAD_PKCS5). Defaults to PAD_NORMAL. Example ------- from pyDes import * data = "Please encrypt my data" k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) # For Python3, you'll need to use bytes, i.e.: # data = b"Please encrypt my data" # k = des(b"DESCRYPT", CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) assert k.decrypt(d, padmode=PAD_PKCS5) == data See the module source (pyDes.py) for more examples of use. You can also run the pyDes.py file without and arguments to see a simple test. Note: This code was not written for high-end systems needing a fast implementation, but rather a handy portable solution with small usage. """ import sys # _pythonMajorVersion is used to handle Python2 and Python3 differences. _pythonMajorVersion = sys.version_info[0] # Modes of crypting / cyphering ECB = 0 CBC = 1 # Modes of padding PAD_NORMAL = 1 PAD_PKCS5 = 2 # PAD_PKCS5: is a method that will unambiguously remove all padding # characters after decryption, when originally encrypted with # this padding mode. # For a good description of the PKCS5 padding technique, see: # http://www.faqs.org/rfcs/rfc1423.html # The base class shared by des and triple des. class _baseDes(object): def __init__(self, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): if IV: IV = self._guardAgainstUnicode(IV) if pad: pad = self._guardAgainstUnicode(pad) self.block_size = 8 # Sanity checking of arguments. if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if IV and len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") # Set the passed in variables self._mode = mode self._iv = IV self._padding = pad self._padmode = padmode def getKey(self): """getKey() -> bytes""" return self.__key def setKey(self, key): """Will set the crypting key for this object.""" key = self._guardAgainstUnicode(key) self.__key = key def getMode(self): """getMode() -> pyDes.ECB or pyDes.CBC""" return self._mode def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" self._mode = mode def getPadding(self): """getPadding() -> bytes of length 1. Padding character.""" return self._padding def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" if pad is not None: pad = self._guardAgainstUnicode(pad) self._padding = pad def getPadMode(self): """getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" return self._padmode def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" self._padmode = mode def getIV(self): """getIV() -> bytes""" return self._iv def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" if not IV or len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") IV = self._guardAgainstUnicode(IV) self._iv = IV def _padData(self, data, pad, padmode): # Pad data depending on the mode if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode == PAD_NORMAL: if len(data) % self.block_size == 0: # No padding required. return data if not pad: # Get the default padding. pad = self.getPadding() if not pad: raise ValueError("Data must be a multiple of " + str(self.block_size) + " bytes in length. Use padmode=PAD_PKCS5 or set the pad character.") data += (self.block_size - (len(data) % self.block_size)) * pad elif padmode == PAD_PKCS5: pad_len = 8 - (len(data) % self.block_size) if _pythonMajorVersion < 3: data += pad_len * chr(pad_len) else: data += bytes([pad_len] * pad_len) return data def _unpadData(self, data, pad, padmode): # Unpad data depending on the mode. if not data: return data if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if padmode == PAD_NORMAL: if not pad: # Get the default padding. pad = self.getPadding() if pad: data = data[:-self.block_size] + \ data[-self.block_size:].rstrip(pad) elif padmode == PAD_PKCS5: if _pythonMajorVersion < 3: pad_len = ord(data[-1]) else: pad_len = data[-1] data = data[:-pad_len] return data def _guardAgainstUnicode(self, data): # Only accept byte strings or ascii unicode values, otherwise # there is no way to correctly decode the data into bytes. if _pythonMajorVersion < 3: if isinstance(data, str): raise ValueError("pyDes can only work with bytes, not Unicode strings.") else: if isinstance(data, str): # Only accept ascii unicode values. try: return data.encode('ascii') except UnicodeEncodeError: pass raise ValueError("pyDes can only work with encoded strings, not Unicode.") return data ############################################################################# # DES # ############################################################################# class des(_baseDes): """DES encryption/decrytpion class Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key,[mode], [IV]) key -> Bytes containing the encryption key, must be exactly 8 bytes mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ # Permutation and translation tables for DES __pc1 = [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 ] # number left rotations of pc1 __left_rotations = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] # permuted choice key (table 2) __pc2 = [ 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 ] # initial permutation IP __ip = [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 ] # Expansion table for turning 32 bit blocks into 48 bits __expansion_table = [ 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0 ] # The (in)famous S-boxes __sbox = [ # S1 [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], # S2 [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], # S3 [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], # S4 [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], # S5 [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], # S6 [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], # S7 [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], # S8 [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] # 32-bit permutation function P used on the output of the S-boxes __p = [ 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23,13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24 ] # final permutation IP^-1 __fp = [ 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24 ] # Type of crypting being done ENCRYPT = 0x00 DECRYPT = 0x01 # Initialisation def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): # Sanity checking of arguments. if len(key) != 8: raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.") _baseDes.__init__(self, mode, IV, pad, padmode) self.key_size = 8 self.L = [] self.R = [] self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16) self.final = [] self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Must be 8 bytes.""" _baseDes.setKey(self, key) self.__create_sub_keys() def __String_to_BitList(self, data): """Turn the string data, into a list of bits (1, 0)'s""" if _pythonMajorVersion < 3: # Turn the strings into integers. Python 3 uses a bytes # class, which already has this behaviour. data = [ord(c) for c in data] l = len(data) * 8 result = [0] * l pos = 0 for ch in data: i = 7 while i >= 0: if ch & (1 << i) != 0: result[pos] = 1 else: result[pos] = 0 pos += 1 i -= 1 return result def __BitList_to_String(self, data): """Turn the list of bits -> data, into a string""" result = [] pos = 0 c = 0 while pos < len(data): c += data[pos] << (7 - (pos % 8)) if (pos % 8) == 7: result.append(c) c = 0 pos += 1 if _pythonMajorVersion < 3: return ''.join([ chr(c) for c in result ]) else: return bytes(result) def __permutate(self, table, block): """Permutate this block with the specified table""" return list([block[x] for x in table]) # Transform the secret key, so that it is ready for data processing # Create the 16 subkeys, K[1] - K[16] def __create_sub_keys(self): """Create the 16 subkeys K[1] to K[16] from the given key""" key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey())) i = 0 # Split into Left and Right sections self.L = key[:28] self.R = key[28:] while i < 16: j = 0 # Perform circular left shifts while j < des.__left_rotations[i]: self.L.append(self.L[0]) del self.L[0] self.R.append(self.R[0]) del self.R[0] j += 1 # Create one of the 16 subkeys through pc2 permutation self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R) i += 1 # Main part of the encryption algorithm, the number cruncher :) def __des_crypt(self, block, crypt_type): """Crypt the block of data through DES bit-manipulation""" block = self.__permutate(des.__ip, block) self.L = block[:32] self.R = block[32:] # Encryption starts from Kn[1] through to Kn[16] if crypt_type == des.ENCRYPT: iteration = 0 iteration_adjustment = 1 # Decryption starts from Kn[16] down to Kn[1] else: iteration = 15 iteration_adjustment = -1 i = 0 while i < 16: # Make a copy of R[i-1], this will later become L[i] tempR = self.R[:] # Permutate R[i - 1] to start creating R[i] self.R = self.__permutate(des.__expansion_table, self.R) # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration])) B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]] # Optimization: Replaced below commented code with above #j = 0 #B = [] #while j < len(self.R): # self.R[j] = self.R[j] ^ self.Kn[iteration][j] # j += 1 # if j % 6 == 0: # B.append(self.R[j-6:j]) # Permutate B[1] to B[8] using the S-Boxes j = 0 Bn = [0] * 32 pos = 0 while j < 8: # Work out the offsets m = (B[j][0] << 1) + B[j][5] n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4] # Find the permutation value v = des.__sbox[j][(m << 4) + n] # Turn value into bits, add it to result: Bn Bn[pos] = (v & 8) >> 3 Bn[pos + 1] = (v & 4) >> 2 Bn[pos + 2] = (v & 2) >> 1 Bn[pos + 3] = v & 1 pos += 4 j += 1 # Permutate the concatination of B[1] to B[8] (Bn) self.R = self.__permutate(des.__p, Bn) # Xor with L[i - 1] self.R = list(map(lambda x, y: x ^ y, self.R, self.L)) # Optimization: This now replaces the below commented code #j = 0 #while j < len(self.R): # self.R[j] = self.R[j] ^ self.L[j] # j += 1 # L[i] becomes R[i - 1] self.L = tempR i += 1 iteration += iteration_adjustment # Final permutation of R[16]L[16] self.final = self.__permutate(des.__fp, self.R + self.L) return self.final # Data to be encrypted/decrypted def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.") if not self.getPadding(): raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character") else: data += (self.block_size - (len(data) % self.block_size)) * self.getPadding() # print "Len of data: %f" % (len(data) / self.block_size) if self.getMode() == CBC: if self.getIV(): iv = self.__String_to_BitList(self.getIV()) else: raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering") # Split the data into blocks, crypting each one seperately i = 0 dict = {} result = [] #cached = 0 #lines = 0 while i < len(data): # Test code for caching encryption results #lines += 1 #if dict.has_key(data[i:i+8]): #print "Cached result for: %s" % data[i:i+8] # cached += 1 # result.append(dict[data[i:i+8]]) # i += 8 # continue block = self.__String_to_BitList(data[i:i+8]) # Xor with IV if using CBC mode if self.getMode() == CBC: if crypt_type == des.ENCRYPT: block = list(map(lambda x, y: x ^ y, block, iv)) #j = 0 #while j < len(block): # block[j] = block[j] ^ iv[j] # j += 1 processed_block = self.__des_crypt(block, crypt_type) if crypt_type == des.DECRYPT: processed_block = list(map(lambda x, y: x ^ y, processed_block, iv)) #j = 0 #while j < len(processed_block): # processed_block[j] = processed_block[j] ^ iv[j] # j += 1 iv = block else: iv = processed_block else: processed_block = self.__des_crypt(block, crypt_type) # Add the resulting crypted block to our list #d = self.__BitList_to_String(processed_block) #result.append(d) result.append(self.__BitList_to_String(processed_block)) #dict[data[i:i+8]] = d i += 8 # print "Lines: %d, cached: %d" % (lines, cached) # Return the full crypted string if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self.crypt(data, des.DECRYPT) return self._unpadData(data, pad, padmode) ############################################################################# # Triple DES # ############################################################################# class triple_des(_baseDes): """Triple DES encryption/decrytpion class This algorithm uses the DES-EDE3 (when a 24 byte key is supplied) or the DES-EDE2 (when a 16 byte key is supplied) encryption methods. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key, [mode], [IV]) key -> Bytes containing the encryption key, must be either 16 or 24 bytes long mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): _baseDes.__init__(self, mode, IV, pad, padmode) self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Either 16 or 24 bytes long.""" self.key_size = 24 # Use DES-EDE3 mode if len(key) != self.key_size: if len(key) == 16: # Use DES-EDE2 mode self.key_size = 16 else: raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long") if self.getMode() == CBC: if not self.getIV(): # Use the first 8 bytes of the key self._iv = key[:self.block_size] if len(self.getIV()) != self.block_size: raise ValueError("Invalid IV, must be 8 bytes in length") self.__key1 = des(key[:8], self._mode, self._iv, self._padding, self._padmode) self.__key2 = des(key[8:16], self._mode, self._iv, self._padding, self._padmode) if self.key_size == 16: self.__key3 = self.__key1 else: self.__key3 = des(key[16:], self._mode, self._iv, self._padding, self._padmode) _baseDes.setKey(self, key) # Override setter methods to work on all 3 keys. def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" _baseDes.setMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setMode(mode) def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" _baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key.setPadding(pad) def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" _baseDes.setPadMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setPadMode(mode) def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" _baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) # Pad the data accordingly. data = self._padData(data, pad, padmode) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): block = self.__key1.crypt(data[i:i+8], ENCRYPT) block = self.__key2.crypt(block, DECRYPT) block = self.__key3.crypt(block, ENCRYPT) self.__key1.setIV(block) self.__key2.setIV(block) self.__key3.setIV(block) result.append(block) i += 8 if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) else: data = self.__key1.crypt(data, ENCRYPT) data = self.__key2.crypt(data, DECRYPT) return self.__key3.crypt(data, ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting, no pad character is required for PAD_PKCS5. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): iv = data[i:i+8] block = self.__key3.crypt(iv, DECRYPT) block = self.__key2.crypt(block, ENCRYPT) block = self.__key1.crypt(block, DECRYPT) self.__key1.setIV(iv) self.__key2.setIV(iv) self.__key3.setIV(iv) result.append(block) i += 8 if _pythonMajorVersion < 3: data = ''.join(result) else: data = bytes.fromhex('').join(result) else: data = self.__key3.crypt(data, DECRYPT) data = self.__key2.crypt(data, ENCRYPT) data = self.__key1.crypt(data, DECRYPT) return self._unpadData(data, pad, padmode) ================================================ FILE: python3/smb/utils/rc4.py ================================================ def RC4_encrypt(key, data): S = list(range(256)) j = 0 key_len = len(key) for i in list(range(256)): j = (j + S[i] + key[i % key_len]) % 256 S[i], S[j] = S[j], S[i] j = 0 y = 0 out = [] for char in data: j = (j + 1) % 256 y = (y + S[j]) % 256 S[j], S[y] = S[y], S[j] out.append(char ^ S[(S[j] + S[y]) % 256]) return bytes(out) ================================================ FILE: python3/smb/utils/sha256.py ================================================ __author__ = 'Thomas Dixon' __license__ = 'MIT' import copy, struct, sys digest_size = 32 blocksize = 1 def new(m=None): return sha256(m) class sha256(object): _k = (0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2) _h = (0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19) _output_size = 8 blocksize = 1 block_size = 64 digest_size = 32 def __init__(self, m=None): self._buffer = '' self._counter = 0 if m is not None: if type(m) is not str: raise TypeError('%s() argument 1 must be string, not %s' % (self.__class__.__name__, type(m).__name__)) self.update(m) def _rotr(self, x, y): return ((x >> y) | (x << (32-y))) & 0xFFFFFFFF def _sha256_process(self, c): w = [0]*64 w[0:15] = struct.unpack('!16L', c) for i in range(16, 64): s0 = self._rotr(w[i-15], 7) ^ self._rotr(w[i-15], 18) ^ (w[i-15] >> 3) s1 = self._rotr(w[i-2], 17) ^ self._rotr(w[i-2], 19) ^ (w[i-2] >> 10) w[i] = (w[i-16] + s0 + w[i-7] + s1) & 0xFFFFFFFF a,b,c,d,e,f,g,h = self._h for i in range(64): s0 = self._rotr(a, 2) ^ self._rotr(a, 13) ^ self._rotr(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) t2 = s0 + maj s1 = self._rotr(e, 6) ^ self._rotr(e, 11) ^ self._rotr(e, 25) ch = (e & f) ^ ((~e) & g) t1 = h + s1 + ch + self._k[i] + w[i] h = g g = f f = e e = (d + t1) & 0xFFFFFFFF d = c c = b b = a a = (t1 + t2) & 0xFFFFFFFF self._h = [(x+y) & 0xFFFFFFFF for x,y in zip(self._h, [a,b,c,d,e,f,g,h])] def update(self, m): if not m: return if type(m) is not str: raise TypeError('%s() argument 1 must be string, not %s' % (sys._getframe().f_code.co_name, type(m).__name__)) self._buffer += m self._counter += len(m) while len(self._buffer) >= 64: self._sha256_process(self._buffer[:64]) self._buffer = self._buffer[64:] def digest(self): mdi = self._counter & 0x3F length = struct.pack('!Q', self._counter<<3) if mdi < 56: padlen = 55-mdi else: padlen = 119-mdi r = self.copy() r.update('\x80'+('\x00'*padlen)+length) return ''.join([struct.pack('!L', i) for i in r._h[:self._output_size]]) def hexdigest(self): return self.digest().encode('hex') def copy(self): return copy.deepcopy(self) ================================================ FILE: python3/tests/DirectSMBConnectionTests/__init__.py ================================================ ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_auth.py ================================================ from nose2.tools.decorators import with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn, conn2, conn3 = None, None, None def teardown_func(): global conn, conn2, conn3 if conn: conn.close() if conn2: conn2.close() if conn3: conn3.close(); @with_teardown(teardown_func) def test_NTLMv1_auth_SMB1(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv1_auth_SMB1_callable_password(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], lambda: info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv2_auth_SMB1(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv1_auth_SMB2(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv2_auth_SMB2(): global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert not conn3.connect(info['server_ip'], info['server_port']) ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, time, random from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_english_directory_SMB1(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_english_directory_SMB2(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_unicode_directory_SMB1(): global conn path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_unicode_directory_SMB2(): global conn path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_echo.py ================================================ import random from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from .util import getConnectionInfo conn = None def setup_func(): global conn info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func) @with_teardown(teardown_func) def test_echo(): global conn data = bytearray('%d' % random.randint(1000, 9999), 'ascii') assert conn.echo(data) == data ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_listpath.py ================================================ # -*- coding: utf-8 -*- from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb.smb_constants import * from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( 'TestDir1', True ) in filenames # Test short English folder names assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathWithManyFiles_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames))==999 @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( 'TestDir1', True ) in filenames # Test short English folder names assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathWithManyFiles_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames))==999 @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterForDirectory_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterForDirectory_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterForFiles_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterForFiles_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterPattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterPattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterUnicodePattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterUnicodePattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_listshares.py ================================================ from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_listsnapshots.py ================================================ from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_english_file_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_english_file_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_unicode_file_SMB1(): global conn old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_unicode_file_SMB2(): global conn old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_english_directory_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_english_directory_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_unicode_directory_SMB1(): global conn old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_unicode_directory_SMB2(): global conn old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile, random, time from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) ================================================ FILE: python3/tests/DirectSMBConnectionTests/test_tqdm.py ================================================ # -*- coding: utf-8 -*- import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_tqdm_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh, show_progress=True) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_tqdm_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh, show_progress=True) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_tqdm_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_tqdm_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) ================================================ FILE: python3/tests/DirectSMBConnectionTests/util.py ================================================ import os from configparser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'direct_port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), 'is_direct_tcp': True, } return info ================================================ FILE: python3/tests/NetBIOSTests/__init__.py ================================================ ================================================ FILE: python3/tests/NetBIOSTests/test_queryname.py ================================================ from nmb.NetBIOS import NetBIOS from nose2.tools.decorators import with_teardown conn = None def teardown_func(): global conn conn.close() @with_teardown(teardown_func) def test_broadcast(): global conn conn = NetBIOS() assert conn.queryName('MICHAEL-I5PC', timeout = 10) ================================================ FILE: python3/tests/README.md ================================================ Steps to Follow to Run the Unit Tests ===================================== ## Step 1: Install system dependencies ## If you are using Ubuntu 20.04 LTS, you can install the system dependencies with the following command ``` $> apt-get install python3-dev python3-venv gcc g++ make automake autoconf ``` For other distributions, you can use their package managers and install the system dependencies (although the package names might differ slightly). ## Step 2: Setup python virtualenv ## We will create a python3 virtualenv and install the python dependencies for testing in the "venv3" folder. ``` $> cd /python3 $> virtualenv -p /usr/bin/python3 venv3 $> source venv3/bin/activate $venv3> pip install nose2 pyasn1 twisted ``` ## Step 3: Setup shared folder on your remote SMB server ## Prepare a shared folder called "smbtest" on your remote SMB server (Windows or Samba). Then, download [smbtest.zip](https://miketeo.net/files/Projects/pysmb/smbtest.zip) and unzip the contents of this zip file in the shared folder. You should also configure a user on the SMB server with read-write access to the "smbtest" folder. ## Step 4: Update connection details in connection.ini ## In the same folder where you are viewing this readme file, there should be an ini file called "connection.ini". Edit this file's connection details to match the shared folder's access information. ## Step 5: Run the unit tests in the python3 folder ## Before running the tests, the venv3 virtualenv must be activated. ``` $> cd /python3 $> source venv3/bin/activate ``` To run all the tests: ``` $venv3> nose2 -v tests ``` To selectively run some tests: ``` $venv3> nose2 -v tests.SMBConnectionTests $venv3> nose2 -v tests.SMBConnectionTests.test_rename $venv3> nose2 -v tests.SMBConnectionTests.test_rename.test_rename_english_file_SMB1 ``` For more information, please consult the [documentation for nose2](https://docs.nose2.io/). ================================================ FILE: python3/tests/SMBConnectionTests/__init__.py ================================================ ================================================ FILE: python3/tests/SMBConnectionTests/test_SMBHandler.py ================================================ # -*- coding: utf-8 -*- import os, urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, time, random from smb.SMBHandler import SMBHandler import util try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() def test_basic(): # Basic test for smb URLs director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/rfc1001.txt' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert len(s) == 158437 fh.close() def test_unicode(): # Test smb URLs with unicode paths director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/测试文件夹/垃圾文件.dat' % util.getConnectionInfo()) s = fh.read() md = MD5() md.update(s) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert len(s) == 256000 fh.close() TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def test_upload(): info = util.getConnectionInfo() info['filename'] = os.sep + 'StoreTest-%d-%d.dat' % ( time.time(), random.randint(0, 10000) ) director = urllib.request.build_opener(SMBHandler) upload_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info, data = open(TEST_FILENAME, 'rb')) retr_fh = director.open('smb://%(user)s:%(password)s@%(server_ip)s/smbtest/%(filename)s' % info) s = retr_fh.read() md = MD5() md.update(s) assert md.hexdigest() == TEST_DIGEST assert len(s) == TEST_FILESIZE ================================================ FILE: python3/tests/SMBConnectionTests/test_auth.py ================================================ from nose2.tools.decorators import with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def teardown_func(): global conn conn.close() @with_teardown(teardown_func) def test_NTLMv1_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv2_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv1_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) @with_teardown(teardown_func) def test_NTLMv2_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) ================================================ FILE: python3/tests/SMBConnectionTests/test_createdeletedirectory.py ================================================ # -*- coding: utf-8 -*- import os, time, random from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_english_directory_SMB1(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_english_directory_SMB2(): global conn path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_unicode_directory_SMB1(): global conn path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_unicode_directory_SMB2(): global conn path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) in names conn.deleteDirectory('smbtest', path) entries = conn.listPath('smbtest', os.path.dirname(path.replace('/', os.sep))) names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names ================================================ FILE: python3/tests/SMBConnectionTests/test_deletepattern.py ================================================ # -*- coding: utf-8 -*- import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_delete_without_subfolder_SMB1(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt') results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*') results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_delete_with_subfolder_SMB1(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' not in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_delete_without_subfolder_SMB2(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt') results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*') results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_delete_with_subfolder_SMB2(): global conn path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) conn.createDirectory('smbtest', path) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: conn.createDirectory('smbtest', path+"/"+p) for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) assert 'aaTest.Folder' not in filenames assert 'bbTest.Folder' in filenames assert 'aaTest.bin' not in filenames assert 'aaBest.bin' in filenames assert 'random.txt' in filenames ================================================ FILE: python3/tests/SMBConnectionTests/test_echo.py ================================================ import random from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from .util import getConnectionInfo conn = None def setup_func(): global conn info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func) @with_teardown(teardown_func) def test_echo(): global conn data = bytearray('%d' % random.randint(1000, 9999), 'ascii') assert conn.echo(data) == data ================================================ FILE: python3/tests/SMBConnectionTests/test_getattributes.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from .util import getConnectionInfo from nose2.tools.decorators import with_setup, with_teardown from smb import smb_structs conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_getAttributes_SMB2(): global conn info = conn.getAttributes('smbtest', '/Test Folder with Long Name/') assert info.isDirectory info = conn.getAttributes('smbtest', '/rfc1001.txt') assert not info.isDirectory assert info.file_size == 158437 assert info.alloc_size == 159744 info = conn.getAttributes('smbtest', u'/\u6d4b\u8bd5\u6587\u4ef6\u5939') assert info.isDirectory @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_getAttributes_SMB1(): global conn info = conn.getAttributes('smbtest', '/Test Folder with Long Name/') assert info.isDirectory info = conn.getAttributes('smbtest', '/rfc1001.txt') assert not info.isDirectory assert info.file_size == 158437 assert info.alloc_size == 159744 info = conn.getAttributes('smbtest', u'/\u6d4b\u8bd5\u6587\u4ef6\u5939') assert info.isDirectory ================================================ FILE: python3/tests/SMBConnectionTests/test_listpath.py ================================================ # -*- coding: utf-8 -*- from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb.smb_constants import * from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( 'TestDir1', True ) in filenames # Test short English folder names assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathWithManyFiles_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames))==999 @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names assert ( 'TestDir1', True ) in filenames # Test short English folder names assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') filenames = [( r.filename, r.isDirectory ) for r in results] assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathWithManyFiles_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive/') filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames))==999 @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterForDirectory_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterForDirectory_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert isDirectory @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterForFiles_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterForFiles_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) filenames = map(lambda r: ( r.filename, r.isDirectory ), results) assert len(list(filenames)) > 0 for f, isDirectory in filenames: assert not isDirectory @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterPattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterPattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 2 assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) not in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterUnicodePattern_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterUnicodePattern_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) assert len(filenames) == 1 assert ( u'Test File.txt', False ) not in filenames assert ( u'Test Folder', True ) not in filenames assert ( u'子文件夹', True ) in filenames @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listPathFilterEmptyList_SMB1(): global conn results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listPathFilterEmptyList_SMB2(): global conn results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) ================================================ FILE: python3/tests/SMBConnectionTests/test_listshares.py ================================================ from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] ================================================ FILE: python3/tests/SMBConnectionTests/test_listsnapshots.py ================================================ from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 ================================================ FILE: python3/tests/SMBConnectionTests/test_messages_in_exception.py ================================================ # -*- coding: utf-8 -*- from io import BytesIO from typing import Optional from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn: Optional[SMBConnection] = None TEST_FILE_NAME = 'StoreTest.txt' TEST_SERVICE_NAME = 'smbtest' def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp=True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_messages_in_exception_SMB2(): info = getConnectionInfo() with open(f'''\\\\{info['server_ip']}\\{TEST_SERVICE_NAME}\\{TEST_FILE_NAME}''', 'w'): try: conn.storeFile(TEST_SERVICE_NAME, TEST_FILE_NAME, BytesIO(b'Test data')) except Exception as ex: conn.retrieveFile(TEST_SERVICE_NAME, TEST_FILE_NAME, BytesIO()) last_smb_message = ex.args[1][-1] if last_smb_message.status != 0xC0000043: raise ex ================================================ FILE: python3/tests/SMBConnectionTests/test_rename.py ================================================ # -*- coding: utf-8 -*- import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_english_file_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_english_file_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_unicode_file_SMB1(): global conn old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_unicode_file_SMB2(): global conn old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.storeFile('smbtest', old_path, BytesIO(b'Rename file test')) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteFiles('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_english_directory_SMB1(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_english_directory_SMB2(): global conn old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_rename_unicode_directory_SMB1(): global conn old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_rename_unicode_directory_SMB2(): global conn old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) conn.createDirectory('smbtest', old_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) in filenames assert os.path.basename(new_path.replace('/', os.sep)) not in filenames conn.rename('smbtest', old_path, new_path) entries = conn.listPath('smbtest', os.path.dirname(old_path.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(old_path.replace('/', os.sep)) not in filenames assert os.path.basename(new_path.replace('/', os.sep)) in filenames conn.deleteDirectory('smbtest', new_path) ================================================ FILE: python3/tests/SMBConnectionTests/test_retrievefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '5367c2bbf97f521059c78eab65309ad3' assert filesize == 158437 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/Implementing CIFS - SMB.html', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '671c5700d279fcbbf958c1bba3c2639e' assert filesize == 421269 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFile('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '8a44c1e80d55e91c92350955cdf83442' assert filesize == 256000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'a141bd8024571ce7cb5c67f2b0d8ea0b' assert filesize == 156000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 100000) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '83b7afd7c92cdece3975338b5ca0b1c5' assert filesize == 100000 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 10) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == '746f60a96b39b712a7b6e17ddde19986' assert filesize == 10 temp_fh.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn temp_fh = BytesIO() file_attributes, filesize = conn.retrieveFileFromOffset('smbtest', '/测试文件夹/垃圾文件.dat', temp_fh, offset = 100000, max_length = 0) md = MD5() md.update(temp_fh.getvalue()) assert md.hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e' assert filesize == 0 temp_fh.close() ================================================ FILE: python3/tests/SMBConnectionTests/test_storefile.py ================================================ # -*- coding: utf-8 -*- import os, tempfile, random, time from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo try: import hashlib def MD5(): return hashlib.md5() except ImportError: import md5 def MD5(): return md5.new() conn = None TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') TEST_FILESIZE = 256000 TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB1) @with_teardown(teardown_func) def test_store_from_offset_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) buf = BytesIO(b'0123456789') filesize = conn.storeFile('smbtest', filename, buf) assert filesize == 10 buf = BytesIO(b'aa') pos = conn.storeFileFromOffset('smbtest', filename, buf, 5) assert pos == 7 buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == 10 assert buf.getvalue() == b'01234aa789' buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) filesize = conn.storeFile('smbtest', filename, open(TEST_FILENAME, 'rb')) assert filesize == TEST_FILESIZE entries = conn.listPath('smbtest', os.path.dirname(filename.replace('/', os.sep))) filenames = [e.filename for e in entries] assert os.path.basename(filename.replace('/', os.sep)) in filenames buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == TEST_FILESIZE md = MD5() md.update(buf.getvalue()) assert md.hexdigest() == TEST_DIGEST buf.close() conn.deleteFiles('smbtest', filename) @with_setup(setup_func_SMB2) @with_teardown(teardown_func) def test_store_from_offset_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) buf = BytesIO(b'0123456789') filesize = conn.storeFile('smbtest', filename, buf) assert filesize == 10 buf = BytesIO(b'aa') pos = conn.storeFileFromOffset('smbtest', filename, buf, 5) assert pos == 7 buf = BytesIO() file_attributes, file_size = conn.retrieveFile('smbtest', filename, buf) assert file_size == 10 assert buf.getvalue() == b'01234aa789' buf.close() conn.deleteFiles('smbtest', filename) ================================================ FILE: python3/tests/SMBConnectionTests/test_with_context.py ================================================ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection from .util import getConnectionInfo def test_context(): info = getConnectionInfo() with SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) as conn: assert conn.connect(info['server_ip'], info['server_port']) assert conn.sock is None ================================================ FILE: python3/tests/SMBConnectionTests/util.py ================================================ import os from configparser import ConfigParser def getConnectionInfo(): config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') cp = ConfigParser() cp.read(config_filename) info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), 'server_port': cp.getint('server', 'port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), 'domain': cp.get('user', 'domain') } return info ================================================ FILE: python3/tests/__init__.py ================================================ ================================================ FILE: python3/tests/connection.ini ================================================ [server] name = SERVER ip = 192.168.1.1 port = 139 direct_port = 445 [client] name = TESTCLIENT [user] name = myuser password = mypassword domain = ================================================ FILE: python3/tests/test_md4.py ================================================ from smb.utils.md4 import MD4 _md4_test_data = [ ("", 0x31d6cfe0d16ae931b73c59d7e0c089c0), ("a", 0xbde52cb31de33e46245e05fbdbd6fb24), ("abc", 0xa448017aaf21d8525fc10ae87aa6729d), ("message digest", 0xd9130a8164549fe818874806e1c7014b), ("abcdefghijklmnopqrstuvwxyz", 0xd79e1c308aa5bbcdeea8ed63df412da9), ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 0x043f8582f241db351ce627e153e7f0e4), ( "12345678901234567890123456789012345678901234567890123456789012345678901234567890", 0xe33b4ddc9c38f2199c3e7b164fcc0536), ("The quick brown fox jumps over the lazy dog", 0x1bee69a46ba811185c194762abaeae90), ("The quick brown fox jumps over the lazy cog", 0xb86e130ce7028da59e672d56ad0113df) ] def test_md4(): for input_data, expected_result in _md4_test_data: expected_digest = expected_result.to_bytes(16, byteorder="big", signed=False) md4 = MD4() md4.update(input_data) computed_digest = md4.digest() assert computed_digest == expected_digest ================================================ FILE: python3/tests/test_ntlm.py ================================================ import binascii from smb import ntlm def test_NTLMv1_without_extended_security(): password = 'Password' server_challenge = b'\x01\x23\x45\x67\x89\xab\xcd\xef' nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(password, server_challenge, has_extended_security = False, client_challenge = b'\xAA'*8) assert binascii.hexlify(nt_challenge_response).lower() == b'67 c4 30 11 f3 02 98 a2 ad 35 ec e6 4f 16 33 1c 44 bd be d9 27 84 1f 94'.replace(b' ', b'') # [MS-NLMP]: 4.2.2.2.1 assert binascii.hexlify(lm_challenge_response).lower() == b'98 de f7 b8 7f 88 aa 5d af e2 df 77 96 88 a1 72 de f1 1c 7d 5c cd ef 13'.replace(b' ', b'') # [MS-NLMP]: 4.2.2.2.2 def test_NTLMv1_with_extended_security(): password = 'Password' server_challenge = b'\x01\x23\x45\x67\x89\xab\xcd\xef' nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(password, server_challenge, has_extended_security = True, client_challenge = b'\xAA'*8) assert binascii.hexlify(nt_challenge_response).lower() == b'75 37 f8 03 ae 36 71 28 ca 45 82 04 bd e7 ca f8 1e 97 ed 26 83 26 72 32'.replace(b' ', b'') # [MS-NLMP]: 4.2.3.2.2 assert binascii.hexlify(lm_challenge_response).lower() == b'aa aa aa aa aa aa aa aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'.replace(b' ', b'') # [MS-NLMP]: 4.2.3.2.1 def test_NTLMv2(): user = 'User' password = 'Password' domain = 'Domain' server_challenge = b'\x01\x23\x45\x67\x89\xab\xcd\xef' server_avpair = binascii.unhexlify(b'01 00 0c 00 53 00 65 00 72 00 76 00 65 00 72 00'.replace(b' ', b'')) domain_avpair = binascii.unhexlify(b'02 00 0c 00 44 00 6f 00 6d 00 61 00 69 00 6e 00'.replace(b' ', b'')) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(password, user, server_challenge, server_avpair + domain_avpair + b'\0'*4, domain, client_challenge = b'\xAA'*8) assert binascii.hexlify(lm_challenge_response).lower() == b'86 c3 50 97 ac 9c ec 10 25 54 76 4a 57 cc cc 19 aa aa aa aa aa aa aa aa'.replace(b' ', b'') # [MS-NLMP]: 4.2.4.2.1 ================================================ FILE: python3/tests/test_security_descriptors.py ================================================ import binascii from smb import security_descriptors as sd from smb import smb_constants as sc def test_sid_string_representation(): sid = sd.SID(1, 5, [2, 3, 4]) assert str(sid) == "S-1-5-2-3-4" sid = sd.SID(1, 2**32 + 3, []) assert str(sid) == "S-1-0x100000003" sid = sd.SID(1, 2**32, [3, 2, 1]) assert str(sid) == "S-1-0x100000000-3-2-1" def test_sid_binary_parsing(): raw_sid = binascii.unhexlify(b""" 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, b' \n')) assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" raw_sid += b"garbage" assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" sid, tail = sd.SID.from_bytes(raw_sid, return_tail=True) assert str(sid) == "S-1-5-21-717312990-3403304746-849770945-1201" assert tail == b"garbage" def test_ace_binary_parsing(): raw_ace = binascii.unhexlify(b""" 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 6e 04 00 00 """.translate(None, b' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1134" assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES | sc.FILE_WRITE_ATTRIBUTES) assert not ace.additional_data raw_ace = binascii.unhexlify(b""" 00 13 18 00 a9 00 12 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 """.translate(None, b' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-32-545" assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert ace.flags == (sd.ACE_FLAG_INHERITED | sd.ACE_FLAG_CONTAINER_INHERIT | sd.ACE_FLAG_OBJECT_INHERIT) assert ace.mask == (sc.SYNCHRONIZE | sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) assert not ace.additional_data raw_ace = binascii.unhexlify(b""" 01 03 24 00 a9 00 02 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 6c 04 00 00 """.translate(None, b' \n')) ace = sd.ACE.from_bytes(raw_ace) assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1132" assert ace.type == sd.ACE_TYPE_ACCESS_DENIED assert ace.flags == (sd.ACE_FLAG_CONTAINER_INHERIT | sd.ACE_FLAG_OBJECT_INHERIT) assert ace.mask == (sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) assert not ace.additional_data def test_acl_binary_parsing(): raw_acl = binascii.unhexlify(b""" 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, b' \n')) acl = sd.ACL.from_bytes(raw_acl) assert acl.revision == 2 assert len(acl.aces) == 4 ace = acl.aces[0] assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert str(ace.sid) == "S-1-5-32-545" assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.FILE_READ_DATA | sc.FILE_READ_EA | sc.FILE_READ_ATTRIBUTES) ace = acl.aces[3] assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1201" assert ace.flags == sd.ACE_FLAG_INHERITED assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES | sc.FILE_WRITE_ATTRIBUTES) def test_descriptor_binary_parsing(): raw_descriptor = binascii.unhexlify(b""" 01 00 04 84 14 00 00 00 30 00 00 00 00 00 00 00 4c 00 00 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 01 02 00 00 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 """.translate(None, b' \n')) descriptor = sd.SecurityDescriptor.from_bytes(raw_descriptor) assert descriptor.flags == (sd.SECURITY_DESCRIPTOR_SELF_RELATIVE | sd.SECURITY_DESCRIPTOR_DACL_PRESENT | sd.SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED) assert descriptor.dacl is not None assert descriptor.sacl is None assert str(descriptor.owner) == "S-1-5-21-717312990-3403304746-849770945-1201" assert str(descriptor.group) == "S-1-5-21-717312990-3403304746-849770945-513" acl = descriptor.dacl assert acl.revision == 2 assert len(acl.aces) == 4 assert str(acl.aces[0].sid) == sd.SID_BUILTIN_USERS assert str(acl.aces[1].sid) == sd.SID_LOCAL_SYSTEM assert str(acl.aces[2].sid) == sd.SID_BUILTIN_ADMINISTRATORS assert str(acl.aces[3].sid) == "S-1-5-21-717312990-3403304746-849770945-1201" ================================================ FILE: python3/tests/test_securityblob.py ================================================ import binascii from smb import securityblob def test_NTLMSSP_NEGOTIATE_encoding(): ntlm_data = binascii.unhexlify(b'4e544c4d5353500001000000978208e200000000000000000000000000000000060072170000000f') # The NTLM negotiate message blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) TARGET = binascii.unhexlify(b""" 60 48 06 06 2b 06 01 05 05 02 a0 3e 30 3c a0 0e 30 0c 06 0a 2b 06 01 04 01 82 37 02 02 0a a2 2a 04 28 4e 54 4c 4d 53 53 50 00 01 00 00 00 97 82 08 e2 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 72 17 00 00 00 0f """.replace(b' ', b'').replace(b'\n', b'')) assert blob == TARGET def test_NTLMSSP_CHALLENGE_decoding(): blob = binascii.unhexlify(b""" a1 81 be 30 81 bb a0 03 0a 01 01 a1 0c 06 0a 2b 06 01 04 01 82 37 02 02 0a a2 81 a5 04 81 a2 4e 54 4c 4d 53 53 50 00 02 00 00 00 0a 00 0a 00 38 00 00 00 15 82 8a e2 32 81 ce 29 7f de 3f 80 00 00 00 00 00 00 00 00 60 00 60 00 42 00 00 00 06 01 00 00 00 00 00 0f 43 00 45 00 54 00 55 00 53 00 02 00 0a 00 43 00 45 00 54 00 55 00 53 00 01 00 0a 00 43 00 45 00 54 00 55 00 53 00 04 00 16 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 03 00 22 00 63 00 65 00 74 00 75 00 73 00 2e 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 00 00 00 00""".replace(b' ', b'').replace(b'\n', b'')) RESPONSE_TOKENS = binascii.unhexlify(b""" 4e 54 4c 4d 53 53 50 00 02 00 00 00 0a 00 0a 00 38 00 00 00 15 82 8a e2 32 81 ce 29 7f de 3f 80 00 00 00 00 00 00 00 00 60 00 60 00 42 00 00 00 06 01 00 00 00 00 00 0f 43 00 45 00 54 00 55 00 53 00 02 00 0a 00 43 00 45 00 54 00 55 00 53 00 01 00 0a 00 43 00 45 00 54 00 55 00 53 00 04 00 16 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 03 00 22 00 63 00 65 00 74 00 75 00 73 00 2e 00 6c 00 6f 00 63 00 61 00 6c 00 64 00 6f 00 6d 00 61 00 69 00 6e 00 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) result, response_tokens = securityblob.decodeChallengeSecurityBlob(blob) assert result == securityblob.RESULT_ACCEPT_INCOMPLETE assert response_tokens == RESPONSE_TOKENS def test_NTLMSSP_AUTH_encoding(): ntlm_data = binascii.unhexlify(b""" 4e 54 4c 4d 53 53 50 00 03 00 00 00 01 00 01 00 70 00 00 00 00 00 00 00 71 00 00 00 00 00 00 00 58 00 00 00 00 00 00 00 58 00 00 00 18 00 18 00 58 00 00 00 10 00 10 00 71 00 00 00 15 8a 88 e2 06 00 72 17 00 00 00 0f 06 49 3b c4 f6 2a 2b be 61 a6 81 e7 cc 58 37 b4 4d 00 49 00 43 00 48 00 41 00 45 00 4c 00 2d 00 49 00 35 00 50 00 43 00 00 a7 0d b4 74 c3 d8 14 c9 df 3d 80 6d 87 94 42 bc """.replace(b' ', b'').replace(b'\n', b'')) TARGET = binascii.unhexlify(b""" a1 81 8a 30 81 87 a2 81 84 04 81 81 4e 54 4c 4d 53 53 50 00 03 00 00 00 01 00 01 00 70 00 00 00 00 00 00 00 71 00 00 00 00 00 00 00 58 00 00 00 00 00 00 00 58 00 00 00 18 00 18 00 58 00 00 00 10 00 10 00 71 00 00 00 15 8a 88 e2 06 00 72 17 00 00 00 0f 06 49 3b c4 f6 2a 2b be 61 a6 81 e7 cc 58 37 b4 4d 00 49 00 43 00 48 00 41 00 45 00 4c 00 2d 00 49 00 35 00 50 00 43 00 00 a7 0d b4 74 c3 d8 14 c9 df 3d 80 6d 87 94 42 bc """.replace(b' ', b'').replace(b'\n', b'')) blob = securityblob.generateAuthSecurityBlob(ntlm_data) assert blob == TARGET def test_auth_response_decoding(): blob = binascii.unhexlify(b"a1 07 30 05 a0 03 0a 01 00".replace(b' ', b'')) result = securityblob.decodeAuthResponseSecurityBlob(blob) assert result == securityblob.RESULT_ACCEPT_COMPLETED ================================================ FILE: setup.py ================================================ import sys, os try: from setuptools import setup except ImportError: from distutils.core import setup pkgdir = { '': 'python%s' % sys.version_info[0] } setup( name = "pysmb", version = "1.2.13", author = "Michael Teo", author_email = "miketeo@miketeo.net", license = "zlib/libpng", description = "pysmb is an experimental SMB/CIFS library written in Python to support file sharing between Windows and Linux machines", keywords = "windows samba cifs sharing ftp smb linux", url = "https://miketeo.net/projects/pysmb", package_dir = pkgdir, packages = [ 'smb', 'smb.utils', 'nmb' ], install_requires = [ 'pyasn1', 'tqdm' ], long_description="""pysmb is an experimental SMB/CIFS library written in Python. It implements the client-side SMB/CIFS protocol which allows your Python application to access and transfer files to/from SMB/CIFS shared folders like your Windows file sharing and Samba folders.""", classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Win32 (MS Windows)", "Environment :: Console", "License :: OSI Approved :: zlib/libpng License", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 2.4", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Communications :: File Sharing", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Networking", ], ) ================================================ FILE: sphinx/Makefile ================================================ # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = ../docs # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pysmb.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pysmb.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pysmb" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pysmb" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ================================================ FILE: sphinx/make.bat ================================================ @ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pysmb.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pysmb.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end ================================================ FILE: sphinx/requirements.txt ================================================ tqdm>=4.66.0 twisted>=15.0.0 pyasn1>=0.3.0 ================================================ FILE: sphinx/source/api/nmb_NBNSProtocol.rst ================================================ NBNSProtocol Class ================== pysmb has a *NBNSProtocol* implementation for Twisted framework. This allows you to perform name query asynchronously without having your application to block and wait for the results. In your project, 1. Create a NBNSProtocol instance. 2. Just call *queryName* method which will return a *Deferred* instance. Add your callback function to the *Deferred* instance via *addCallback* method to receive the results of the name query. 3. When you are done with the NBNSProtocol instance, call its .transport.stopListening method to remove this instance from the reactor. .. autoclass:: nmb.NetBIOSProtocol.NBNSProtocol :members: :special-members: .. autoclass:: nmb.NetBIOSProtocol.NetBIOSTimeout :members: ================================================ FILE: sphinx/source/api/nmb_NetBIOS.rst ================================================ NetBIOS class ============= To use the NetBIOS class in your application, 1. Create a new NetBIOS instance 2. Call *queryName* method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout. 3. When you are done, call *close* method to release the underlying resources. .. autoclass:: nmb.NetBIOS.NetBIOS :members: :special-members: ================================================ FILE: sphinx/source/api/smb_SMBConnection.rst ================================================ SMBConnection Class =================== The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially. Each file operation method, when invoked, will block and return after it has completed or has encountered an error. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from smb.SMBConnection import SMBConnection # 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) assert 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() SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBConnection* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * It is not meant to be used asynchronously. * A single *SMBConnection* instance should not be used to perform more than one operation concurrently at the same time. * Do not keep a *SMBConnection* instance "idle" for too long, i.e. keeping a *SMBConnection* instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client. .. autoclass:: smb.SMBConnection.SMBConnection :members: :special-members: ================================================ FILE: sphinx/source/api/smb_SMBHandler.rst ================================================ SMbHandler Class ================ The SMBHandler class provides support for "smb://" URLs in the `urllib2 `_ python package. Notes ----- * The host component of the URL must be one of the following: * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com * An IP address. Example: 192.168.1.1 * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 * The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file. * You can retrieve and upload files, but you cannot delete files/folders or create folders. In uploads, if the parent folders do not exist, an *urllib2.URLError* will be raised. Example ------- The following code snippet illustrates file retrieval with Python 2.:: # -*- coding: utf-8 -*- import urllib2 from smb.SMBHandler import SMBHandler director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib2 from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() The following code snippet illustrates file retrieval with Python 3.:: import urllib from smb.SMBHandler import SMBHandler director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close() # For paths/files with unicode characters, simply pass in the URL as an unicode string fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') # Process fh2 like a file-like object and then close it. fh2.close() The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close() ================================================ FILE: sphinx/source/api/smb_SMBProtocolFactory.rst ================================================ SMBProtocolFactory Class ======================== For those who want to utilize pysmb in Twisted framework, pysmb has a *smb.SMBProtocol.SMBProtocol* implementation. In most cases, you do not need to touch or import the *SMBProtocol* directly. All the SMB functionalities are exposed in the *SMBProtocolFactory*. In your project, 1. Create a new class and subclass *SMBProtocolFactory*. 2. Override the *SMBProtocolFactory.onAuthOK* and *SMBProtocolFactory.onAuthFailed* instance methods to provide your own post-authenthentication handling. Once *SMBProtocolFactory.onAuthOK* has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through the *SMBProtocolFactory* public methods such as *SMBProtocolFactory.storeFile*, *SMBProtocolFactory.retrieveFile*, etc. 3. When you want to disconnect from the remote SMB/CIFS server, just call *SMBProtocolFactory.closeConnection* method. All the *SMBProtocolFactory* public methods that provide file functionlities will return a *twisted.internet.defer.Deferred* instance. A :doc:`NotReadyError` exception is raised when the underlying SMB is not authenticated. If the underlying SMB connection has been terminated, a :doc:`NotConnectedError` exception is raised. All the file operation methods in *SMBProtocolFactory* class accept a *timeout* parameter. This parameter specifies the time limit where pysmb will wait for the entire file operation (except *storeFile* and *retrieveFile* methods) to complete. If the file operation fails to complete within the timeout period, the returned *Deferred* instance's *errback* method will be called with a *SMBTimeout* exception. If you are interested in learning the results of the operation or to know when the operation has completed, you should add a handling method to the returned *Deferred* instance via *Deferred.addCallback*. If the file operation fails, the *Deferred.errback* function will be called with an :doc:`OperationFailure`; on timeout, it will be called with a :doc:`SMBTimeout`. Example ------- The following illustrates a simple file retrieving implementation.:: import tempfile from twisted.internet import reactor from smb.SMBProtocol import SMBProtocolFactory class RetrieveFileFactory(SMBProtocolFactory): def __init__(self, *args, **kwargs): SMBProtocolFactory.__init__(self, *args, **kwargs) def fileRetrieved(self, write_result): file_obj, file_attributes, file_size = write_result # 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() to if you # need to read from the beginning file_obj.close() self.transport.loseConnection() def onAuthOK(self): d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile()) d.addCallback(self.fileRetrieved) d.addErrback(self.d.errback) def onAuthFailed(self): print 'Auth failed' # 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 factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) factory.service = 'smbtest' factory.path = '/rfc1001.txt' reactor.connectTCP(server_ip, 139, factory) SMB2 Support ------------- Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol. To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBProtocolFactory* instance.:: from smb import smb_structs smb_structs.SUPPORT_SMB2 = False Caveats ------- * A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection. * The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call *storeFile* or *retrieveFile* in batches. * The *timeout* parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise *SMBTimeout* exception after 1.5 sec. .. autoclass:: smb.SMBProtocol.SMBProtocolFactory :members: :special-members: ================================================ FILE: sphinx/source/api/smb_SharedDevice.rst ================================================ SharedDevice Class ================== .. autoclass:: smb.base.SharedDevice :members: ================================================ FILE: sphinx/source/api/smb_SharedFile.rst ================================================ SharedFile Class ================ .. autoclass:: smb.base.SharedFile :members: ================================================ FILE: sphinx/source/api/smb_exceptions.rst ================================================ SMB Exceptions ============== .. autoclass:: smb.base.SMBTimeout :members: .. autoclass:: smb.base.NotReadyError :members: .. autoclass:: smb.base.NotConnectedError :members: .. autoclass:: smb.smb_structs.UnsupportedFeature :members: .. autoclass:: smb.smb_structs.ProtocolError :members: .. autoclass:: smb.smb_structs.OperationFailure :members: ================================================ FILE: sphinx/source/api/smb_security_descriptors.rst ================================================ Security Descriptors ==================== .. module:: smb.security_descriptors :synopsis: Data structures used in Windows security descriptors. This module implements security descriptors, and associated data structures, as specified in `[MS-DTYP]`_. .. autoclass:: SID :members: .. autoclass:: ACE :members: .. autoclass:: ACL :members: .. autoclass:: SecurityDescriptor :members: .. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx ================================================ FILE: sphinx/source/conf.py ================================================ # -*- coding: utf-8 -*- # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'python3')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pysmb' copyright = u'2001-2025, Michael Teo https://miketeo.net/' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.2.13' # The full version, including alpha/beta/rc tags. release = '1.2.13' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] autodoc_member_order = 'groupwise' # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pysmbdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pysmb.tex', u'pysmb Documentation', u'Michael Teo', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pysmb', u'pysmb Documentation', [u'Michael Teo'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pysmb', u'pysmb Documentation', u'Michael Teo', 'pysmb', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' ================================================ FILE: sphinx/source/extending.rst ================================================ Extending pysmb For Other Frameworks ==================================== This page briefly describes the steps involved in extending pysmb for other frameworks. In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, initiate file operations with the remote SMB/CIFS server. Now the above steps in more technical details: 1. Create a new class which subclasses the *smb.base.SMB* class. Most often, the connection setup will be part of the *__init__* method. 2. Override the *write(self, data)* method to provide an implementation which will write *data* to the socket. 3. Write your own loop handling method to read data from the socket. Once data have been read, call *feedData* method with the parameter. The *feedData* method has its own internal buffer, so it can accept incomplete NetBIOS session packet data. 4. Override * *onAuthOK* method to include your own operations to perform when authentication is successful. You can initiate file operations in this method. * *onAuthFailed* method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (*use_ntlm_v2* parameter in the constructor). * *onNMBSessionFailed* method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong *remote_name* parameter in the constructor. ================================================ FILE: sphinx/source/index.rst ================================================ Welcome to pysmb's documentation! ================================= pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x. The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. License ------- pysmb itself is licensed under an opensource license. You are free to use pysmb in any applications, including for commercial purposes. For more details on the terms of use, please read the LICENSE file that comes with your pysmb source. pysmb depends on other 3rd-party modules whose terms of use are not covered by pysmb. Use of these modules could possibly conflict with your licensing needs. Please exercise your own discretion to determine their suitabilities. I have listed these modules in the following section. Credits ------- pysmb is not alone. It is made possible with support from other modules. * **pyasn1** : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately) * **md4** and **U32** : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb. * **pyDes** : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb. * **sha256** : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm. In various places, there are references to different specifications. Most of these referenced specifications can be downloaded from Microsoft web site under Microsoft's "Open Specification Promise". If you need to download a copy of these specifications, please google for it. For example, google for "MS-CIFS" to download the CIFS specification for NT LM dialect. Package Contents and Description ================================ pysmb is organized into 2 main packages: smb and nmb. The smb package contains all the functionalities related to Server Message Block (SMB) implementation. As an application developer, you will be importing this module into your application. Hence, please take some time to familiarize yourself with the smb package contents. * **nmb/base.py** : Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication without any network transport specifics. * **nmb/NetBIOS.py**: Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O. * **nmb/NetBIOSProtocol.py** : Provides the NBNS protocol implementation for use in Twisted framework. * **smb/base.py** : Contains the SMB abstract class which implements the SMB communication without any network transport specifics. * **smb/ntlm.py** : Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages. * **smb/securityblob.py** : Provides routines to encode/decode the NTLMSSP security blob in the SMB messages. * **smb/smb_constants.py** : All the constants used in the smb package for SMB1 protocol * **smb/smb_structs.py** : Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message. * **smb/smb2_constants.py** : All the constants used in the smb package for SMB2 protocol * **smb/smb2_structs.py** : Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message. * **smb/SMBConnection.py** : Contains a SMB protocol implementation. All operations are blocking I/O. * **smb/SMBProtocol.py** : Contains the SMB protocol implementation for use in the Twisted framework. * **smb/SMBHandler.py** : Provides support for "smb://" URL in the urllib2 python package. Using pysmb =========== As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses, * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`nmb.NetBIOS.NetBIOS` documentation. * To use pysmb in Twisted, please read :doc:`nmb.NetBIOSProtocol.NBNSProtocol` documentation. As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB: * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read :doc:`smb.SMBConnection.SMBConnection` documentation. * To use pysmb in Twisted, please read :doc:`smb.SMBProtocol.SMBProtocolFactory` documentation. * To support "smb://" URL in urllib2 python package, read :doc:`smb.SMBHandler.SMBHandler` documentation. As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: * Read :doc:`extending` If you are upgrading from older pysmb versions: * Read :doc:`upgrading` Indices and tables ================== .. toctree:: :glob: :maxdepth: 1 api/* extending upgrading * :ref:`genindex` * :ref:`search` ================================================ FILE: sphinx/source/upgrading.rst ================================================ Upgrading from older pysmb versions ==================================== This page documents the improvements and changes to the API that could be incompatible with previous releases. pysmb 1.2.0 ----------- - Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.28 ------------ - SharedFile instances returned from the `listPath()` method now has a new property `file_id` attribute which represents the file reference number given by the remote SMB server. pysmb 1.1.26 ------------ - SMBConnection class can now be used as a context manager pysmb 1.1.25 ------------ - SharedFile class has a new property `isNormal` which will be True if the file is a 'normal' file. pysmb defines a 'normal' file as a file entry that is not read-only, not hidden, not system, not archive and not a directory; it ignores other attributes like compression, indexed, sparse, temporary and encryption. - `listPath()` method in SMBProtocolFactory and SMBConnection class will now include 'normal' files by default if you do not specify the `search` parameter. pysmb 1.1.20 ------------ - A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.15 ------------ - Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection class to support truncation of the file before writing. If you are passing timeout parameter to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. pysmb 1.1.11 ------------ - A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. pysmb 1.1.10 ------------ - A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class - SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. pysmb 1.1.2 ----------- - `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. pysmb 1.0.3 ----------- - Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` to support querying for a machine's NetBIOS name at the given IP address. - A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection to support finer control of file retrieval operation. pysmb 1.0.0 ----------- pysmb was completely rewritten in version 1.0.0. If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API. ================================================ FILE: utils/ScanNetworkForSMB.py ================================================ #!/usr/bin/python # # ScanNetworkForSMB.py - Script for scanning network for open SMB/CIFS services # Copyright (C) 2012 Michael Teo # # This software is provided 'as-is', without any express or implied warranty. # In no event will the author be held liable for any damages arising from the # use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # # 3. This notice cannot be removed or altered from any source distribution. # import sys, select, socket, random, string, time from nmb import base class NonBlockingNetBIOS(base.NBNS): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.pendings = set() self.pending_count = 0 def write(self, data, ip, port): assert self.sock, 'Socket is already closed' self.sock.sendto(data, ( ip, port )) def queryIPForName(self, ip): assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) data = self.prepareNetNameQuery(trn_id) self.write(data, ip, 137) self.pendings.add(ip) self.pending_count += 1 def queryResult(self, ip, results): results = filter(lambda s: s and s[0] in string.printable, results) if results: print ip.rjust(16), '-->', ' '.join(results) def poll(self, timeout = 0): end_time = time.time() + timeout while self.pending_count > 0 and (timeout == 0 or time.time() < end_time): t = max(0, end_time - time.time()) try: ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], t) if not ready: return None data, ( ip, port ) = self.sock.recvfrom(0xFFFF) _, ret = self.decodeIPQueryPacket(data) try: self.pendings.remove(ip) self.pending_count -= 1 self.queryResult(ip, set(ret)) except KeyError: pass except select.error, ex: if type(ex) is types.TupleType: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex # Originally from http://snipplr.com/view/14807/ def DottedIPToInt(dotted_ip): exp = 3 intip = 0 for quad in dotted_ip.split('.'): intip = intip + (int(quad) * (256 ** exp)) exp = exp - 1 return(intip) def IntToDottedIP( intip ): octet = '' for exp in [3,2,1,0]: octet = octet + str(intip / ( 256 ** exp )) + "." intip = intip % ( 256 ** exp ) return(octet.rstrip('.')) def main(): if len(sys.argv) > 2: start_ip = DottedIPToInt(sys.argv[1]) end_ip = DottedIPToInt(sys.argv[2]) elif len(sys.argv) == 2: start_ip = DottedIPToInt(sys.argv[1]) end_ip = start_ip else: print 'ScanNetworkForSMB - Script for scanning network for open SMB/CIFS services' print 'Error: missing IP arguments' print 'Usage:', sys.argv[0], 'start-IP-address [end-IP-address]' print return print 'Beginning scanning %d IP addresses...' % ( end_ip-start_ip+1, ) print ns = NonBlockingNetBIOS() for ip in range(start_ip, end_ip + 1): ns.queryIPForName(IntToDottedIP(ip)) ns.poll() if ns.pending_count > 0: ns.poll(10) print print 'Query timeout. No replies from %d IP addresses' % ns.pending_count if __name__ == '__main__': main() ================================================ FILE: utils/recursiveDelete.py ================================================ #!/usr/bin/python2 # # Simple script to demonstrate how to delete all files/sub-folders in the shared folder # from smb.SMBConnection import SMBConnection dry_run = True # Set to True to test if all files/folders can be "walked". Set to False to perform the deletion. userID = 'myuser' password = 'mypassword' client_machine_name = 'testclient' # Usually safe to use 'testclient' server_name = 'MYSERVER' # Must match the NetBIOS name of the remote server server_ip = '192.168.1.10' # Must point to the correct IP address domain_name = '' # Safe to leave blank, or fill in the domain used for your remote server shared_folder = 'smbtest' # Set to the shared folder name 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) def walk_path(path): print 'Walking path', path for p in conn.listPath(shared_folder, path): if p.filename!='.' and p.filename!='..': parentPath = path if not parentPath.endswith('/'): parentPath += '/' if p.isDirectory: walk_path(parentPath+p.filename) print 'Deleting folder (%s) in %s' % ( p.filename, path ) if not dry_run: conn.deleteDirectory(shared_folder, parentPath+p.filename) else: print 'Deleting file (%s) in %s' % ( p.filename, path ) if not dry_run: conn.deleteFiles(shared_folder, parentPath+p.filename) # Start and delete everything at shared folder root walk_path('/')