Debian Codegraph @

deps/curl/tests/smbserver.py

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