smbserver.py 14 KB

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