smbserver.py 14 KB

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