2
0

smbserver.py 16 KB

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