1# SPDX-License-Identifier: GPL-2.0-only
2# This file is part of Scapy
3# See https://scapy.net/ for more information
4# Copyright (C) Gabriel Potter
5
6"""
7SMB 2 Server Automaton
8
9This provides a [MS-SMB2] server that can:
10- serve files
11- host a DCE/RPC server
12
13This is a Scapy Automaton that is supposedly easily extendable.
14
15.. note::
16 You will find more complete documentation for this layer over at
17 `SMB <https://scapy.readthedocs.io/en/latest/layers/smb.html#server>`_
18"""
19
20import hashlib
21import pathlib
22import socket
23import struct
24import time
25
26from scapy.arch import get_if_addr
27from scapy.automaton import ATMT, Automaton
28from scapy.compat import isreserved
29from scapy.config import conf
30from scapy.error import log_runtime, log_interactive
31from scapy.volatile import RandUUID
32
33from scapy.layers.dcerpc import (
34 DCERPC_Transport,
35 NDRUnion,
36 NDRPointer,
37)
38from scapy.layers.gssapi import (
39 GSS_S_COMPLETE,
40 GSS_S_CONTINUE_NEEDED,
41 GSS_S_CREDENTIALS_EXPIRED,
42)
43from scapy.layers.msrpce.rpcserver import DCERPC_Server
44from scapy.layers.ntlm import (
45 NTLMSSP,
46)
47from scapy.layers.smb import (
48 SMBNegotiate_Request,
49 SMBSession_Null,
50 SMBSession_Setup_AndX_Request,
51 SMBSession_Setup_AndX_Request_Extended_Security,
52 SMB_Header,
53)
54from scapy.layers.windows.security import SECURITY_DESCRIPTOR
55from scapy.layers.smb2 import (
56 DFS_REFERRAL_ENTRY1,
57 DFS_REFERRAL_V3,
58 DirectTCP,
59 FILE_BOTH_DIR_INFORMATION,
60 FILE_FULL_DIR_INFORMATION,
61 FILE_ID_BOTH_DIR_INFORMATION,
62 FILE_NAME_INFORMATION,
63 FileAllInformation,
64 FileAlternateNameInformation,
65 FileBasicInformation,
66 FileEaInformation,
67 FileFsAttributeInformation,
68 FileFsSizeInformation,
69 FileFsVolumeInformation,
70 FileIdBothDirectoryInformation,
71 FileInternalInformation,
72 FileNetworkOpenInformation,
73 FileStandardInformation,
74 FileStreamInformation,
75 NETWORK_INTERFACE_INFO,
76 SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2,
77 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE,
78 SMB2_CREATE_QUERY_ON_DISK_ID,
79 SMB2_Cancel_Request,
80 SMB2_Change_Notify_Request,
81 SMB2_Change_Notify_Response,
82 SMB2_Close_Request,
83 SMB2_Close_Response,
84 SMB2_Create_Context,
85 SMB2_Create_Request,
86 SMB2_Create_Response,
87 SMB2_ENCRYPTION_CIPHERS,
88 SMB2_Echo_Request,
89 SMB2_Echo_Response,
90 SMB2_Encryption_Capabilities,
91 SMB2_Error_Response,
92 SMB2_FILEID,
93 SMB2_Header,
94 SMB2_IOCTL_Network_Interface_Info,
95 SMB2_IOCTL_RESP_GET_DFS_Referral,
96 SMB2_IOCTL_Request,
97 SMB2_IOCTL_Response,
98 SMB2_IOCTL_Validate_Negotiate_Info_Response,
99 SMB2_Negotiate_Context,
100 SMB2_Negotiate_Protocol_Request,
101 SMB2_Negotiate_Protocol_Response,
102 SMB2_Preauth_Integrity_Capabilities,
103 SMB2_Query_Directory_Request,
104 SMB2_Query_Directory_Response,
105 SMB2_Query_Info_Request,
106 SMB2_Query_Info_Response,
107 SMB2_Read_Request,
108 SMB2_Read_Response,
109 SMB2_SIGNING_ALGORITHMS,
110 SMB2_Session_Logoff_Request,
111 SMB2_Session_Logoff_Response,
112 SMB2_Session_Setup_Request,
113 SMB2_Session_Setup_Response,
114 SMB2_Set_Info_Request,
115 SMB2_Set_Info_Response,
116 SMB2_Signing_Capabilities,
117 SMB2_Tree_Connect_Request,
118 SMB2_Tree_Connect_Response,
119 SMB2_Tree_Disconnect_Request,
120 SMB2_Tree_Disconnect_Response,
121 SMB2_Write_Request,
122 SMB2_Write_Response,
123 SMBStreamSocket,
124 SOCKADDR_STORAGE,
125 SRVSVC_SHARE_TYPES,
126)
127from scapy.layers.spnego import SPNEGOSSP
128
129# Import DCE/RPC
130from scapy.layers.msrpce.raw.ms_srvs import (
131 LPSERVER_INFO_101,
132 LPSHARE_ENUM_STRUCT,
133 LPSHARE_INFO_1,
134 NetrServerGetInfo_Request,
135 NetrServerGetInfo_Response,
136 NetrShareEnum_Request,
137 NetrShareEnum_Response,
138 NetrShareGetInfo_Request,
139 NetrShareGetInfo_Response,
140 SHARE_INFO_1_CONTAINER,
141)
142from scapy.layers.msrpce.raw.ms_wkst import (
143 LPWKSTA_INFO_100,
144 NetrWkstaGetInfo_Request,
145 NetrWkstaGetInfo_Response,
146)
147
148
149class SMBShare:
150 """
151 A class used to define a share, used by SMB_Server
152
153 :param name: the share name
154 :param path: the path the the folder hosted by the share
155 :param type: (optional) share type per [MS-SRVS] sect 2.2.2.4
156 :param remark: (optional) a description of the share
157 :param encryptdata: (optional) whether encryption should be used for this
158 share. This only applies to SMB 3.1.1.
159 """
160
161 def __init__(self, name, path=".", type=None, remark="", encryptdata=False):
162 # Set the default type
163 if type is None:
164 type = 0 # DISKTREE
165 if name.endswith("$"):
166 type &= 0x80000000 # SPECIAL
167 # Lower case the name for resolution
168 self._name = name.lower()
169 # Resolve path
170 self.path = pathlib.Path(path).resolve()
171 # props
172 self.name = name
173 self.type = type
174 self.remark = remark
175 self.encryptdata = encryptdata
176
177 def __repr__(self):
178 type = SRVSVC_SHARE_TYPES[self.type & 0x0FFFFFFF]
179 if self.type & 0x80000000:
180 type = "SPECIAL+" + type
181 if self.type & 0x40000000:
182 type = "TEMPORARY+" + type
183 return "<SMBShare %s [%s]%s = %s>" % (
184 self.name,
185 type,
186 self.remark and (" '%s'" % self.remark) or "",
187 str(self.path),
188 )
189
190
191# The SMB Automaton
192
193
194class SMB_Server(Automaton):
195 """
196 SMB server automaton
197
198 :param shares: the shares to serve. By default, share nothing.
199 Note that IPC$ is appended.
200 :param ssp: the SSP to use
201
202 All other options (in caps) are optional, and SMB specific:
203
204 :param ANONYMOUS_LOGIN: mark the clients as anonymous
205 :param GUEST_LOGIN: mark the clients as guest
206 :param REQUIRE_SIGNATURE: set 'Require Signature'
207 :param REQUIRE_ENCRYPTION: globally require encryption.
208 You could also make it share-specific on 3.1.1.
209 :param MAX_DIALECT: maximum SMB dialect. Defaults to 0x0311 (3.1.1)
210 :param TREE_SHARE_FLAGS: flags to announce on Tree_Connect_Response
211 :param TREE_CAPABILITIES: capabilities to announce on Tree_Connect_Response
212 :param TREE_MAXIMAL_ACCESS: maximal access to announce on Tree_Connect_Response
213 :param FILE_MAXIMAL_ACCESS: maximal access to announce in MxAc Create Context
214 """
215
216 pkt_cls = DirectTCP
217 socketcls = SMBStreamSocket
218
219 def __init__(self, shares=[], ssp=None, verb=True, readonly=True, *args, **kwargs):
220 self.verb = verb
221 if "sock" not in kwargs:
222 raise ValueError(
223 "SMB_Server cannot be started directly ! Use SMB_Server.spawn"
224 )
225 # Various SMB server arguments
226 self.ANONYMOUS_LOGIN = kwargs.pop("ANONYMOUS_LOGIN", False)
227 self.GUEST_LOGIN = kwargs.pop("GUEST_LOGIN", None)
228 self.REQUIRE_SIGNATURE = kwargs.pop("REQUIRE_SIGNATURE", None)
229 self.REQUIRE_ENCRYPTION = kwargs.pop("REQUIRE_ENCRYPTION", False)
230 self.MAX_DIALECT = kwargs.pop("MAX_DIALECT", 0x0311)
231 self.TREE_SHARE_FLAGS = kwargs.pop(
232 "TREE_SHARE_FLAGS", "FORCE_LEVELII_OPLOCK+RESTRICT_EXCLUSIVE_OPENS"
233 )
234 self.TREE_CAPABILITIES = kwargs.pop("TREE_CAPABILITIES", 0)
235 self.TREE_MAXIMAL_ACCESS = kwargs.pop(
236 "TREE_MAXIMAL_ACCESS",
237 "+".join(
238 [
239 "FILE_READ_DATA",
240 "FILE_WRITE_DATA",
241 "FILE_APPEND_DATA",
242 "FILE_READ_EA",
243 "FILE_WRITE_EA",
244 "FILE_EXECUTE",
245 "FILE_DELETE_CHILD",
246 "FILE_READ_ATTRIBUTES",
247 "FILE_WRITE_ATTRIBUTES",
248 "DELETE",
249 "READ_CONTROL",
250 "WRITE_DAC",
251 "WRITE_OWNER",
252 "SYNCHRONIZE",
253 ]
254 ),
255 )
256 self.FILE_MAXIMAL_ACCESS = kwargs.pop(
257 # Read-only
258 "FILE_MAXIMAL_ACCESS",
259 "+".join(
260 [
261 "FILE_READ_DATA",
262 "FILE_READ_EA",
263 "FILE_EXECUTE",
264 "FILE_READ_ATTRIBUTES",
265 "READ_CONTROL",
266 "SYNCHRONIZE",
267 ]
268 ),
269 )
270 self.LOCAL_IPS = kwargs.pop(
271 "LOCAL_IPS", [get_if_addr(kwargs.get("iface", conf.iface) or conf.iface)]
272 )
273 self.DOMAIN_REFERRALS = kwargs.pop("DOMAIN_REFERRALS", [])
274 self.readonly = readonly
275 # We don't want to update the parent shares argument
276 self.shares = shares.copy()
277 # Append the IPC$ share
278 self.shares.append(
279 SMBShare(
280 name="IPC$",
281 type=0x80000003, # SPECIAL+IPC
282 remark="Remote IPC",
283 )
284 )
285 # Initialize the DCE/RPC server for SMB
286 self.rpc_server = SMB_DCERPC_Server(
287 DCERPC_Transport.NCACN_NP,
288 shares=self.shares,
289 verb=self.verb,
290 )
291 # Extend it if another DCE/RPC server is provided
292 if "DCERPC_SERVER_CLS" in kwargs:
293 self.rpc_server.extend(kwargs.pop("DCERPC_SERVER_CLS"))
294 # Internal Session information
295 self.NegotiateCapabilities = None
296 self.GUID = RandUUID()._fix()
297 self.NextForceSign = False
298 self.NextForceEncrypt = False
299
300 # Credits/Sequence handling
301 self.MaxCreditCount = 2048 # [MS-SMB2] note: windows max default
302 self.ClientCreditCount = 1
303 self.SequenceWindow = (0, 0)
304 self.SequenceNumbers = set([0]) # keep track of allowed MIDs
305
306 # Compounds are handled on receiving by the StreamSocket,
307 # and on aggregated in a CompoundQueue to be sent in one go
308 self.NextCompound = False
309 self.CompoundedHandle = None
310 # SSP provider
311 if ssp is None:
312 # No SSP => fallback on NTLM with guest
313 ssp = SPNEGOSSP(
314 [
315 NTLMSSP(
316 USE_MIC=False,
317 DO_NOT_CHECK_LOGIN=True,
318 ),
319 ]
320 )
321 if self.GUEST_LOGIN is None:
322 self.GUEST_LOGIN = True
323 # Initialize
324 Automaton.__init__(self, *args, **kwargs)
325 # Set session options
326 self.session.ssp = ssp
327 self.session.SigningRequired = (
328 self.REQUIRE_SIGNATURE if self.REQUIRE_SIGNATURE is not None else bool(ssp)
329 )
330
331 @property
332 def session(self):
333 # session shorthand
334 return self.sock.session
335
336 def vprint(self, s=""):
337 """
338 Verbose print (if enabled)
339 """
340 if self.verb:
341 if conf.interactive:
342 log_interactive.info("> %s", s)
343 else:
344 print("> %s" % s)
345
346 def send(self, pkt):
347 ForceSign, ForceEncrypt = self.NextForceSign, self.NextForceEncrypt
348 self.NextForceSign = self.NextForceEncrypt = False
349 return super(SMB_Server, self).send(
350 pkt,
351 Compounded=self.NextCompound,
352 ForceSign=ForceSign,
353 ForceEncrypt=ForceEncrypt,
354 )
355
356 @ATMT.state(initial=1)
357 def BEGIN(self):
358 self.authenticated = False
359
360 @ATMT.receive_condition(BEGIN)
361 def received_negotiate_smb1(self, pkt):
362 if SMBNegotiate_Request in pkt:
363 raise self.NEGOTIATED().action_parameters(pkt)
364
365 @ATMT.receive_condition(BEGIN)
366 def received_negotiate_smb2_begin(self, pkt):
367 if SMB2_Negotiate_Protocol_Request in pkt:
368 raise self.NEGOTIATED().action_parameters(pkt)
369
370 @ATMT.action(received_negotiate_smb2_begin)
371 def on_negotiate_smb2_begin(self, pkt):
372 self.on_negotiate(pkt)
373
374 @ATMT.action(received_negotiate_smb1)
375 def on_negotiate(self, pkt):
376 self.session.sspcontext, spnego_token = self.session.ssp.NegTokenInit2()
377
378 # Build SMB2 header
379 self.smb_header = DirectTCP() / SMB2_Header(
380 Flags="SMB2_FLAGS_SERVER_TO_REDIR",
381 CreditRequest=1,
382 CreditCharge=1,
383 )
384
385 if SMBNegotiate_Request in pkt:
386 # SMB1. We don't support anything else than a Multi-Protocol Negotiate.
387 # [MS-SMB2] 3.2.4.2.2.1 Multi-Protocol Negotiate
388
389 # Find a dialect matching SMB2, or error.
390 DialectIndexes = [
391 x.DialectString for x in pkt[SMBNegotiate_Request].Dialects
392 ]
393 for key, rev in [(b"SMB 2.???", 0x02FF), (b"SMB 2.002", 0x0202)]:
394 if key in DialectIndexes:
395 DialectRevision = rev
396 break
397 else:
398 # Error: client only supports SMB1. We must answer in SMB1.
399 resp = DirectTCP() / SMB_Header(
400 Command="SMB_COM_NEGOTIATE",
401 Status="STATUS_NOT_SUPPORTED",
402 Flags="REPLY+CASE_INSENSITIVE+CANONICALIZED_PATHS",
403 Flags2=(
404 "LONG_NAMES+EAS+NT_STATUS+SMB_SECURITY_SIGNATURE+"
405 "UNICODE+IS_LONG_NAME+EXTENDED_SECURITY"
406 ),
407 TID=pkt.TID,
408 MID=pkt.MID,
409 UID=pkt.UID,
410 PIDLow=pkt.PIDLow,
411 )
412 resp /= SMBSession_Null()
413 self.send(resp)
414 return
415
416 # Multi-Protocol Negotiate: allocate credit 1
417 self.SequenceWindow = (1, 1)
418 self.SequenceNumbers = set([1])
419
420 elif SMB2_Negotiate_Protocol_Request in pkt:
421 # SMB2
422 self.update_smbheader(pkt)
423
424 # Find common revisions
425 DialectRevisions = pkt[SMB2_Negotiate_Protocol_Request].Dialects
426 DialectRevisions = [x for x in DialectRevisions if x <= self.MAX_DIALECT]
427 DialectRevisions.sort(reverse=True)
428 if DialectRevisions:
429 DialectRevision = DialectRevisions[0]
430 if DialectRevision & 0xFF != 0xFF:
431 # Version isn't SMB X.???
432 self.session.Dialect = DialectRevision
433
434 # SecurityMode
435 if pkt.SecurityMode.SIGNING_REQUIRED:
436 self.session.SigningRequired = True
437
438 if DialectRevision is None:
439 # No common dialect found.
440 resp = self.smb_header.copy() / SMB2_Error_Response()
441 resp.Command = "SMB2_NEGOTIATE"
442 resp.Status = "STATUS_NOT_SUPPORTED"
443 self.send(resp)
444 return
445
446 # Capabilities: [MS-SMB2] 3.3.5.4
447 self.NegotiateCapabilities = "+".join(
448 [
449 "DFS",
450 "LEASING",
451 "LARGE_MTU",
452 ]
453 )
454 if DialectRevision >= 0x0300:
455 # "if Connection.Dialect belongs to the SMB 3.x dialect family,
456 # the server supports..."
457 self.NegotiateCapabilities += "+" + "+".join(
458 [
459 "MULTI_CHANNEL",
460 "PERSISTENT_HANDLES",
461 "DIRECTORY_LEASING",
462 "ENCRYPTION",
463 ]
464 )
465
466 # Build response
467 resp = self.smb_header.copy() / SMB2_Negotiate_Protocol_Response(
468 DialectRevision=DialectRevision,
469 SecurityMode=(
470 "SIGNING_ENABLED+SIGNING_REQUIRED"
471 if self.session.SigningRequired
472 else "SIGNING_ENABLED"
473 ),
474 ServerTime=(time.time() + 11644473600) * 1e7,
475 ServerStartTime=0,
476 MaxTransactionSize=65536,
477 MaxReadSize=65536,
478 MaxWriteSize=65536,
479 Capabilities=self.NegotiateCapabilities,
480 GUID=self.GUID,
481 )
482 # SMB >= 3.0.0
483 if DialectRevision >= 0x0300:
484 # [MS-SMB2] sect 3.3.5.3.1 note 253
485 resp.MaxTransactionSize = 0x800000
486 resp.MaxReadSize = 0x800000
487 resp.MaxWriteSize = 0x800000
488 # SMB 3.1.1
489 if DialectRevision >= 0x0311 and pkt.NegotiateContextsCount:
490 # Negotiate context-capabilities
491 for ngctx in pkt.NegotiateContexts:
492 if ngctx.ContextType == 0x0002:
493 # SMB2_ENCRYPTION_CAPABILITIES
494 for ciph in ngctx.Ciphers:
495 tciph = SMB2_ENCRYPTION_CIPHERS.get(ciph, None)
496 if tciph in self.session.SupportedCipherIds:
497 # Common !
498 self.session.CipherId = tciph
499 self.session.SupportsEncryption = True
500 break
501 elif ngctx.ContextType == 0x0008:
502 # SMB2_SIGNING_CAPABILITIES
503 for signalg in ngctx.SigningAlgorithms:
504 tsignalg = SMB2_SIGNING_ALGORITHMS.get(signalg, None)
505 if tsignalg in self.session.SupportedSigningAlgorithmIds:
506 # Common !
507 self.session.SigningAlgorithmId = tsignalg
508 break
509 # Send back the negotiated algorithms
510 resp.NegotiateContexts = [
511 # Preauth capabilities
512 SMB2_Negotiate_Context()
513 / SMB2_Preauth_Integrity_Capabilities(
514 # SHA-512 by default
515 HashAlgorithms=[self.session.PreauthIntegrityHashId],
516 Salt=self.session.Salt,
517 ),
518 # Encryption capabilities
519 SMB2_Negotiate_Context()
520 / SMB2_Encryption_Capabilities(
521 # AES-128-CCM by default
522 Ciphers=[self.session.CipherId],
523 ),
524 # Signing capabilities
525 SMB2_Negotiate_Context()
526 / SMB2_Signing_Capabilities(
527 # AES-128-CCM by default
528 SigningAlgorithms=[self.session.SigningAlgorithmId],
529 ),
530 ]
531
532 # Add security blob
533 resp.SecurityBlob = spnego_token
534
535 if SMB2_Negotiate_Protocol_Request in pkt:
536 # If required, compute sessions
537 self.session.computeSMBConnectionPreauth(
538 bytes(pkt[SMB2_Header]), # nego request
539 bytes(resp[SMB2_Header]), # nego response
540 )
541
542 self.send(resp)
543
544 @ATMT.state(error=1)
545 def NEGO_FAILED(self):
546 self.vprint("SMB Negotiate failed: encryption was not negotiated.")
547 self.end()
548
549 @ATMT.state()
550 def NEGOTIATED(self):
551 pass
552
553 @ATMT.state(error=1)
554 def INVALID_SEQUENCE_WINDOW(self, MID, CreditCharge):
555 self.vprint(
556 "SMB: Invalid sequence [%s:%s] in %s. (%s)"
557 % (
558 MID,
559 MID + CreditCharge - 1,
560 repr(self.SequenceWindow),
561 repr(self.SequenceNumbers),
562 )
563 )
564 self.end()
565
566 @ATMT.state(error=1)
567 def INSUFFICIENT_CREDITS(self):
568 self.vprint("SMB Negotiate failed: encryption was not negotiated.")
569 self.end()
570
571 def update_smbheader(self, pkt):
572 """
573 Called when receiving a SMB2 packet to update the current smb_header
574 """
575 # [MS-SMB2] sect 3.3.1.1 - Algorithm for Handling MIDs
576 MID = pkt.MID
577 if self.session.Dialect >= 0x0210:
578 # SMB 2.1.0+ - Credits
579 CreditCharge = pkt.CreditCharge
580 Consumed = range(MID, MID + CreditCharge)
581 if (
582 (
583 CreditCharge <= 0
584 and not isinstance(
585 pkt.payload.payload, SMB2_Negotiate_Protocol_Request
586 )
587 )
588 or CreditCharge >= self.MaxCreditCount
589 or not (self.SequenceWindow[0] <= MID <= self.SequenceWindow[1])
590 or not self.SequenceNumbers.issuperset(Consumed)
591 ):
592 raise self.INVALID_SEQUENCE_WINDOW(MID, CreditCharge)
593
594 # [MS-SMB2] sect 3.3.1.2 - Algorithm for the Granting of Credits
595 CreditGranted = min(
596 pkt.CreditRequest, self.MaxCreditCount - self.ClientCreditCount
597 )
598 if (
599 self.SequenceWindow[1] - self.SequenceWindow[0]
600 >= 2 * self.ClientCreditCount
601 ):
602 # "the server will not allow the difference between the smallest
603 # available sequence number and the largest available sequence number
604 # to exceed 2*[Credit Granted]"
605 CreditGranted = 0
606 self.smb_header.CreditRequest = CreditGranted
607 self.ClientCreditCount += CreditGranted
608 self.ClientCreditCount -= CreditCharge
609 if self.ClientCreditCount <= 0:
610 raise self.INSUFFICIENT_CREDITS()
611
612 else:
613 # SMB 2.0.2 - No credits
614 if not (self.SequenceWindow[0] <= MID <= self.SequenceWindow[1]):
615 raise self.INVALID_SEQUENCE_WINDOW()
616 CreditGranted = 1
617 Consumed = [MID]
618
619 # Update allowed sequence numbers (protect against replay)
620 self.SequenceNumbers -= set(Consumed)
621
622 # Store granted sequence numbers
623 self.SequenceNumbers |= set(
624 range(
625 self.SequenceWindow[1] + 1,
626 self.SequenceWindow[1] + 1 + CreditGranted,
627 )
628 )
629 # And update sequence window
630 self.SequenceWindow = (
631 min(self.SequenceNumbers),
632 self.SequenceWindow[1] + CreditGranted,
633 )
634
635 # [MS-SMB2] sect 3.3.4.1
636 # "the server SHOULD set the CreditCharge field in the SMB2 header
637 # of the response to the CreditCharge value in the SMB2 header of the request."
638 self.smb_header.CreditCharge = pkt.CreditCharge
639 # TODO: check that the announced CreditCharge is correct for the message.
640 # Right now we trust the client.
641
642 # If the packet has a NextCommand, set NextCompound to True
643 self.NextCompound = bool(pkt.NextCommand)
644 # [MS-SMB2] sect 3.3.4.1.1 - "If the request was signed by the client..."
645 # If the packet was signed, note we must answer with a signed packet.
646 if (
647 not self.session.SigningRequired
648 and pkt.SecuritySignature != b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
649 ):
650 self.NextForceSign = True
651 # [MS-SMB2] sect 3.3.4.1.4 - "If the message being sent is any response to a
652 # client request for which Request.IsEncrypted is TRUE"
653 if pkt[SMB2_Header]._decrypted:
654 self.NextForceEncrypt = True
655
656 # [MS-SMB2] sect 3.3.5.2.7.2
657 # Add SMB2_FLAGS_RELATED_OPERATIONS to the response if present
658 if pkt.Flags.SMB2_FLAGS_RELATED_OPERATIONS:
659 self.smb_header.Flags += "SMB2_FLAGS_RELATED_OPERATIONS"
660 else:
661 self.smb_header.Flags -= "SMB2_FLAGS_RELATED_OPERATIONS"
662
663 # [MS-SMB2] sect 2.2.1.2 - Priority
664 if (self.session.Dialect or 0) >= 0x0311:
665 self.smb_header.Flags &= 0xFF8F
666 self.smb_header.Flags |= int(pkt.Flags) & 0x70
667
668 # Update IDs
669 self.smb_header.SessionId = pkt.SessionId
670 self.smb_header.TID = pkt.TID
671 self.smb_header.MID = pkt.MID
672 self.smb_header.PID = pkt.PID
673
674 @ATMT.receive_condition(NEGOTIATED)
675 def received_negotiate_smb2(self, pkt):
676 if SMB2_Negotiate_Protocol_Request in pkt:
677 raise self.NEGOTIATED().action_parameters(pkt)
678
679 @ATMT.action(received_negotiate_smb2)
680 def on_negotiate_smb2(self, pkt):
681 self.on_negotiate(pkt)
682
683 @ATMT.state(error=1)
684 def INVALID_SMB_VERSION(self):
685 log_runtime.warning("Tree request in SMB1: unimplemented. Quit")
686 self.end()
687
688 @ATMT.receive_condition(NEGOTIATED)
689 def receive_setup_andx_request(self, pkt):
690 if SMB2_Session_Setup_Request in pkt:
691 # SMB2
692 ssp_blob = pkt.SecurityBlob
693 raise self.RECEIVED_SETUP_ANDX_REQUEST().action_parameters(pkt, ssp_blob)
694 if (
695 SMBSession_Setup_AndX_Request_Extended_Security in pkt
696 or SMBSession_Setup_AndX_Request in pkt
697 ):
698 raise self.INVALID_SMB_VERSION()
699
700 @ATMT.state()
701 def RECEIVED_SETUP_ANDX_REQUEST(self):
702 pass
703
704 @ATMT.action(receive_setup_andx_request)
705 def on_setup_andx_request(self, pkt, ssp_blob):
706 self.session.sspcontext, tok, status = self.session.ssp.GSS_Accept_sec_context(
707 self.session.sspcontext,
708 ssp_blob,
709 )
710 self.update_smbheader(pkt)
711 self.smb_header.SessionId = 0x0001000000000015
712 if status not in [GSS_S_CONTINUE_NEEDED, GSS_S_COMPLETE]:
713 # Error
714 resp = self.smb_header.copy() / SMB2_Session_Setup_Response()
715 # Map some GSS return codes to NTStatus
716 if status == GSS_S_CREDENTIALS_EXPIRED:
717 resp.Status = "STATUS_PASSWORD_EXPIRED"
718 else:
719 resp.Status = "STATUS_LOGON_FAILURE"
720 # Reset Session preauth (SMB 3.1.1)
721 self.session.SessionPreauthIntegrityHashValue = None
722 else:
723 # Negotiation
724 resp = self.smb_header.copy() / SMB2_Session_Setup_Response()
725 if self.GUEST_LOGIN:
726 # "If the security subsystem indicates that the session
727 # was established by a guest user, Session.SigningRequired
728 # MUST be set to FALSE and Session.IsGuest MUST be set to TRUE."
729 resp.SessionFlags = "IS_GUEST"
730 self.session.IsGuest = True
731 self.session.SigningRequired = False
732 if self.ANONYMOUS_LOGIN:
733 resp.SessionFlags = "IS_NULL"
734 # [MS-SMB2] sect 3.3.5.5.3
735 if self.session.Dialect >= 0x0300 and self.REQUIRE_ENCRYPTION:
736 resp.SessionFlags += "ENCRYPT_DATA"
737 resp.Status = 0x0 if (status == GSS_S_COMPLETE) else 0xC0000016
738
739 # Set security blob (if any)
740 resp.SecurityBlob = tok
741
742 # We have a response. If required, compute sessions
743 if status == GSS_S_CONTINUE_NEEDED:
744 # the setup session response is used in hash
745 self.session.computeSMBSessionPreauth(
746 bytes(pkt[SMB2_Header]), # session setup request
747 bytes(resp[SMB2_Header]), # session setup response
748 )
749 else:
750 # the setup session response is not used in hash
751 self.session.computeSMBSessionPreauth(
752 bytes(pkt[SMB2_Header]), # session setup request
753 )
754 if status == GSS_S_COMPLETE:
755 # Authentication was successful
756 self.session.computeSMBSessionKeys(IsClient=False)
757 self.authenticated = True
758 # [MS-SMB2] Note: "Windows-based servers always sign the final session setup
759 # response when the user is neither anonymous nor guest."
760 # If not available, it will still be ignored.
761 self.NextForceSign = True
762 self.send(resp)
763 # Check whether we must enable encryption from now on
764 if (
765 self.authenticated
766 and not self.session.IsGuest
767 and self.session.Dialect >= 0x0300
768 and self.REQUIRE_ENCRYPTION
769 ):
770 # [MS-SMB2] sect 3.3.5.5.3: from now on, turn encryption on !
771 self.session.EncryptData = True
772 self.session.SigningRequired = False
773
774 @ATMT.condition(RECEIVED_SETUP_ANDX_REQUEST)
775 def wait_for_next_request(self):
776 if self.authenticated:
777 self.vprint(
778 "User authenticated %s!" % (self.GUEST_LOGIN and " as guest" or "")
779 )
780 raise self.AUTHENTICATED()
781 else:
782 raise self.NEGOTIATED()
783
784 @ATMT.state()
785 def AUTHENTICATED(self):
786 """Dev: overload this"""
787 pass
788
789 # DEV: add a condition on AUTHENTICATED with prio=0
790
791 @ATMT.condition(AUTHENTICATED, prio=1)
792 def should_serve(self):
793 # Serve files
794 self.current_trees = {}
795 self.current_handles = {}
796 self.enumerate_index = {} # used for query directory enumeration
797 self.tree_id = 0
798 self.base_time_t = self.current_smb_time()
799 raise self.SERVING()
800
801 def _ioctl_error(self, Status="STATUS_NOT_SUPPORTED"):
802 pkt = self.smb_header.copy() / SMB2_Error_Response(ErrorData=b"\xff")
803 pkt.Status = Status
804 pkt.Command = "SMB2_IOCTL"
805 self.send(pkt)
806
807 @ATMT.state(final=1)
808 def END(self):
809 self.end()
810
811 # SERVE FILES
812
813 def current_tree(self):
814 """
815 Return the current tree name
816 """
817 return self.current_trees[self.smb_header.TID]
818
819 def root_path(self):
820 """
821 Return the root path of the current tree
822 """
823 curtree = self.current_tree()
824 try:
825 share_path = next(x.path for x in self.shares if x._name == curtree.lower())
826 except StopIteration:
827 return None
828 return pathlib.Path(share_path).resolve()
829
830 @ATMT.state()
831 def SERVING(self):
832 """
833 Main state when serving files
834 """
835 pass
836
837 @ATMT.receive_condition(SERVING)
838 def receive_logoff_request(self, pkt):
839 if SMB2_Session_Logoff_Request in pkt:
840 raise self.NEGOTIATED().action_parameters(pkt)
841
842 @ATMT.action(receive_logoff_request)
843 def send_logoff_response(self, pkt):
844 self.update_smbheader(pkt)
845 self.send(self.smb_header.copy() / SMB2_Session_Logoff_Response())
846
847 @ATMT.receive_condition(SERVING)
848 def receive_setup_andx_request_in_serving(self, pkt):
849 self.receive_setup_andx_request(pkt)
850
851 @ATMT.receive_condition(SERVING)
852 def receive_tree_connect(self, pkt):
853 if SMB2_Tree_Connect_Request in pkt:
854 tree_name = pkt[SMB2_Tree_Connect_Request].Path.split("\\")[-1]
855 raise self.SERVING().action_parameters(pkt, tree_name)
856
857 @ATMT.action(receive_tree_connect)
858 def send_tree_connect_response(self, pkt, tree_name):
859 self.update_smbheader(pkt)
860 # Check the tree name against the shares we're serving
861 try:
862 share = next(x for x in self.shares if x._name == tree_name.lower())
863 tree_name = share.name # normalize
864 except StopIteration:
865 # Unknown tree
866 resp = self.smb_header.copy() / SMB2_Error_Response()
867 resp.Command = "SMB2_TREE_CONNECT"
868 resp.Status = "STATUS_BAD_NETWORK_NAME"
869 self.send(resp)
870 return
871 # Add tree to current trees
872 if tree_name not in self.current_trees:
873 self.tree_id += 1
874 self.smb_header.TID = self.tree_id
875 self.current_trees[self.smb_header.TID] = tree_name
876
877 # Construct ShareFlags
878 ShareFlags = (
879 "AUTO_CACHING+NO_CACHING"
880 if self.current_tree() == "IPC$"
881 else self.TREE_SHARE_FLAGS
882 )
883 # [MS-SMB2] sect 3.3.5.7
884 if (
885 self.session.Dialect >= 0x0311
886 and not self.session.EncryptData
887 and share.encryptdata
888 ):
889 if not self.session.SupportsEncryption:
890 raise Exception("Peer asked for encryption but doesn't support it !")
891 ShareFlags += "+ENCRYPT_DATA"
892
893 self.vprint("Tree Connect on: %s" % tree_name)
894 self.send(
895 self.smb_header.copy()
896 / SMB2_Tree_Connect_Response(
897 ShareType="PIPE" if self.current_tree() == "IPC$" else "DISK",
898 ShareFlags=ShareFlags,
899 Capabilities=(
900 0 if self.current_tree() == "IPC$" else self.TREE_CAPABILITIES
901 ),
902 MaximalAccess=self.TREE_MAXIMAL_ACCESS,
903 )
904 )
905
906 @ATMT.receive_condition(SERVING)
907 def receive_ioctl(self, pkt):
908 if SMB2_IOCTL_Request in pkt:
909 raise self.SERVING().action_parameters(pkt)
910
911 @ATMT.action(receive_ioctl)
912 def send_ioctl_response(self, pkt):
913 self.update_smbheader(pkt)
914 if pkt.CtlCode == 0x11C017:
915 # FSCTL_PIPE_TRANSCEIVE
916 self.rpc_server.recv(pkt.Input.load)
917 self.send(
918 self.smb_header.copy()
919 / SMB2_IOCTL_Response(
920 CtlCode=0x11C017,
921 FileId=pkt[SMB2_IOCTL_Request].FileId,
922 Buffer=[("Output", self.rpc_server.get_response())],
923 )
924 )
925 elif pkt.CtlCode == 0x00140204 and self.session.sspcontext.SessionKey:
926 # FSCTL_VALIDATE_NEGOTIATE_INFO
927 # This is a security measure asking the server to validate
928 # what flags were negotiated during the SMBNegotiate exchange.
929 # This packet is ALWAYS signed, and expects a signed response.
930
931 # https://docs.microsoft.com/en-us/archive/blogs/openspecification/smb3-secure-dialect-negotiation
932 # > "Down-level servers (pre-Windows 2012) will return
933 # > STATUS_NOT_SUPPORTED or STATUS_INVALID_DEVICE_REQUEST
934 # > since they do not allow or implement
935 # > FSCTL_VALIDATE_NEGOTIATE_INFO.
936 # > The client should accept the
937 # > response provided it's properly signed".
938
939 if (self.session.Dialect or 0) < 0x0300:
940 # SMB < 3 isn't supposed to support FSCTL_VALIDATE_NEGOTIATE_INFO
941 self._ioctl_error(Status="STATUS_FILE_CLOSED")
942 return
943
944 # SMB3
945 self.send(
946 self.smb_header.copy()
947 / SMB2_IOCTL_Response(
948 CtlCode=0x00140204,
949 FileId=pkt[SMB2_IOCTL_Request].FileId,
950 Buffer=[
951 (
952 "Output",
953 SMB2_IOCTL_Validate_Negotiate_Info_Response(
954 GUID=self.GUID,
955 DialectRevision=self.session.Dialect,
956 SecurityMode=(
957 "SIGNING_ENABLED+SIGNING_REQUIRED"
958 if self.session.SigningRequired
959 else "SIGNING_ENABLED"
960 ),
961 Capabilities=self.NegotiateCapabilities,
962 ),
963 )
964 ],
965 )
966 )
967 elif pkt.CtlCode == 0x001401FC:
968 # FSCTL_QUERY_NETWORK_INTERFACE_INFO
969 self.send(
970 self.smb_header.copy()
971 / SMB2_IOCTL_Response(
972 CtlCode=0x001401FC,
973 FileId=pkt[SMB2_IOCTL_Request].FileId,
974 Output=SMB2_IOCTL_Network_Interface_Info(
975 interfaces=[
976 NETWORK_INTERFACE_INFO(
977 SockAddr_Storage=SOCKADDR_STORAGE(
978 Family=0x0002,
979 IPv4Adddress=x,
980 )
981 )
982 for x in self.LOCAL_IPS
983 ]
984 ),
985 )
986 )
987 elif pkt.CtlCode == 0x00060194:
988 # FSCTL_DFS_GET_REFERRALS
989 if (
990 self.DOMAIN_REFERRALS
991 and not pkt[SMB2_IOCTL_Request].Input.RequestFileName
992 ):
993 # Requesting domain referrals
994 self.send(
995 self.smb_header.copy()
996 / SMB2_IOCTL_Response(
997 CtlCode=0x00060194,
998 FileId=pkt[SMB2_IOCTL_Request].FileId,
999 Output=SMB2_IOCTL_RESP_GET_DFS_Referral(
1000 ReferralEntries=[
1001 DFS_REFERRAL_V3(
1002 ReferralEntryFlags="NameListReferral",
1003 TimeToLive=600,
1004 )
1005 for _ in self.DOMAIN_REFERRALS
1006 ],
1007 ReferralBuffer=[
1008 DFS_REFERRAL_ENTRY1(SpecialName=name)
1009 for name in self.DOMAIN_REFERRALS
1010 ],
1011 ),
1012 )
1013 )
1014 return
1015 resp = self.smb_header.copy() / SMB2_Error_Response()
1016 resp.Command = "SMB2_IOCTL"
1017 resp.Status = "STATUS_FS_DRIVER_REQUIRED"
1018 self.send(resp)
1019 else:
1020 # Among other things, FSCTL_VALIDATE_NEGOTIATE_INFO
1021 self._ioctl_error(Status="STATUS_NOT_SUPPORTED")
1022
1023 @ATMT.receive_condition(SERVING)
1024 def receive_create_file(self, pkt):
1025 if SMB2_Create_Request in pkt:
1026 raise self.SERVING().action_parameters(pkt)
1027
1028 PIPES_TABLE = {
1029 "srvsvc": SMB2_FILEID(Persistent=0x4000000012, Volatile=0x4000000001),
1030 "wkssvc": SMB2_FILEID(Persistent=0x4000000013, Volatile=0x4000000002),
1031 "NETLOGON": SMB2_FILEID(Persistent=0x4000000014, Volatile=0x4000000003),
1032 }
1033
1034 # special handle in case of compounded requests ([MS-SMB2] 3.2.4.1.4)
1035 # that points to the chained opened file handle
1036 LAST_HANDLE = SMB2_FILEID(
1037 Persistent=0xFFFFFFFFFFFFFFFF, Volatile=0xFFFFFFFFFFFFFFFF
1038 )
1039
1040 def current_smb_time(self):
1041 return (
1042 FileNetworkOpenInformation().get_field("CreationTime").i2m(None, None)
1043 - 864000000000 # one day ago
1044 )
1045
1046 def make_file_id(self, fname):
1047 """
1048 Generate deterministic FileId based on the fname
1049 """
1050 hash = hashlib.md5((fname or "").encode()).digest()
1051 return 0x4000000000 | struct.unpack("<I", hash[:4])[0]
1052
1053 def lookup_file(self, fname, durable_handle=None, create=False, createOptions=None):
1054 """
1055 Lookup the file and build it's SMB2_FILEID
1056 """
1057 root = self.root_path()
1058 if isinstance(fname, pathlib.Path):
1059 path = fname
1060 fname = path.name
1061 else:
1062 path = root / (fname or "").replace("\\", "/")
1063 path = path.resolve()
1064 # Word of caution: this check ONLY works because root and path have been
1065 # resolve(). Be careful
1066 # Note: symbolic links are currently unsupported.
1067 if root not in path.parents and path != root:
1068 raise FileNotFoundError
1069 if isreserved(path):
1070 raise FileNotFoundError
1071 if not path.exists():
1072 if create and createOptions:
1073 if createOptions.FILE_DIRECTORY_FILE:
1074 # Folder creation
1075 path.mkdir()
1076 self.vprint("Created folder:" + fname)
1077 else:
1078 # File creation
1079 path.touch()
1080 self.vprint("Created file:" + fname)
1081 else:
1082 raise FileNotFoundError
1083 if durable_handle is None:
1084 handle = SMB2_FILEID(
1085 Persistent=self.make_file_id(fname) + self.smb_header.MID,
1086 )
1087 else:
1088 # We were given a durable handle. Use it
1089 handle = durable_handle
1090 attrs = {
1091 "CreationTime": self.base_time_t,
1092 "LastAccessTime": self.base_time_t,
1093 "LastWriteTime": self.base_time_t,
1094 "ChangeTime": self.base_time_t,
1095 "EndOfFile": 0,
1096 "AllocationSize": 0,
1097 }
1098 path_stat = path.stat()
1099 attrs["EndOfFile"] = attrs["AllocationSize"] = path_stat.st_size
1100 if fname is None:
1101 # special case
1102 attrs["FileAttributes"] = "+".join(
1103 [
1104 "FILE_ATTRIBUTE_HIDDEN",
1105 "FILE_ATTRIBUTE_SYSTEM",
1106 "FILE_ATTRIBUTE_DIRECTORY",
1107 ]
1108 )
1109 elif path.is_dir():
1110 attrs["FileAttributes"] = "FILE_ATTRIBUTE_DIRECTORY"
1111 else:
1112 attrs["FileAttributes"] = "FILE_ATTRIBUTE_ARCHIVE"
1113 self.current_handles[handle] = (
1114 path, # file path
1115 attrs, # file attributes
1116 )
1117 self.enumerate_index[handle] = 0
1118 return handle
1119
1120 def set_compounded_handle(self, handle):
1121 """
1122 Mark a handle as the current one being compounded.
1123 """
1124 self.CompoundedHandle = handle
1125
1126 def get_file_id(self, pkt):
1127 """
1128 Return the FileId attribute of pkt, accounting for compounded requests.
1129 """
1130 fid = pkt.FileId
1131 if fid == self.LAST_HANDLE:
1132 return self.CompoundedHandle
1133 return fid
1134
1135 def lookup_folder(self, handle, filter, offset, cls):
1136 """
1137 Lookup a folder handle
1138 """
1139 path = self.current_handles[handle][0]
1140 self.vprint("Query directory: " + str(path))
1141 self.current_handles[handle][1]["LastAccessTime"] = self.current_smb_time()
1142 if not path.is_dir():
1143 raise NotADirectoryError
1144 return sorted(
1145 [
1146 cls(FileName=x.name, **self.current_handles[self.lookup_file(x)][1])
1147 for x in path.glob(filter)
1148 # Note: symbolic links are unsupported because it's hard to check
1149 # for path traversal on them.
1150 if not x.is_symlink()
1151 ]
1152 + [
1153 cls(
1154 FileAttributes=("FILE_ATTRIBUTE_DIRECTORY"),
1155 FileName=".",
1156 )
1157 ]
1158 + (
1159 [
1160 cls(
1161 FileAttributes=("FILE_ATTRIBUTE_DIRECTORY"),
1162 FileName="..",
1163 )
1164 ]
1165 if path.resolve() != self.root_path()
1166 else []
1167 ),
1168 key=lambda x: x.FileName,
1169 )[offset:]
1170
1171 @ATMT.action(receive_create_file)
1172 def send_create_file_response(self, pkt):
1173 """
1174 Handle CreateFile request
1175
1176 See [MS-SMB2] 3.3.5.9 ()
1177 """
1178 self.update_smbheader(pkt)
1179 if pkt[SMB2_Create_Request].NameLen:
1180 fname = pkt[SMB2_Create_Request].Name
1181 else:
1182 fname = None
1183 if fname:
1184 self.vprint("Opened: " + fname)
1185 if self.current_tree() == "IPC$":
1186 # Special IPC$ case: opening a pipe
1187 FILE_ID = self.PIPES_TABLE.get(fname, None)
1188 if FILE_ID:
1189 attrs = {
1190 "CreationTime": 0,
1191 "LastAccessTime": 0,
1192 "LastWriteTime": 0,
1193 "ChangeTime": 0,
1194 "EndOfFile": 0,
1195 "AllocationSize": 4096,
1196 }
1197 self.current_handles[FILE_ID] = (
1198 fname,
1199 attrs,
1200 )
1201 self.send(
1202 self.smb_header.copy()
1203 / SMB2_Create_Response(
1204 OplockLevel=pkt.RequestedOplockLevel,
1205 FileId=FILE_ID,
1206 **attrs,
1207 )
1208 )
1209 else:
1210 # NOT_FOUND
1211 resp = self.smb_header.copy() / SMB2_Error_Response()
1212 resp.Command = "SMB2_CREATE"
1213 resp.Status = "STATUS_OBJECT_NAME_NOT_FOUND"
1214 self.send(resp)
1215 return
1216 else:
1217 # Check if there is a Durable Handle Reconnect Request
1218 durable_handle = None
1219 if pkt[SMB2_Create_Request].CreateContextsLen:
1220 try:
1221 durable_handle = next(
1222 x.Data.FileId
1223 for x in pkt[SMB2_Create_Request].CreateContexts
1224 if x.Name == b"DH2C"
1225 )
1226 except StopIteration:
1227 pass
1228 # Lookup file handle
1229 try:
1230 handle = self.lookup_file(fname, durable_handle=durable_handle)
1231 except FileNotFoundError:
1232 # NOT_FOUND
1233 if pkt[SMB2_Create_Request].CreateDisposition in [
1234 0x00000002, # FILE_CREATE
1235 0x00000005, # FILE_OVERWRITE_IF
1236 ]:
1237 if self.readonly:
1238 resp = self.smb_header.copy() / SMB2_Error_Response()
1239 resp.Command = "SMB2_CREATE"
1240 resp.Status = "STATUS_ACCESS_DENIED"
1241 self.send(resp)
1242 return
1243 else:
1244 # Create file
1245 handle = self.lookup_file(
1246 fname,
1247 durable_handle=durable_handle,
1248 create=True,
1249 createOptions=pkt[SMB2_Create_Request].CreateOptions,
1250 )
1251 else:
1252 resp = self.smb_header.copy() / SMB2_Error_Response()
1253 resp.Command = "SMB2_CREATE"
1254 resp.Status = "STATUS_OBJECT_NAME_NOT_FOUND"
1255 self.send(resp)
1256 return
1257 # Store compounded handle
1258 self.set_compounded_handle(handle)
1259 # Build response
1260 attrs = self.current_handles[handle][1]
1261 resp = self.smb_header.copy() / SMB2_Create_Response(
1262 OplockLevel=pkt.RequestedOplockLevel,
1263 FileId=handle,
1264 **attrs,
1265 )
1266 # Handle the various chain elements
1267 if pkt[SMB2_Create_Request].CreateContextsLen:
1268 CreateContexts = []
1269 # Note: failing to provide context elements when the client asks for
1270 # them will make the windows implementation fall into a weird
1271 # "the-server-is-dumb" mode. So provide them 'quoi qu'il en coûte'.
1272 for elt in pkt[SMB2_Create_Request].CreateContexts:
1273 if elt.Name == b"QFid":
1274 # [MS-SMB2] sect 3.3.5.9.9
1275 CreateContexts.append(
1276 SMB2_Create_Context(
1277 Name=b"QFid",
1278 Data=SMB2_CREATE_QUERY_ON_DISK_ID(
1279 DiskFileId=self.make_file_id(fname),
1280 VolumeId=0xBA39CD11,
1281 ),
1282 )
1283 )
1284 elif elt.Name == b"MxAc":
1285 # [MS-SMB2] sect 3.3.5.9.5
1286 CreateContexts.append(
1287 SMB2_Create_Context(
1288 Name=b"MxAc",
1289 Data=SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE(
1290 QueryStatus=0,
1291 MaximalAccess=self.FILE_MAXIMAL_ACCESS,
1292 ),
1293 )
1294 )
1295 elif elt.Name == b"DH2Q":
1296 # [MS-SMB2] sect 3.3.5.9.10
1297 if "FILE_ATTRIBUTE_DIRECTORY" in attrs["FileAttributes"]:
1298 continue
1299 CreateContexts.append(
1300 SMB2_Create_Context(
1301 Name=b"DH2Q",
1302 Data=SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2(
1303 Timeout=180000
1304 ),
1305 )
1306 )
1307 elif elt.Name == b"RqLs":
1308 # [MS-SMB2] sect 3.3.5.9.11
1309 # TODO: hmm, we are probably supposed to do something here
1310 CreateContexts.append(
1311 SMB2_Create_Context(
1312 Name=b"RqLs",
1313 Data=elt.Data,
1314 )
1315 )
1316 resp.CreateContexts = CreateContexts
1317 self.send(resp)
1318
1319 @ATMT.receive_condition(SERVING)
1320 def receive_change_notify_info(self, pkt):
1321 if SMB2_Change_Notify_Request in pkt:
1322 raise self.SERVING().action_parameters(pkt)
1323
1324 @ATMT.action(receive_change_notify_info)
1325 def send_change_notify_info_response(self, pkt):
1326 # [MS-SMB2] sect 3.3.5.19
1327 # "If the underlying object store does not support change notifications, the
1328 # server MUST fail this request with STATUS_NOT_SUPPORTED."
1329 self.update_smbheader(pkt)
1330 resp = self.smb_header.copy() / SMB2_Error_Response()
1331 resp.Command = "SMB2_CHANGE_NOTIFY"
1332 # ScapyFS doesn't support notifications
1333 resp.Status = "STATUS_NOT_SUPPORTED"
1334 self.send(resp)
1335
1336 @ATMT.receive_condition(SERVING)
1337 def receive_query_directory_info(self, pkt):
1338 if SMB2_Query_Directory_Request in pkt:
1339 raise self.SERVING().action_parameters(pkt)
1340
1341 @ATMT.action(receive_query_directory_info)
1342 def send_query_directory_response(self, pkt):
1343 self.update_smbheader(pkt)
1344 if not pkt.FileNameLen:
1345 # this is broken.
1346 return
1347 query = pkt.FileName
1348 fid = self.get_file_id(pkt)
1349 # Check for handled FileInformationClass
1350 # 0x02: FileFullDirectoryInformation
1351 # 0x03: FileBothDirectoryInformation
1352 # 0x25: FileIdBothDirectoryInformation
1353 if pkt.FileInformationClass not in [0x02, 0x03, 0x25]:
1354 # Unknown FileInformationClass
1355 resp = self.smb_header.copy() / SMB2_Error_Response()
1356 resp.Command = "SMB2_QUERY_DIRECTORY"
1357 resp.Status = "STATUS_INVALID_INFO_CLASS"
1358 self.send(resp)
1359 return
1360 # Handle SMB2_RESTART_SCANS
1361 if pkt[SMB2_Query_Directory_Request].Flags.SMB2_RESTART_SCANS:
1362 self.enumerate_index[fid] = 0
1363 # Lookup the files
1364 try:
1365 files = self.lookup_folder(
1366 fid,
1367 query,
1368 self.enumerate_index[fid],
1369 {
1370 0x02: FILE_FULL_DIR_INFORMATION,
1371 0x03: FILE_BOTH_DIR_INFORMATION,
1372 0x25: FILE_ID_BOTH_DIR_INFORMATION,
1373 }[pkt.FileInformationClass],
1374 )
1375 except NotADirectoryError:
1376 resp = self.smb_header.copy() / SMB2_Error_Response()
1377 resp.Command = "SMB2_QUERY_DIRECTORY"
1378 resp.Status = "STATUS_INVALID_PARAMETER"
1379 self.send(resp)
1380 return
1381 if not files:
1382 # No more files !
1383 self.enumerate_index[fid] = 0
1384 resp = self.smb_header.copy() / SMB2_Error_Response()
1385 resp.Command = "SMB2_QUERY_DIRECTORY"
1386 resp.Status = "STATUS_NO_MORE_FILES"
1387 self.send(resp)
1388 return
1389 # Handle SMB2_RETURN_SINGLE_ENTRY
1390 if pkt[SMB2_Query_Directory_Request].Flags.SMB2_RETURN_SINGLE_ENTRY:
1391 files = files[:1]
1392 # Increment index
1393 self.enumerate_index[fid] += len(files)
1394 # Build response based on the FileInformationClass
1395 fileinfo = FileIdBothDirectoryInformation(
1396 files=files,
1397 )
1398 self.send(
1399 self.smb_header.copy()
1400 / SMB2_Query_Directory_Response(Buffer=[("Output", fileinfo)])
1401 )
1402
1403 @ATMT.receive_condition(SERVING)
1404 def receive_query_info(self, pkt):
1405 if SMB2_Query_Info_Request in pkt:
1406 raise self.SERVING().action_parameters(pkt)
1407
1408 @ATMT.action(receive_query_info)
1409 def send_query_info_response(self, pkt):
1410 self.update_smbheader(pkt)
1411 # [MS-FSCC] + [MS-SMB2] sect 2.2.37 / 3.3.5.20.1
1412 fid = self.get_file_id(pkt)
1413 if pkt.InfoType == 0x01: # SMB2_0_INFO_FILE
1414 if pkt.FileInfoClass == 0x05: # FileStandardInformation
1415 attrs = self.current_handles[fid][1]
1416 fileinfo = FileStandardInformation(
1417 EndOfFile=attrs["EndOfFile"],
1418 AllocationSize=attrs["AllocationSize"],
1419 )
1420 elif pkt.FileInfoClass == 0x06: # FileInternalInformation
1421 pth = self.current_handles[fid][0]
1422 fileinfo = FileInternalInformation(
1423 IndexNumber=hash(pth) & 0xFFFFFFFFFFFFFFFF,
1424 )
1425 elif pkt.FileInfoClass == 0x07: # FileEaInformation
1426 fileinfo = FileEaInformation()
1427 elif pkt.FileInfoClass == 0x12: # FileAllInformation
1428 attrs = self.current_handles[fid][1]
1429 fileinfo = FileAllInformation(
1430 BasicInformation=FileBasicInformation(
1431 CreationTime=attrs["CreationTime"],
1432 LastAccessTime=attrs["LastAccessTime"],
1433 LastWriteTime=attrs["LastWriteTime"],
1434 ChangeTime=attrs["ChangeTime"],
1435 FileAttributes=attrs["FileAttributes"],
1436 ),
1437 StandardInformation=FileStandardInformation(
1438 EndOfFile=attrs["EndOfFile"],
1439 AllocationSize=attrs["AllocationSize"],
1440 ),
1441 )
1442 elif pkt.FileInfoClass == 0x15: # FileAlternateNameInformation
1443 pth = self.current_handles[fid][0]
1444 fileinfo = FileAlternateNameInformation(
1445 FileName=pth.name,
1446 )
1447 elif pkt.FileInfoClass == 0x16: # FileStreamInformation
1448 attrs = self.current_handles[fid][1]
1449 fileinfo = FileStreamInformation(
1450 StreamSize=attrs["EndOfFile"],
1451 StreamAllocationSize=attrs["AllocationSize"],
1452 )
1453 elif pkt.FileInfoClass == 0x22: # FileNetworkOpenInformation
1454 attrs = self.current_handles[fid][1]
1455 fileinfo = FileNetworkOpenInformation(
1456 **attrs,
1457 )
1458 elif pkt.FileInfoClass == 0x30: # FileNormalizedNameInformation
1459 pth = self.current_handles[fid][0]
1460 fileinfo = FILE_NAME_INFORMATION(
1461 FileName=pth.name,
1462 )
1463 else:
1464 log_runtime.warning(
1465 "Unimplemented: %s"
1466 % pkt[SMB2_Query_Info_Request].sprintf("%InfoType% %FileInfoClass%")
1467 )
1468 return
1469 elif pkt.InfoType == 0x02: # SMB2_0_INFO_FILESYSTEM
1470 # [MS-FSCC] sect 2.5
1471 if pkt.FileInfoClass == 0x01: # FileFsVolumeInformation
1472 fileinfo = FileFsVolumeInformation()
1473 elif pkt.FileInfoClass == 0x03: # FileFsSizeInformation
1474 fileinfo = FileFsSizeInformation()
1475 elif pkt.FileInfoClass == 0x05: # FileFsAttributeInformation
1476 fileinfo = FileFsAttributeInformation(
1477 FileSystemAttributes=0x88000F,
1478 )
1479 elif pkt.FileInfoClass == 0x07: # FileEaInformation
1480 fileinfo = FileEaInformation()
1481 else:
1482 log_runtime.warning(
1483 "Unimplemented: %s"
1484 % pkt[SMB2_Query_Info_Request].sprintf("%InfoType% %FileInfoClass%")
1485 )
1486 return
1487 elif pkt.InfoType == 0x03: # SMB2_0_INFO_SECURITY
1488 # [MS-FSCC] 2.4.6
1489 fileinfo = SECURITY_DESCRIPTOR()
1490 # TODO: fill it
1491 if pkt.AdditionalInformation.OWNER_SECURITY_INFORMATION:
1492 pass
1493 if pkt.AdditionalInformation.GROUP_SECURITY_INFORMATION:
1494 pass
1495 if pkt.AdditionalInformation.DACL_SECURITY_INFORMATION:
1496 pass
1497 if pkt.AdditionalInformation.SACL_SECURITY_INFORMATION:
1498 pass
1499 # Observed:
1500 if (
1501 pkt.AdditionalInformation.OWNER_SECURITY_INFORMATION
1502 or pkt.AdditionalInformation.SACL_SECURITY_INFORMATION
1503 or pkt.AdditionalInformation.GROUP_SECURITY_INFORMATION
1504 or pkt.AdditionalInformation.DACL_SECURITY_INFORMATION
1505 ):
1506 pkt = self.smb_header.copy() / SMB2_Error_Response(ErrorData=b"\xff")
1507 pkt.Status = "STATUS_ACCESS_DENIED"
1508 pkt.Command = "SMB2_QUERY_INFO"
1509 self.send(pkt)
1510 return
1511 if pkt.AdditionalInformation.ATTRIBUTE_SECURITY_INFORMATION:
1512 fileinfo.Control = 0x8800
1513 self.send(
1514 self.smb_header.copy()
1515 / SMB2_Query_Info_Response(Buffer=[("Output", fileinfo)])
1516 )
1517
1518 @ATMT.receive_condition(SERVING)
1519 def receive_set_info_request(self, pkt):
1520 if SMB2_Set_Info_Request in pkt:
1521 raise self.SERVING().action_parameters(pkt)
1522
1523 @ATMT.action(receive_set_info_request)
1524 def send_set_info_response(self, pkt):
1525 self.update_smbheader(pkt)
1526 self.send(self.smb_header.copy() / SMB2_Set_Info_Response())
1527
1528 @ATMT.receive_condition(SERVING)
1529 def receive_write_request(self, pkt):
1530 if SMB2_Write_Request in pkt:
1531 raise self.SERVING().action_parameters(pkt)
1532
1533 @ATMT.action(receive_write_request)
1534 def send_write_response(self, pkt):
1535 self.update_smbheader(pkt)
1536 resp = SMB2_Write_Response(Count=len(pkt.Data))
1537 fid = self.get_file_id(pkt)
1538 if self.current_tree() == "IPC$":
1539 if fid in self.PIPES_TABLE.values():
1540 # A pipe
1541 self.rpc_server.recv(pkt.Data)
1542 else:
1543 if self.readonly:
1544 # Read only !
1545 resp = SMB2_Error_Response()
1546 resp.Command = "SMB2_WRITE"
1547 resp.Status = "ERROR_FILE_READ_ONLY"
1548 else:
1549 # Write file
1550 pth, _ = self.current_handles[fid]
1551 length = pkt[SMB2_Write_Request].DataLen
1552 off = pkt[SMB2_Write_Request].Offset
1553 self.vprint("Writing %s bytes at %s" % (length, off))
1554 with open(pth, "r+b") as fd:
1555 fd.seek(off)
1556 resp.Count = fd.write(pkt[SMB2_Write_Request].Data)
1557 self.send(self.smb_header.copy() / resp)
1558
1559 @ATMT.receive_condition(SERVING)
1560 def receive_read_request(self, pkt):
1561 if SMB2_Read_Request in pkt:
1562 raise self.SERVING().action_parameters(pkt)
1563
1564 @ATMT.action(receive_read_request)
1565 def send_read_response(self, pkt):
1566 self.update_smbheader(pkt)
1567 resp = SMB2_Read_Response()
1568 fid = self.get_file_id(pkt)
1569 if self.current_tree() == "IPC$":
1570 # Read output from DCE/RPC server
1571 r = self.rpc_server.get_response()
1572 resp.Data = bytes(r)
1573 else:
1574 # Read file and send content
1575 pth, _ = self.current_handles[fid]
1576 length = pkt[SMB2_Read_Request].Length
1577 off = pkt[SMB2_Read_Request].Offset
1578 self.vprint("Reading %s bytes at %s" % (length, off))
1579 with open(pth, "rb") as fd:
1580 fd.seek(off)
1581 resp.Data = fd.read(length)
1582 self.send(self.smb_header.copy() / resp)
1583
1584 @ATMT.receive_condition(SERVING)
1585 def receive_close_request(self, pkt):
1586 if SMB2_Close_Request in pkt:
1587 raise self.SERVING().action_parameters(pkt)
1588
1589 @ATMT.action(receive_close_request)
1590 def send_close_response(self, pkt):
1591 self.update_smbheader(pkt)
1592 if self.current_tree() != "IPC$":
1593 fid = self.get_file_id(pkt)
1594 pth, attrs = self.current_handles[fid]
1595 if pth:
1596 self.vprint("Closed: " + str(pth))
1597 del self.current_handles[fid]
1598 del self.enumerate_index[fid]
1599 self.send(
1600 self.smb_header.copy()
1601 / SMB2_Close_Response(
1602 Flags=pkt[SMB2_Close_Request].Flags,
1603 **attrs,
1604 )
1605 )
1606 else:
1607 self.send(self.smb_header.copy() / SMB2_Close_Response())
1608
1609 @ATMT.receive_condition(SERVING)
1610 def receive_tree_disconnect_request(self, pkt):
1611 if SMB2_Tree_Disconnect_Request in pkt:
1612 raise self.SERVING().action_parameters(pkt)
1613
1614 @ATMT.action(receive_tree_disconnect_request)
1615 def send_tree_disconnect_response(self, pkt):
1616 self.update_smbheader(pkt)
1617 try:
1618 del self.current_trees[self.smb_header.TID] # clear tree
1619 resp = self.smb_header.copy() / SMB2_Tree_Disconnect_Response()
1620 except KeyError:
1621 resp = self.smb_header.copy() / SMB2_Error_Response()
1622 resp.Command = "SMB2_TREE_DISCONNECT"
1623 resp.Status = "STATUS_NETWORK_NAME_DELETED"
1624 self.send(resp)
1625
1626 @ATMT.receive_condition(SERVING)
1627 def receive_cancel_request(self, pkt):
1628 if SMB2_Cancel_Request in pkt:
1629 raise self.SERVING().action_parameters(pkt)
1630
1631 @ATMT.action(receive_cancel_request)
1632 def send_notify_cancel_response(self, pkt):
1633 self.update_smbheader(pkt)
1634 resp = self.smb_header.copy() / SMB2_Change_Notify_Response()
1635 resp.Status = "STATUS_CANCELLED"
1636 self.send(resp)
1637
1638 @ATMT.receive_condition(SERVING)
1639 def receive_echo_request(self, pkt):
1640 if SMB2_Echo_Request in pkt:
1641 raise self.SERVING().action_parameters(pkt)
1642
1643 @ATMT.action(receive_echo_request)
1644 def send_echo_reply(self, pkt):
1645 self.update_smbheader(pkt)
1646 self.send(self.smb_header.copy() / SMB2_Echo_Response())
1647
1648
1649# DCE/RPC server for SMB
1650
1651
1652class SMB_DCERPC_Server(DCERPC_Server):
1653 """
1654 DCE/RPC server than handles the minimum RPCs for SMB to work:
1655 """
1656
1657 def __init__(self, *args, **kwargs):
1658 self.shares = kwargs.pop("shares")
1659 super(SMB_DCERPC_Server, self).__init__(*args, **kwargs)
1660
1661 @DCERPC_Server.answer(NetrShareEnum_Request)
1662 def netr_share_enum(self, req):
1663 """
1664 NetrShareEnum [MS-SRVS]
1665 "retrieves information about each shared resource on a server."
1666 """
1667 level = req.InfoStruct.Level
1668
1669 # Create response
1670 resp = NetrShareEnum_Response(
1671 InfoStruct=LPSHARE_ENUM_STRUCT(
1672 Level=level,
1673 ShareInfo=NDRUnion(
1674 tag=level,
1675 value=None,
1676 ),
1677 ),
1678 ndr64=self.ndr64,
1679 )
1680
1681 if level == 1:
1682 nbEntries = len(self.shares)
1683 resp.InfoStruct.ShareInfo.value = NDRPointer(
1684 referent_id=0x20000,
1685 value=SHARE_INFO_1_CONTAINER(
1686 Buffer=[
1687 # Add shares
1688 LPSHARE_INFO_1(
1689 shi1_netname=x.name,
1690 shi1_type=x.type,
1691 shi1_remark=x.remark,
1692 )
1693 for x in self.shares
1694 ],
1695 EntriesRead=nbEntries,
1696 ),
1697 )
1698 resp.TotalEntries = nbEntries
1699 else:
1700 # We only support level 1 :(
1701 resp.status = 0x0000007C # ERROR_INVALID_LEVEL
1702
1703 return resp
1704
1705 @DCERPC_Server.answer(NetrWkstaGetInfo_Request)
1706 def netr_wksta_getinfo(self, req):
1707 """
1708 NetrWkstaGetInfo [MS-SRVS]
1709 "returns information about the configuration of a workstation."
1710 """
1711 level = req.Level
1712
1713 # Create response
1714 resp = NetrWkstaGetInfo_Response(
1715 WkstaInfo=NDRUnion(
1716 tag=level,
1717 value=None,
1718 ),
1719 ndr64=self.ndr64,
1720 )
1721
1722 if level == 100:
1723 resp.WkstaInfo.value = NDRPointer(
1724 referent_id=0x20000,
1725 value=LPWKSTA_INFO_100(
1726 wki100_platform_id=500, # NT
1727 wki100_ver_major=5,
1728 ),
1729 )
1730 else:
1731 # We only support level 101 :(
1732 resp.status = 0x0000007C # ERROR_INVALID_LEVEL
1733
1734 return resp
1735
1736 @DCERPC_Server.answer(NetrServerGetInfo_Request)
1737 def netr_server_getinfo(self, req):
1738 """
1739 NetrServerGetInfo [MS-WKST]
1740 "retrieves current configuration information for CIFS and
1741 SMB Version 1.0 servers."
1742 """
1743 level = req.Level
1744
1745 # Create response
1746 resp = NetrServerGetInfo_Response(
1747 InfoStruct=NDRUnion(
1748 tag=level,
1749 value=None,
1750 ),
1751 ndr64=self.ndr64,
1752 )
1753
1754 if level == 101:
1755 resp.InfoStruct.value = NDRPointer(
1756 referent_id=0x20000,
1757 value=LPSERVER_INFO_101(
1758 sv101_platform_id=500, # NT
1759 sv101_name="WORKSTATION",
1760 sv101_version_major=10,
1761 sv101_version_minor=0,
1762 sv101_version_type=1, # Workstation
1763 ),
1764 )
1765 else:
1766 # We only support level 101 :(
1767 resp.status = 0x0000007C # ERROR_INVALID_LEVEL
1768
1769 return resp
1770
1771 @DCERPC_Server.answer(NetrShareGetInfo_Request)
1772 def netr_share_getinfo(self, req):
1773 """
1774 NetrShareGetInfo [MS-SRVS]
1775 "retrieves information about a particular shared resource on a server."
1776 """
1777 level = req.Level
1778 share_netname = req.payload.payload.valueof("NetName").decode()
1779
1780 # Create response
1781 resp = NetrShareGetInfo_Response(
1782 InfoStruct=NDRUnion(
1783 tag=level,
1784 value=None,
1785 ),
1786 ndr64=self.ndr64,
1787 )
1788
1789 # Find the share the client is asking details for
1790 try:
1791 share = next(x for x in self.shares if x.name == share_netname)
1792 except StopIteration:
1793 # Share doesn't exist !
1794 resp.status = 0x00000906 # NERR_NetNameNotFound
1795 return resp
1796
1797 if level == 1:
1798 resp.InfoStruct.value = NDRPointer(
1799 referent_id=0x20000,
1800 value=LPSHARE_INFO_1(
1801 shi1_netname=share.name,
1802 shi1_type=share.type,
1803 shi1_remark=share.remark,
1804 ),
1805 )
1806 else:
1807 # We only support level 1 :(
1808 resp.status = 0x0000007C # ERROR_INVALID_LEVEL
1809
1810 return resp
1811
1812
1813# Util
1814
1815
1816class smbserver:
1817 r"""
1818 Spawns a simple smbserver
1819
1820 smbserver parameters:
1821
1822 :param shares: the list of shares to announce. Note that IPC$ is appended.
1823 By default, a 'Scapy' share on './'
1824 :param port: (optional) the port to bind on, default 445
1825 :param iface: (optional) the interface to bind on, default conf.iface
1826 :param readonly: (optional) whether the server is read-only or not. default True
1827 :param ssp: (optional) the SSP to use. See the examples below.
1828 Default NTLM with guest
1829
1830 Many more SMB-specific parameters are available in help(SMB_Server)
1831 """
1832
1833 def __init__(
1834 self,
1835 shares=None,
1836 iface: str = None,
1837 port: int = 445,
1838 verb: int = 2,
1839 readonly: bool = True,
1840 # SMB arguments
1841 ssp=None,
1842 **kwargs,
1843 ):
1844 # Default Share
1845 if shares is None:
1846 shares = [
1847 SMBShare(
1848 name="Scapy", path=".", remark="Scapy's SMB server default share"
1849 )
1850 ]
1851 # Verb
1852 if verb >= 2:
1853 log_runtime.info("-- Scapy %s SMB Server --" % conf.version)
1854 log_runtime.info(
1855 "SSP: %s. Read-Only: %s. Serving %s shares:"
1856 % (
1857 conf.color_theme.yellow(ssp or "NTLM (guest)"),
1858 (
1859 conf.color_theme.yellow("YES")
1860 if readonly
1861 else conf.color_theme.format("NO", "bg_red+white")
1862 ),
1863 conf.color_theme.red(len(shares)),
1864 )
1865 )
1866 for share in shares:
1867 log_runtime.info(" * %s" % share)
1868 # Start SMB Server
1869 self.srv = SMB_Server.spawn(
1870 # TCP server
1871 port=port,
1872 iface=iface or conf.loopback_name,
1873 verb=verb,
1874 # SMB server
1875 ssp=ssp,
1876 shares=shares,
1877 readonly=readonly,
1878 # SMB arguments
1879 **kwargs,
1880 )
1881
1882 def close(self):
1883 """
1884 Close the smbserver if started in background mode (bg=True)
1885 """
1886 if self.srv:
1887 try:
1888 self.srv.shutdown(socket.SHUT_RDWR)
1889 except OSError:
1890 pass
1891 self.srv.close()
1892
1893
1894if __name__ == "__main__":
1895 from scapy.utils import AutoArgparse
1896
1897 AutoArgparse(smbserver)