smbserver.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Project ___| | | | _ \| |
  5. # / __| | | | |_) | |
  6. # | (__| |_| | _ <| |___
  7. # \___|\___/|_| \_\_____|
  8. #
  9. # Copyright (C) 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
  10. #
  11. # This software is licensed as described in the file COPYING, which
  12. # you should have received as part of this distribution. The terms
  13. # are also available at https://curl.haxx.se/docs/copyright.html.
  14. #
  15. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. # copies of the Software, and permit persons to whom the Software is
  17. # furnished to do so, under the terms of the COPYING file.
  18. #
  19. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. # KIND, either express or implied.
  21. #
  22. """Server for testing SMB"""
  23. from __future__ import (absolute_import, division, print_function)
  24. # unicode_literals)
  25. import argparse
  26. import ConfigParser
  27. import os
  28. import sys
  29. import logging
  30. import tempfile
  31. # Import our curl test data helper
  32. import curl_test_data
  33. # This saves us having to set up the PYTHONPATH explicitly
  34. deps_dir = os.path.join(os.path.dirname(__file__), "python_dependencies")
  35. sys.path.append(deps_dir)
  36. from impacket import smbserver as imp_smbserver
  37. from impacket import smb as imp_smb
  38. from impacket.nt_errors import (STATUS_ACCESS_DENIED, STATUS_SUCCESS,
  39. STATUS_NO_SUCH_FILE)
  40. log = logging.getLogger(__name__)
  41. SERVER_MAGIC = "SERVER_MAGIC"
  42. TESTS_MAGIC = "TESTS_MAGIC"
  43. VERIFIED_REQ = "verifiedserver"
  44. VERIFIED_RSP = b"WE ROOLZ: {pid}\n"
  45. def smbserver(options):
  46. """Start up a TCP SMB server that serves forever
  47. """
  48. if options.pidfile:
  49. pid = os.getpid()
  50. with open(options.pidfile, "w") as f:
  51. f.write("{0}".format(pid))
  52. # Here we write a mini config for the server
  53. smb_config = ConfigParser.ConfigParser()
  54. smb_config.add_section("global")
  55. smb_config.set("global", "server_name", "SERVICE")
  56. smb_config.set("global", "server_os", "UNIX")
  57. smb_config.set("global", "server_domain", "WORKGROUP")
  58. smb_config.set("global", "log_file", "")
  59. smb_config.set("global", "credentials_file", "")
  60. # We need a share which allows us to test that the server is running
  61. smb_config.add_section("SERVER")
  62. smb_config.set("SERVER", "comment", "server function")
  63. smb_config.set("SERVER", "read only", "yes")
  64. smb_config.set("SERVER", "share type", "0")
  65. smb_config.set("SERVER", "path", SERVER_MAGIC)
  66. # Have a share for tests. These files will be autogenerated from the
  67. # test input.
  68. smb_config.add_section("TESTS")
  69. smb_config.set("TESTS", "comment", "tests")
  70. smb_config.set("TESTS", "read only", "yes")
  71. smb_config.set("TESTS", "share type", "0")
  72. smb_config.set("TESTS", "path", TESTS_MAGIC)
  73. if not options.srcdir or not os.path.isdir(options.srcdir):
  74. raise ScriptException("--srcdir is mandatory")
  75. test_data_dir = os.path.join(options.srcdir, "data")
  76. smb_server = TestSmbServer(("127.0.0.1", options.port),
  77. config_parser=smb_config,
  78. test_data_directory=test_data_dir)
  79. log.info("[SMB] setting up SMB server on port %s", options.port)
  80. smb_server.processConfigFile()
  81. smb_server.serve_forever()
  82. return 0
  83. class TestSmbServer(imp_smbserver.SMBSERVER):
  84. """
  85. Test server for SMB which subclasses the impacket SMBSERVER and provides
  86. test functionality.
  87. """
  88. def __init__(self,
  89. address,
  90. config_parser=None,
  91. test_data_directory=None):
  92. imp_smbserver.SMBSERVER.__init__(self,
  93. address,
  94. config_parser=config_parser)
  95. # Set up a test data object so we can get test data later.
  96. self.ctd = curl_test_data.TestData(test_data_directory)
  97. # Override smbComNtCreateAndX so we can pretend to have files which
  98. # don't exist.
  99. self.hookSmbCommand(imp_smb.SMB.SMB_COM_NT_CREATE_ANDX,
  100. self.create_and_x)
  101. def create_and_x(self, conn_id, smb_server, smb_command, recv_packet):
  102. """
  103. Our version of smbComNtCreateAndX looks for special test files and
  104. fools the rest of the framework into opening them as if they were
  105. normal files.
  106. """
  107. conn_data = smb_server.getConnectionData(conn_id)
  108. # Wrap processing in a try block which allows us to throw SmbException
  109. # to control the flow.
  110. try:
  111. ncax_parms = imp_smb.SMBNtCreateAndX_Parameters(
  112. smb_command["Parameters"])
  113. path = self.get_share_path(conn_data,
  114. ncax_parms["RootFid"],
  115. recv_packet["Tid"])
  116. log.info("[SMB] Requested share path: %s", path)
  117. disposition = ncax_parms["Disposition"]
  118. log.debug("[SMB] Requested disposition: %s", disposition)
  119. # Currently we only support reading files.
  120. if disposition != imp_smb.FILE_OPEN:
  121. raise SmbException(STATUS_ACCESS_DENIED,
  122. "Only support reading files")
  123. # Check to see if the path we were given is actually a
  124. # magic path which needs generating on the fly.
  125. if path not in [SERVER_MAGIC, TESTS_MAGIC]:
  126. # Pass the command onto the original handler.
  127. return imp_smbserver.SMBCommands.smbComNtCreateAndX(conn_id,
  128. smb_server,
  129. smb_command,
  130. recv_packet)
  131. flags2 = recv_packet["Flags2"]
  132. ncax_data = imp_smb.SMBNtCreateAndX_Data(flags=flags2,
  133. data=smb_command[
  134. "Data"])
  135. requested_file = imp_smbserver.decodeSMBString(
  136. flags2,
  137. ncax_data["FileName"])
  138. log.debug("[SMB] User requested file '%s'", requested_file)
  139. if path == SERVER_MAGIC:
  140. fid, full_path = self.get_server_path(requested_file)
  141. else:
  142. assert (path == TESTS_MAGIC)
  143. fid, full_path = self.get_test_path(requested_file)
  144. resp_parms = imp_smb.SMBNtCreateAndXResponse_Parameters()
  145. resp_data = ""
  146. # Simple way to generate a fid
  147. if len(conn_data["OpenedFiles"]) == 0:
  148. fakefid = 1
  149. else:
  150. fakefid = conn_data["OpenedFiles"].keys()[-1] + 1
  151. resp_parms["Fid"] = fakefid
  152. resp_parms["CreateAction"] = disposition
  153. if os.path.isdir(path):
  154. resp_parms[
  155. "FileAttributes"] = imp_smb.SMB_FILE_ATTRIBUTE_DIRECTORY
  156. resp_parms["IsDirectory"] = 1
  157. else:
  158. resp_parms["IsDirectory"] = 0
  159. resp_parms["FileAttributes"] = ncax_parms["FileAttributes"]
  160. # Get this file's information
  161. resp_info, error_code = imp_smbserver.queryPathInformation(
  162. "", full_path, level=imp_smb.SMB_QUERY_FILE_ALL_INFO)
  163. if error_code != STATUS_SUCCESS:
  164. raise SmbException(error_code, "Failed to query path info")
  165. resp_parms["CreateTime"] = resp_info["CreationTime"]
  166. resp_parms["LastAccessTime"] = resp_info[
  167. "LastAccessTime"]
  168. resp_parms["LastWriteTime"] = resp_info["LastWriteTime"]
  169. resp_parms["LastChangeTime"] = resp_info[
  170. "LastChangeTime"]
  171. resp_parms["FileAttributes"] = resp_info[
  172. "ExtFileAttributes"]
  173. resp_parms["AllocationSize"] = resp_info[
  174. "AllocationSize"]
  175. resp_parms["EndOfFile"] = resp_info["EndOfFile"]
  176. # Let's store the fid for the connection
  177. # smbServer.log("Create file %s, mode:0x%x" % (pathName, mode))
  178. conn_data["OpenedFiles"][fakefid] = {}
  179. conn_data["OpenedFiles"][fakefid]["FileHandle"] = fid
  180. conn_data["OpenedFiles"][fakefid]["FileName"] = path
  181. conn_data["OpenedFiles"][fakefid]["DeleteOnClose"] = False
  182. except SmbException as s:
  183. log.debug("[SMB] SmbException hit: %s", s)
  184. error_code = s.error_code
  185. resp_parms = ""
  186. resp_data = ""
  187. resp_cmd = imp_smb.SMBCommand(imp_smb.SMB.SMB_COM_NT_CREATE_ANDX)
  188. resp_cmd["Parameters"] = resp_parms
  189. resp_cmd["Data"] = resp_data
  190. smb_server.setConnectionData(conn_id, conn_data)
  191. return [resp_cmd], None, error_code
  192. def get_share_path(self, conn_data, root_fid, tid):
  193. conn_shares = conn_data["ConnectedShares"]
  194. if tid in conn_shares:
  195. if root_fid > 0:
  196. # If we have a rootFid, the path is relative to that fid
  197. path = conn_data["OpenedFiles"][root_fid]["FileName"]
  198. log.debug("RootFid present %s!" % path)
  199. else:
  200. if "path" in conn_shares[tid]:
  201. path = conn_shares[tid]["path"]
  202. else:
  203. raise SmbException(STATUS_ACCESS_DENIED,
  204. "Connection share had no path")
  205. else:
  206. raise SmbException(imp_smbserver.STATUS_SMB_BAD_TID,
  207. "TID was invalid")
  208. return path
  209. def get_server_path(self, requested_filename):
  210. log.debug("[SMB] Get server path '%s'", requested_filename)
  211. if requested_filename not in [VERIFIED_REQ]:
  212. raise SmbException(STATUS_NO_SUCH_FILE, "Couldn't find the file")
  213. fid, filename = tempfile.mkstemp()
  214. log.debug("[SMB] Created %s (%d) for storing '%s'",
  215. filename, fid, requested_filename)
  216. contents = ""
  217. if requested_filename == VERIFIED_REQ:
  218. log.debug("[SMB] Verifying server is alive")
  219. contents = VERIFIED_RSP.format(pid=os.getpid())
  220. self.write_to_fid(fid, contents)
  221. return fid, filename
  222. def write_to_fid(self, fid, contents):
  223. # Write the contents to file descriptor
  224. os.write(fid, contents)
  225. os.fsync(fid)
  226. # Rewind the file to the beginning so a read gets us the contents
  227. os.lseek(fid, 0, os.SEEK_SET)
  228. def get_test_path(self, requested_filename):
  229. log.info("[SMB] Get reply data from 'test%s'", requested_filename)
  230. fid, filename = tempfile.mkstemp()
  231. log.debug("[SMB] Created %s (%d) for storing test '%s'",
  232. filename, fid, requested_filename)
  233. try:
  234. contents = self.ctd.get_test_data(requested_filename)
  235. self.write_to_fid(fid, contents)
  236. return fid, filename
  237. except Exception:
  238. log.exception("Failed to make test file")
  239. raise SmbException(STATUS_NO_SUCH_FILE, "Failed to make test file")
  240. class SmbException(Exception):
  241. def __init__(self, error_code, error_message):
  242. super(SmbException, self).__init__(error_message)
  243. self.error_code = error_code
  244. class ScriptRC(object):
  245. """Enum for script return codes"""
  246. SUCCESS = 0
  247. FAILURE = 1
  248. EXCEPTION = 2
  249. class ScriptException(Exception):
  250. pass
  251. def get_options():
  252. parser = argparse.ArgumentParser()
  253. parser.add_argument("--port", action="store", default=9017,
  254. type=int, help="port to listen on")
  255. parser.add_argument("--verbose", action="store", type=int, default=0,
  256. help="verbose output")
  257. parser.add_argument("--pidfile", action="store",
  258. help="file name for the PID")
  259. parser.add_argument("--logfile", action="store",
  260. help="file name for the log")
  261. parser.add_argument("--srcdir", action="store", help="test directory")
  262. parser.add_argument("--id", action="store", help="server ID")
  263. parser.add_argument("--ipv4", action="store_true", default=0,
  264. help="IPv4 flag")
  265. return parser.parse_args()
  266. def setup_logging(options):
  267. """
  268. Set up logging from the command line options
  269. """
  270. root_logger = logging.getLogger()
  271. add_stdout = False
  272. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
  273. # Write out to a logfile
  274. if options.logfile:
  275. handler = logging.FileHandler(options.logfile, mode="w")
  276. handler.setFormatter(formatter)
  277. handler.setLevel(logging.DEBUG)
  278. root_logger.addHandler(handler)
  279. else:
  280. # The logfile wasn't specified. Add a stdout logger.
  281. add_stdout = True
  282. if options.verbose:
  283. # Add a stdout logger as well in verbose mode
  284. root_logger.setLevel(logging.DEBUG)
  285. add_stdout = True
  286. else:
  287. root_logger.setLevel(logging.INFO)
  288. if add_stdout:
  289. stdout_handler = logging.StreamHandler(sys.stdout)
  290. stdout_handler.setFormatter(formatter)
  291. stdout_handler.setLevel(logging.DEBUG)
  292. root_logger.addHandler(stdout_handler)
  293. if __name__ == '__main__':
  294. # Get the options from the user.
  295. options = get_options()
  296. # Setup logging using the user options
  297. setup_logging(options)
  298. # Run main script.
  299. try:
  300. rc = smbserver(options)
  301. except Exception as e:
  302. log.exception(e)
  303. rc = ScriptRC.EXCEPTION
  304. log.info("[SMB] Returning %d", rc)
  305. sys.exit(rc)