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 1 / 2 Client Automaton
8
9
10.. note::
11 You will find more complete documentation for this layer over at
12 `SMB <https://scapy.readthedocs.io/en/latest/layers/smb.html#client>`_
13"""
14
15import io
16import os
17import pathlib
18import re
19import socket
20import threading
21import time
22
23from scapy.automaton import ATMT, Automaton, ObjectPipe
24from scapy.config import conf
25from scapy.error import Scapy_Exception
26from scapy.fields import UTCTimeField
27from scapy.supersocket import SuperSocket
28from scapy.utils import (
29 CLIUtil,
30 pretty_list,
31 human_size,
32)
33from scapy.volatile import RandUUID
34
35from scapy.layers.dcerpc import NDRUnion, find_dcerpc_interface
36from scapy.layers.gssapi import (
37 GSS_C_FLAGS,
38 GSS_S_COMPLETE,
39 GSS_S_CONTINUE_NEEDED,
40 GSS_S_DEFECTIVE_TOKEN,
41)
42from scapy.layers.msrpce.raw.ms_srvs import (
43 LPSHARE_ENUM_STRUCT,
44 NetrSessionEnum_Request,
45 NetrShareEnum_Request,
46 PSESSION_ENUM_STRUCT,
47 SESSION_INFO_502_CONTAINER,
48 SHARE_INFO_1_CONTAINER,
49)
50from scapy.layers.ntlm import (
51 NTLMSSP,
52)
53from scapy.layers.smb import (
54 SMBNegotiate_Request,
55 SMBNegotiate_Response_Extended_Security,
56 SMBNegotiate_Response_Security,
57 SMBSession_Null,
58 SMBSession_Setup_AndX_Request,
59 SMBSession_Setup_AndX_Request_Extended_Security,
60 SMBSession_Setup_AndX_Response,
61 SMBSession_Setup_AndX_Response_Extended_Security,
62 SMB_Dialect,
63 SMB_Header,
64)
65from scapy.layers.windows.security import SECURITY_DESCRIPTOR
66from scapy.layers.smb2 import (
67 DirectTCP,
68 FileAllInformation,
69 FileIdBothDirectoryInformation,
70 SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2,
71 SMB2_CREATE_REQUEST_LEASE,
72 SMB2_CREATE_REQUEST_LEASE_V2,
73 SMB2_Change_Notify_Request,
74 SMB2_Change_Notify_Response,
75 SMB2_Close_Request,
76 SMB2_Close_Response,
77 SMB2_Create_Context,
78 SMB2_Create_Request,
79 SMB2_Create_Response,
80 SMB2_ENCRYPTION_CIPHERS,
81 SMB2_Encryption_Capabilities,
82 SMB2_Error_Response,
83 SMB2_FILEID,
84 SMB2_Header,
85 SMB2_IOCTL_Request,
86 SMB2_IOCTL_Response,
87 SMB2_Negotiate_Context,
88 SMB2_Negotiate_Protocol_Request,
89 SMB2_Negotiate_Protocol_Response,
90 SMB2_Netname_Negotiate_Context_ID,
91 SMB2_Preauth_Integrity_Capabilities,
92 SMB2_Query_Directory_Request,
93 SMB2_Query_Directory_Response,
94 SMB2_Query_Info_Request,
95 SMB2_Query_Info_Response,
96 SMB2_Read_Request,
97 SMB2_Read_Response,
98 SMB2_SIGNING_ALGORITHMS,
99 SMB2_Session_Setup_Request,
100 SMB2_Session_Setup_Response,
101 SMB2_Signing_Capabilities,
102 SMB2_Tree_Connect_Request,
103 SMB2_Tree_Connect_Response,
104 SMB2_Tree_Disconnect_Request,
105 SMB2_Tree_Disconnect_Response,
106 SMB2_Write_Request,
107 SMB2_Write_Response,
108 SMBStreamSocket,
109 SMB_DIALECTS,
110 SRVSVC_SHARE_TYPES,
111 STATUS_ERREF,
112)
113from scapy.layers.spnego import SPNEGOSSP
114
115
116class SMB_Client(Automaton):
117 """
118 SMB client automaton
119
120 :param sock: the SMBStreamSocket to use
121 :param ssp: the SSP to use
122
123 All other options (in caps) are optional, and SMB specific:
124
125 :param REQUIRE_SIGNATURE: set 'Require Signature'
126 :param REQUIRE_ENCRYPTION: set 'Requite Encryption'
127 :param MIN_DIALECT: minimum SMB dialect. Defaults to 0x0202 (2.0.2)
128 :param MAX_DIALECT: maximum SMB dialect. Defaults to 0x0311 (3.1.1)
129 :param DIALECTS: list of supported SMB2 dialects.
130 Constructed from MIN_DIALECT, MAX_DIALECT otherwise.
131 """
132
133 port = 445
134 cls = DirectTCP
135
136 def __init__(self, sock, ssp=None, *args, **kwargs):
137 # Various SMB client arguments
138 self.EXTENDED_SECURITY = kwargs.pop("EXTENDED_SECURITY", True)
139 self.USE_SMB1 = kwargs.pop("USE_SMB1", False)
140 self.REQUIRE_SIGNATURE = kwargs.pop("REQUIRE_SIGNATURE", None)
141 self.REQUIRE_ENCRYPTION = kwargs.pop("REQUIRE_ENCRYPTION", False)
142 self.RETRY = kwargs.pop("RETRY", 0) # optionally: retry n times session setup
143 self.SMB2 = kwargs.pop("SMB2", False) # optionally: start directly in SMB2
144 self.HOST = kwargs.pop("HOST", "")
145 # Store supported dialects
146 if "DIALECTS" in kwargs:
147 self.DIALECTS = kwargs.pop("DIALECTS")
148 else:
149 MIN_DIALECT = kwargs.pop("MIN_DIALECT", 0x0202)
150 self.MAX_DIALECT = kwargs.pop("MAX_DIALECT", 0x0311)
151 self.DIALECTS = sorted(
152 [
153 x
154 for x in [0x0202, 0x0210, 0x0300, 0x0302, 0x0311]
155 if x >= MIN_DIALECT and x <= self.MAX_DIALECT
156 ]
157 )
158 # Internal Session information
159 self.ErrorStatus = None
160 self.NegotiateCapabilities = None
161 self.GUID = RandUUID()._fix()
162 self.SequenceWindow = (0, 0) # keep track of allowed MIDs
163 self.CurrentCreditCount = 0
164 self.MaxCreditCount = 128
165 if ssp is None:
166 # We got no SSP. Assuming the server allows anonymous
167 ssp = SPNEGOSSP(
168 [
169 NTLMSSP(
170 UPN="guest",
171 HASHNT=b"",
172 )
173 ]
174 )
175 # Initialize
176 kwargs["sock"] = sock
177 Automaton.__init__(
178 self,
179 *args,
180 **kwargs,
181 )
182 if self.is_atmt_socket:
183 self.smb_sock_ready = threading.Event()
184 # Set session options
185 self.session.ssp = ssp
186 self.session.SigningRequired = (
187 self.REQUIRE_SIGNATURE if self.REQUIRE_SIGNATURE is not None else bool(ssp)
188 )
189 self.session.Dialect = self.MAX_DIALECT
190
191 @classmethod
192 def from_tcpsock(cls, sock, **kwargs):
193 return cls.smblink(
194 None,
195 SMBStreamSocket(sock, DirectTCP),
196 **kwargs,
197 )
198
199 @property
200 def session(self):
201 # session shorthand
202 return self.sock.session
203
204 def send(self, pkt):
205 # Calculate what CreditCharge to send.
206 if self.session.Dialect > 0x0202 and isinstance(pkt.payload, SMB2_Header):
207 # [MS-SMB2] sect 3.2.4.1.5
208 typ = type(pkt.payload.payload)
209 if typ is SMB2_Negotiate_Protocol_Request:
210 # See [MS-SMB2] 3.2.4.1.2 note
211 pkt.CreditCharge = 0
212 elif typ in [
213 SMB2_Read_Request,
214 SMB2_Write_Request,
215 SMB2_IOCTL_Request,
216 SMB2_Query_Directory_Request,
217 SMB2_Change_Notify_Request,
218 SMB2_Query_Info_Request,
219 ]:
220 # [MS-SMB2] 3.1.5.2
221 # "For READ, WRITE, IOCTL, and QUERY_DIRECTORY requests"
222 # "CHANGE_NOTIFY, QUERY_INFO, or SET_INFO"
223 if typ == SMB2_Read_Request:
224 Length = pkt.payload.Length
225 elif typ == SMB2_Write_Request:
226 Length = len(pkt.payload.Data)
227 elif typ == SMB2_IOCTL_Request:
228 # [MS-SMB2] 3.3.5.15
229 try:
230 Length = max(
231 len(pkt.payload.Input), pkt.payload.MaxOutputResponse
232 )
233 except AttributeError:
234 Length = 0
235 elif typ in [
236 SMB2_Query_Directory_Request,
237 SMB2_Change_Notify_Request,
238 SMB2_Query_Info_Request,
239 ]:
240 Length = pkt.payload.OutputBufferLength
241 else:
242 raise RuntimeError("impossible case")
243 pkt.CreditCharge = 1 + (Length - 1) // 65536
244 else:
245 # "For all other requests, the client MUST set CreditCharge to 1"
246 pkt.CreditCharge = 1
247 # Keep track of our credits
248 self.CurrentCreditCount -= pkt.CreditCharge
249 # [MS-SMB2] note <110>
250 # "The Windows-based client will request credits up to a configurable
251 # maximum of 128 by default."
252 pkt.CreditRequest = max(self.MaxCreditCount - self.CurrentCreditCount, 0)
253 # Get first available message ID: [MS-SMB2] 3.2.4.1.3 and 3.2.4.1.5
254 pkt.MID = self.SequenceWindow[0]
255 return super(SMB_Client, self).send(pkt)
256
257 @ATMT.state(initial=1)
258 def BEGIN(self):
259 pass
260
261 @ATMT.condition(BEGIN)
262 def continue_smb2(self):
263 if self.SMB2: # Directly started in SMB2
264 self.smb_header = DirectTCP() / SMB2_Header(PID=0xFEFF)
265 raise self.SMB2_NEGOTIATE()
266
267 @ATMT.condition(BEGIN, prio=1)
268 def send_negotiate(self):
269 raise self.SENT_NEGOTIATE()
270
271 @ATMT.action(send_negotiate)
272 def on_negotiate(self):
273 # [MS-SMB2] sect 3.2.4.2.2.1 - Multi-Protocol Negotiate
274 self.smb_header = DirectTCP() / SMB_Header(
275 Flags2=(
276 "LONG_NAMES+EAS+NT_STATUS+UNICODE+"
277 "SMB_SECURITY_SIGNATURE+EXTENDED_SECURITY"
278 ),
279 TID=0xFFFF,
280 PIDLow=0xFEFF,
281 UID=0,
282 MID=0,
283 )
284 if self.EXTENDED_SECURITY:
285 self.smb_header.Flags2 += "EXTENDED_SECURITY"
286 pkt = self.smb_header.copy() / SMBNegotiate_Request(
287 Dialects=[
288 SMB_Dialect(DialectString=x)
289 for x in [
290 "PC NETWORK PROGRAM 1.0",
291 "LANMAN1.0",
292 "Windows for Workgroups 3.1a",
293 "LM1.2X002",
294 "LANMAN2.1",
295 "NT LM 0.12",
296 ]
297 + (["SMB 2.002", "SMB 2.???"] if not self.USE_SMB1 else [])
298 ],
299 )
300 if not self.EXTENDED_SECURITY:
301 pkt.Flags2 -= "EXTENDED_SECURITY"
302 pkt[SMB_Header].Flags2 = (
303 pkt[SMB_Header].Flags2
304 - "SMB_SECURITY_SIGNATURE"
305 + "SMB_SECURITY_SIGNATURE_REQUIRED+IS_LONG_NAME"
306 )
307 self.send(pkt)
308
309 @ATMT.state()
310 def SENT_NEGOTIATE(self):
311 pass
312
313 @ATMT.state()
314 def SMB2_NEGOTIATE(self):
315 pass
316
317 @ATMT.condition(SMB2_NEGOTIATE)
318 def send_negotiate_smb2(self):
319 raise self.SENT_NEGOTIATE()
320
321 @ATMT.action(send_negotiate_smb2)
322 def on_negotiate_smb2(self):
323 # [MS-SMB2] sect 3.2.4.2.2.2 - SMB2-Only Negotiate
324 pkt = self.smb_header.copy() / SMB2_Negotiate_Protocol_Request(
325 Dialects=self.DIALECTS,
326 SecurityMode=(
327 "SIGNING_ENABLED+SIGNING_REQUIRED"
328 if self.session.SigningRequired
329 else "SIGNING_ENABLED"
330 ),
331 )
332 if self.MAX_DIALECT >= 0x0210:
333 # "If the client implements the SMB 2.1 or SMB 3.x dialect, ClientGuid
334 # MUST be set to the global ClientGuid value"
335 pkt.ClientGUID = self.GUID
336 # Capabilities: same as [MS-SMB2] 3.3.5.4
337 self.NegotiateCapabilities = "+".join(
338 [
339 "DFS",
340 "LEASING",
341 "LARGE_MTU",
342 ]
343 )
344 if self.MAX_DIALECT >= 0x0300:
345 # "if Connection.Dialect belongs to the SMB 3.x dialect family ..."
346 self.NegotiateCapabilities += "+" + "+".join(
347 [
348 "MULTI_CHANNEL",
349 "PERSISTENT_HANDLES",
350 "DIRECTORY_LEASING",
351 "ENCRYPTION",
352 ]
353 )
354 if self.MAX_DIALECT >= 0x0311:
355 # "If the client implements the SMB 3.1.1 dialect, it MUST do"
356 pkt.NegotiateContexts = [
357 SMB2_Negotiate_Context()
358 / SMB2_Preauth_Integrity_Capabilities(
359 # As for today, no other hash algorithm is described by the spec
360 HashAlgorithms=["SHA-512"],
361 Salt=self.session.Salt,
362 ),
363 SMB2_Negotiate_Context()
364 / SMB2_Encryption_Capabilities(
365 Ciphers=self.session.SupportedCipherIds,
366 ),
367 # TODO support compression and RDMA
368 SMB2_Negotiate_Context()
369 / SMB2_Netname_Negotiate_Context_ID(
370 NetName=self.HOST,
371 ),
372 SMB2_Negotiate_Context()
373 / SMB2_Signing_Capabilities(
374 SigningAlgorithms=self.session.SupportedSigningAlgorithmIds,
375 ),
376 ]
377 pkt.Capabilities = self.NegotiateCapabilities
378 # Send
379 self.send(pkt)
380 # If required, compute sessions
381 self.session.computeSMBConnectionPreauth(
382 bytes(pkt[SMB2_Header]), # nego request
383 )
384
385 @ATMT.receive_condition(SENT_NEGOTIATE)
386 def receive_negotiate_response(self, pkt):
387 if (
388 SMBNegotiate_Response_Extended_Security in pkt
389 or SMB2_Negotiate_Protocol_Response in pkt
390 ):
391 # Extended SMB1 / SMB2
392 try:
393 ssp_blob = pkt.SecurityBlob # eventually SPNEGO server initiation
394 except AttributeError:
395 ssp_blob = None
396 if (
397 SMB2_Negotiate_Protocol_Response in pkt
398 and pkt.DialectRevision & 0xFF == 0xFF
399 ):
400 # Version is SMB X.???
401 # [MS-SMB2] 3.2.5.2
402 # If the DialectRevision field in the SMB2 NEGOTIATE Response is
403 # 0x02FF ... the client MUST allocate sequence number 1 from
404 # Connection.SequenceWindow, and MUST set MessageId field of the
405 # SMB2 header to 1.
406 self.SequenceWindow = (1, 1)
407 self.smb_header = DirectTCP() / SMB2_Header(PID=0xFEFF, MID=1)
408 self.SMB2 = True # We're now using SMB2 to talk to the server
409 raise self.SMB2_NEGOTIATE()
410 else:
411 if SMB2_Negotiate_Protocol_Response in pkt:
412 # SMB2 was negotiated !
413 self.session.Dialect = pkt.DialectRevision
414 # If required, compute sessions
415 self.session.computeSMBConnectionPreauth(
416 bytes(pkt[SMB2_Header]), # nego response
417 )
418 # Process max sizes
419 self.session.MaxReadSize = pkt.MaxReadSize
420 self.session.MaxTransactionSize = pkt.MaxTransactionSize
421 self.session.MaxWriteSize = pkt.MaxWriteSize
422 # Process SecurityMode
423 if pkt.SecurityMode.SIGNING_REQUIRED:
424 self.session.SigningRequired = True
425 # Process capabilities
426 if self.session.Dialect >= 0x0300:
427 self.session.SupportsEncryption = pkt.Capabilities.ENCRYPTION
428 # Process NegotiateContext
429 if self.session.Dialect >= 0x0311 and pkt.NegotiateContextsCount:
430 for ngctx in pkt.NegotiateContexts:
431 if ngctx.ContextType == 0x0002:
432 # SMB2_ENCRYPTION_CAPABILITIES
433 if ngctx.Ciphers and ngctx.Ciphers[0] != 0:
434 self.session.CipherId = SMB2_ENCRYPTION_CIPHERS[
435 ngctx.Ciphers[0]
436 ]
437 self.session.SupportsEncryption = True
438 elif ngctx.ContextType == 0x0008:
439 # SMB2_SIGNING_CAPABILITIES
440 self.session.SigningAlgorithmId = (
441 SMB2_SIGNING_ALGORITHMS[ngctx.SigningAlgorithms[0]]
442 )
443 if self.REQUIRE_ENCRYPTION and not self.session.SupportsEncryption:
444 self.ErrorStatus = "NEGOTIATE FAILURE: encryption."
445 raise self.NEGO_FAILED()
446 if self.SMB2:
447 self.update_smbheader(pkt)
448 raise self.NEGOTIATED(ssp_blob)
449 elif SMBNegotiate_Response_Security in pkt:
450 # Non-extended SMB1
451 # Never tested. FIXME. probably broken
452 raise self.NEGOTIATED(pkt.Challenge)
453
454 @ATMT.state(final=1)
455 def NEGO_FAILED(self):
456 self.smb_sock_ready.set()
457
458 @ATMT.state()
459 def NEGOTIATED(self, ssp_blob=None):
460 # Negotiated ! We now know the Dialect
461 if self.session.Dialect > 0x0202:
462 # [MS-SMB2] sect 3.2.5.1.4
463 self.smb_header.CreditRequest = 1
464 # Begin session establishment
465 ssp_tuple = self.session.ssp.GSS_Init_sec_context(
466 self.session.sspcontext,
467 input_token=ssp_blob,
468 target_name="cifs/" + self.HOST if self.HOST else None,
469 req_flags=(
470 GSS_C_FLAGS.GSS_C_MUTUAL_FLAG
471 | (GSS_C_FLAGS.GSS_C_INTEG_FLAG if self.session.SigningRequired else 0)
472 ),
473 )
474 return ssp_tuple
475
476 def update_smbheader(self, pkt):
477 """
478 Called when receiving a SMB2 packet to update the current smb_header
479 """
480 # Some values should not be updated when ASYNC
481 if not pkt.Flags.SMB2_FLAGS_ASYNC_COMMAND:
482 # Update IDs
483 self.smb_header.SessionId = pkt.SessionId
484 self.smb_header.TID = pkt.TID
485 self.smb_header.PID = pkt.PID
486 # Update credits
487 self.CurrentCreditCount += pkt.CreditRequest
488 # [MS-SMB2] 3.2.5.1.4
489 self.SequenceWindow = (
490 self.SequenceWindow[0] + max(pkt.CreditCharge, 1),
491 self.SequenceWindow[1] + pkt.CreditRequest,
492 )
493
494 # DEV: add a condition on NEGOTIATED with prio=0
495
496 @ATMT.condition(NEGOTIATED, prio=1)
497 def should_retry_without_blob(self, ssp_tuple):
498 _, _, status = ssp_tuple
499 if status == GSS_S_DEFECTIVE_TOKEN:
500 # Token was defective. This could be that we passed a SPNEGO initial token
501 # to a NTLM SSP (not using SPNEGO). Retry using no input blob
502 raise self.NEGOTIATED()
503
504 @ATMT.condition(NEGOTIATED, prio=2)
505 def should_send_session_setup_request(self, ssp_tuple):
506 _, _, status = ssp_tuple
507 if status not in [GSS_S_COMPLETE, GSS_S_CONTINUE_NEEDED]:
508 raise ValueError(
509 "Internal error: the SSP completed with error: %s" % status
510 )
511 raise self.SENT_SESSION_REQUEST().action_parameters(ssp_tuple)
512
513 @ATMT.state()
514 def SENT_SESSION_REQUEST(self):
515 pass
516
517 @ATMT.action(should_send_session_setup_request)
518 def send_setup_session_request(self, ssp_tuple):
519 self.session.sspcontext, token, status = ssp_tuple
520 if self.SMB2 and status == GSS_S_CONTINUE_NEEDED:
521 # New session: force 0
522 self.SessionId = 0
523 if self.SMB2 or self.EXTENDED_SECURITY:
524 # SMB1 extended / SMB2
525 if self.SMB2:
526 # SMB2
527 pkt = self.smb_header.copy() / SMB2_Session_Setup_Request(
528 Capabilities="DFS",
529 SecurityMode=(
530 "SIGNING_ENABLED+SIGNING_REQUIRED"
531 if self.session.SigningRequired
532 else "SIGNING_ENABLED"
533 ),
534 )
535 else:
536 # SMB1 extended
537 pkt = (
538 self.smb_header.copy()
539 / SMBSession_Setup_AndX_Request_Extended_Security(
540 ServerCapabilities=(
541 "UNICODE+NT_SMBS+STATUS32+LEVEL_II_OPLOCKS+"
542 "DYNAMIC_REAUTH+EXTENDED_SECURITY"
543 ),
544 NativeOS=b"",
545 NativeLanMan=b"",
546 )
547 )
548 pkt.SecurityBlob = token
549 else:
550 # Non-extended security.
551 pkt = self.smb_header.copy() / SMBSession_Setup_AndX_Request(
552 ServerCapabilities="UNICODE+NT_SMBS+STATUS32+LEVEL_II_OPLOCKS",
553 NativeOS=b"",
554 NativeLanMan=b"",
555 OEMPassword=b"\0" * 24,
556 UnicodePassword=token,
557 )
558 self.send(pkt)
559 if self.SMB2:
560 # If required, compute sessions
561 self.session.computeSMBSessionPreauth(
562 bytes(pkt[SMB2_Header]), # session request
563 )
564
565 @ATMT.receive_condition(SENT_SESSION_REQUEST)
566 def receive_session_setup_response(self, pkt):
567 if (
568 SMBSession_Null in pkt
569 or SMBSession_Setup_AndX_Response_Extended_Security in pkt
570 or SMBSession_Setup_AndX_Response in pkt
571 ):
572 # SMB1
573 if SMBSession_Null in pkt:
574 # Likely an error
575 raise self.NEGOTIATED()
576 # Logging
577 if pkt.Status != 0 and pkt.Status != 0xC0000016:
578 # Not SUCCESS nor MORE_PROCESSING_REQUIRED: log
579 self.ErrorStatus = pkt.sprintf("%SMB2_Header.Status%")
580 self.debug(
581 lvl=1,
582 msg=conf.color_theme.red(
583 pkt.sprintf("SMB Session Setup Response: %SMB2_Header.Status%")
584 ),
585 )
586 if self.SMB2:
587 self.update_smbheader(pkt)
588 # Cases depending on the response packet
589 if (
590 SMBSession_Setup_AndX_Response_Extended_Security in pkt
591 or SMB2_Session_Setup_Response in pkt
592 ):
593 # The server assigns us a SessionId
594 self.smb_header.SessionId = pkt.SessionId
595 # SMB1 extended / SMB2
596 if pkt.Status == 0: # Authenticated
597 if SMB2_Session_Setup_Response in pkt:
598 # [MS-SMB2] sect 3.2.5.3.1
599 if pkt.SessionFlags.IS_GUEST:
600 if self.REQUIRE_SIGNATURE or self.REQUIRE_ENCRYPTION:
601 self.ErrorStatus = "Guest session lacks required protection"
602 raise self.AUTH_FAILED()
603 # "If the security subsystem indicates that the session
604 # was established by a guest user, Session.SigningRequired
605 # MUST be set to FALSE and Session.IsGuest MUST be set to TRUE."
606 self.session.IsGuest = True
607 self.session.SigningRequired = False
608 elif self.session.Dialect >= 0x0300:
609 if pkt.SessionFlags.ENCRYPT_DATA or self.REQUIRE_ENCRYPTION:
610 self.session.EncryptData = True
611 self.session.SigningRequired = False
612 raise self.AUTHENTICATED(pkt.SecurityBlob)
613 else:
614 if SMB2_Header in pkt:
615 # If required, compute sessions
616 self.session.computeSMBSessionPreauth(
617 bytes(pkt[SMB2_Header]), # session response
618 )
619 # Ongoing auth
620 raise self.NEGOTIATED(pkt.SecurityBlob)
621 elif SMBSession_Setup_AndX_Response_Extended_Security in pkt:
622 # SMB1 non-extended
623 pass
624 elif SMB2_Error_Response in pkt:
625 # Authentication failure
626 self.session.sspcontext.clifailure()
627 # Reset Session preauth (SMB 3.1.1)
628 self.session.SessionPreauthIntegrityHashValue = None
629 if not self.RETRY:
630 raise self.AUTH_FAILED()
631 self.debug(lvl=2, msg="RETRY: %s" % self.RETRY)
632 self.RETRY -= 1
633 raise self.NEGOTIATED()
634
635 @ATMT.state(final=1)
636 def AUTH_FAILED(self):
637 self.smb_sock_ready.set()
638
639 @ATMT.state()
640 def AUTHENTICATED(self, ssp_blob=None):
641 self.session.sspcontext, _, status = self.session.ssp.GSS_Init_sec_context(
642 self.session.sspcontext,
643 input_token=ssp_blob,
644 target_name="cifs/" + self.HOST if self.HOST else None,
645 )
646 if status != GSS_S_COMPLETE:
647 raise ValueError(
648 "Internal error: the SSP completed with error: %s" % status
649 )
650 # Authentication was successful
651 self.session.computeSMBSessionKeys(IsClient=True)
652
653 # DEV: add a condition on AUTHENTICATED with prio=0
654
655 @ATMT.condition(AUTHENTICATED, prio=1)
656 def authenticated_post_actions(self):
657 raise self.SOCKET_BIND()
658
659 # Plain SMB Socket
660
661 @ATMT.state()
662 def SOCKET_BIND(self):
663 self.smb_sock_ready.set()
664
665 @ATMT.condition(SOCKET_BIND)
666 def start_smb_socket(self):
667 raise self.SOCKET_MODE_SMB()
668
669 @ATMT.state()
670 def SOCKET_MODE_SMB(self):
671 pass
672
673 @ATMT.receive_condition(SOCKET_MODE_SMB)
674 def incoming_data_received_smb(self, pkt):
675 raise self.SOCKET_MODE_SMB().action_parameters(pkt)
676
677 @ATMT.action(incoming_data_received_smb)
678 def receive_data_smb(self, pkt):
679 resp = pkt[SMB2_Header].payload
680 if isinstance(resp, SMB2_Error_Response):
681 if pkt.Status == 0x00000103: # STATUS_PENDING
682 # answer is coming later.. just wait...
683 return
684 if pkt.Status == 0x0000010B: # STATUS_NOTIFY_CLEANUP
685 # this is a notify cleanup. ignore
686 return
687 self.update_smbheader(pkt)
688 # Add the status to the response as metadata
689 resp.NTStatus = pkt.sprintf("%SMB2_Header.Status%")
690 self.oi.smbpipe.send(resp)
691
692 @ATMT.ioevent(SOCKET_MODE_SMB, name="smbpipe", as_supersocket="smblink")
693 def outgoing_data_received_smb(self, fd):
694 raise self.SOCKET_MODE_SMB().action_parameters(fd.recv())
695
696 @ATMT.action(outgoing_data_received_smb)
697 def send_data(self, d):
698 self.send(self.smb_header.copy() / d)
699
700
701class SMB_SOCKET(SuperSocket):
702 """
703 Mid-level wrapper over SMB_Client.smblink that provides some basic SMB
704 client functions, such as tree connect, directory query, etc.
705 """
706
707 def __init__(self, smbsock, use_ioctl=True, timeout=3):
708 self.ins = smbsock
709 self.timeout = timeout
710 if not self.ins.atmt.smb_sock_ready.wait(timeout=timeout):
711 # If we have a SSP, tell it we failed.
712 if self.session.sspcontext:
713 self.session.sspcontext.clifailure()
714 raise TimeoutError(
715 "The SMB handshake timed out ! (enable debug=1 for logs)"
716 )
717 if self.ins.atmt.ErrorStatus:
718 raise Scapy_Exception(
719 "SMB Session Setup failed: %s" % self.ins.atmt.ErrorStatus
720 )
721
722 @classmethod
723 def from_tcpsock(cls, sock, **kwargs):
724 """
725 Wraps the tcp socket in a SMB_Client.smblink first, then into the
726 SMB_SOCKET/SMB_RPC_SOCKET
727 """
728 return cls(
729 use_ioctl=kwargs.pop("use_ioctl", True),
730 timeout=kwargs.pop("timeout", 3),
731 smbsock=SMB_Client.from_tcpsock(sock, **kwargs),
732 )
733
734 @property
735 def session(self):
736 return self.ins.atmt.session
737
738 def set_TID(self, TID):
739 """
740 Set the TID (Tree ID).
741 This can be called before sending a packet
742 """
743 self.ins.atmt.smb_header.TID = TID
744
745 def get_TID(self):
746 """
747 Get the current TID from the underlying socket
748 """
749 return self.ins.atmt.smb_header.TID
750
751 def tree_connect(self, name):
752 """
753 Send a TreeConnect request
754 """
755 resp = self.ins.sr1(
756 SMB2_Tree_Connect_Request(
757 Buffer=[
758 (
759 "Path",
760 "\\\\%s\\%s"
761 % (
762 self.session.sspcontext.ServerHostname,
763 name,
764 ),
765 )
766 ]
767 ),
768 chainCC=True,
769 verbose=False,
770 timeout=self.timeout,
771 )
772 if not resp:
773 raise ValueError("TreeConnect timed out !")
774 if SMB2_Tree_Connect_Response not in resp:
775 raise ValueError("Failed TreeConnect ! %s" % resp.NTStatus)
776 # [MS-SMB2] sect 3.2.5.5
777 if self.session.Dialect >= 0x0300:
778 if resp.ShareFlags.ENCRYPT_DATA and self.session.SupportsEncryption:
779 self.session.TreeEncryptData = True
780 else:
781 self.session.TreeEncryptData = False
782 return self.get_TID()
783
784 def tree_disconnect(self):
785 """
786 Send a TreeDisconnect request
787 """
788 resp = self.ins.sr1(
789 SMB2_Tree_Disconnect_Request(),
790 verbose=False,
791 timeout=self.timeout,
792 chainCC=True,
793 )
794 if not resp:
795 raise ValueError("TreeDisconnect timed out !")
796 if SMB2_Tree_Disconnect_Response not in resp:
797 raise ValueError("Failed TreeDisconnect ! %s" % resp.NTStatus)
798
799 def create_request(
800 self,
801 name,
802 mode="r",
803 type="pipe",
804 extra_create_options=[],
805 extra_desired_access=[],
806 ):
807 """
808 Open a file/pipe by its name
809
810 :param name: the name of the file or named pipe. e.g. 'srvsvc'
811 """
812 ShareAccess = []
813 DesiredAccess = []
814 # Common params depending on the access
815 if "r" in mode:
816 ShareAccess.append("FILE_SHARE_READ")
817 DesiredAccess.extend(["FILE_READ_DATA", "FILE_READ_ATTRIBUTES"])
818 if "w" in mode:
819 ShareAccess.append("FILE_SHARE_WRITE")
820 DesiredAccess.extend(["FILE_WRITE_DATA", "FILE_WRITE_ATTRIBUTES"])
821 if "d" in mode:
822 ShareAccess.append("FILE_SHARE_DELETE")
823 # Params depending on the type
824 FileAttributes = []
825 CreateOptions = []
826 CreateContexts = []
827 CreateDisposition = "FILE_OPEN"
828 if type == "folder":
829 FileAttributes.append("FILE_ATTRIBUTE_DIRECTORY")
830 CreateOptions.append("FILE_DIRECTORY_FILE")
831 elif type in ["file", "pipe"]:
832 CreateOptions = ["FILE_NON_DIRECTORY_FILE"]
833 if "r" in mode:
834 DesiredAccess.extend(["FILE_READ_EA", "READ_CONTROL", "SYNCHRONIZE"])
835 if "w" in mode:
836 CreateDisposition = "FILE_OVERWRITE_IF"
837 DesiredAccess.append("FILE_WRITE_EA")
838 if "d" in mode:
839 DesiredAccess.append("DELETE")
840 CreateOptions.append("FILE_DELETE_ON_CLOSE")
841 if type == "file":
842 FileAttributes.append("FILE_ATTRIBUTE_NORMAL")
843 elif type:
844 raise ValueError("Unknown type: %s" % type)
845 # [MS-SMB2] 3.2.4.3.8
846 RequestedOplockLevel = 0
847 if self.session.Dialect >= 0x0300:
848 RequestedOplockLevel = "SMB2_OPLOCK_LEVEL_LEASE"
849 elif self.session.Dialect >= 0x0210 and type == "file":
850 RequestedOplockLevel = "SMB2_OPLOCK_LEVEL_LEASE"
851 # SMB 3.X
852 if self.session.Dialect >= 0x0300 and type in ["file", "folder"]:
853 CreateContexts.extend(
854 [
855 # [SMB2] sect 3.2.4.3.5
856 SMB2_Create_Context(
857 Name=b"DH2Q",
858 Data=SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2(
859 CreateGuid=RandUUID()._fix()
860 ),
861 ),
862 # [SMB2] sect 3.2.4.3.9
863 SMB2_Create_Context(
864 Name=b"MxAc",
865 ),
866 # [SMB2] sect 3.2.4.3.10
867 SMB2_Create_Context(
868 Name=b"QFid",
869 ),
870 # [SMB2] sect 3.2.4.3.8
871 SMB2_Create_Context(
872 Name=b"RqLs",
873 Data=SMB2_CREATE_REQUEST_LEASE_V2(LeaseKey=RandUUID()._fix()),
874 ),
875 ]
876 )
877 elif self.session.Dialect == 0x0210 and type == "file":
878 CreateContexts.extend(
879 [
880 # [SMB2] sect 3.2.4.3.8
881 SMB2_Create_Context(
882 Name=b"RqLs",
883 Data=SMB2_CREATE_REQUEST_LEASE(LeaseKey=RandUUID()._fix()),
884 ),
885 ]
886 )
887 # Extra options
888 if extra_create_options:
889 CreateOptions.extend(extra_create_options)
890 if extra_desired_access:
891 DesiredAccess.extend(extra_desired_access)
892 # Request
893 resp = self.ins.sr1(
894 SMB2_Create_Request(
895 ImpersonationLevel="Impersonation",
896 DesiredAccess="+".join(DesiredAccess),
897 CreateDisposition=CreateDisposition,
898 CreateOptions="+".join(CreateOptions),
899 ShareAccess="+".join(ShareAccess),
900 FileAttributes="+".join(FileAttributes),
901 CreateContexts=CreateContexts,
902 RequestedOplockLevel=RequestedOplockLevel,
903 Name=name,
904 ),
905 chainCC=True,
906 verbose=0,
907 timeout=self.timeout,
908 )
909 if not resp:
910 raise ValueError("CreateRequest timed out !")
911 if SMB2_Create_Response not in resp:
912 raise ValueError("Failed CreateRequest ! %s" % resp.NTStatus)
913 return resp[SMB2_Create_Response].FileId
914
915 def close_request(self, FileId):
916 """
917 Close the FileId
918 """
919 pkt = SMB2_Close_Request(FileId=FileId)
920 resp = self.ins.sr1(pkt, verbose=0, timeout=self.timeout, chainCC=True)
921 if not resp:
922 raise ValueError("CloseRequest timed out !")
923 if SMB2_Close_Response not in resp:
924 raise ValueError("Failed CloseRequest ! %s" % resp.NTStatus)
925
926 def read_request(self, FileId, Length, Offset=0):
927 """
928 Read request
929 """
930 resp = self.ins.sr1(
931 SMB2_Read_Request(
932 FileId=FileId,
933 Length=Length,
934 Offset=Offset,
935 ),
936 chainCC=True,
937 verbose=0,
938 timeout=self.timeout * 10,
939 )
940 if not resp:
941 raise ValueError("ReadRequest timed out !")
942 if SMB2_Read_Response not in resp:
943 raise ValueError("Failed ReadRequest ! %s" % resp.NTStatus)
944 return resp.Data
945
946 def write_request(self, Data, FileId, Offset=0):
947 """
948 Write request
949 """
950 resp = self.ins.sr1(
951 SMB2_Write_Request(
952 FileId=FileId,
953 Data=Data,
954 Offset=Offset,
955 ),
956 chainCC=True,
957 verbose=0,
958 timeout=self.timeout * 10,
959 )
960 if not resp:
961 raise ValueError("WriteRequest timed out !")
962 if SMB2_Write_Response not in resp:
963 raise ValueError("Failed WriteRequest ! %s" % resp.NTStatus)
964 return resp.Count
965
966 def query_directory(self, FileId, FileName="*"):
967 """
968 Query the Directory with FileId
969 """
970 results = []
971 Flags = "SMB2_RESTART_SCANS"
972 while True:
973 pkt = SMB2_Query_Directory_Request(
974 FileInformationClass="FileIdBothDirectoryInformation",
975 FileId=FileId,
976 FileName=FileName,
977 Flags=Flags,
978 )
979 resp = self.ins.sr1(pkt, verbose=0, timeout=self.timeout, chainCC=True)
980 Flags = 0 # only the first one is RESTART_SCANS
981 if not resp:
982 raise ValueError("QueryDirectory timed out !")
983 if SMB2_Error_Response in resp:
984 break
985 elif SMB2_Query_Directory_Response not in resp:
986 raise ValueError("Failed QueryDirectory ! %s" % resp.NTStatus)
987 res = FileIdBothDirectoryInformation(resp.Output)
988 results.extend(
989 [
990 (
991 x.FileName,
992 x.FileAttributes,
993 x.EndOfFile,
994 x.LastWriteTime,
995 )
996 for x in res.files
997 # strip invalid file names
998 if "/" not in x.FileName
999 ]
1000 )
1001 return results
1002
1003 def query_info(self, FileId, InfoType, FileInfoClass, AdditionalInformation=0):
1004 """
1005 Query the Info
1006 """
1007 pkt = SMB2_Query_Info_Request(
1008 InfoType=InfoType,
1009 FileInfoClass=FileInfoClass,
1010 OutputBufferLength=65535,
1011 FileId=FileId,
1012 AdditionalInformation=AdditionalInformation,
1013 )
1014 resp = self.ins.sr1(pkt, verbose=0, timeout=self.timeout, chainCC=True)
1015 if not resp:
1016 raise ValueError("QueryInfo timed out !")
1017 if SMB2_Query_Info_Response not in resp:
1018 raise ValueError("Failed QueryInfo ! %s" % resp.NTStatus)
1019 return resp.Output
1020
1021 def ioctl(self, CtlCode, Flags="SMB2_0_IOCTL_IS_FSCTL", Input=None):
1022 """
1023 Perform an IOCTL
1024 """
1025 pkt = SMB2_IOCTL_Request(
1026 FileId=SMB2_FILEID(
1027 Persistent=0xFFFFFFFFFFFFFFFF, Volatile=0xFFFFFFFFFFFFFFFF
1028 ),
1029 Flags=Flags,
1030 CtlCode=CtlCode,
1031 )
1032 if Input is not None:
1033 pkt.Input = bytes(Input)
1034 resp = self.ins.sr1(pkt, verbose=0, chainCC=True)
1035 if SMB2_IOCTL_Response not in resp:
1036 raise ValueError("Failed reading IOCTL_Response ! %s" % resp.NTStatus)
1037 return resp.Output
1038
1039 def changenotify(self, FileId):
1040 """
1041 Register change notify
1042 """
1043 pkt = SMB2_Change_Notify_Request(
1044 Flags="SMB2_WATCH_TREE",
1045 OutputBufferLength=65535,
1046 FileId=FileId,
1047 CompletionFilter=0x0FFF,
1048 )
1049 # we can wait forever, not a problem in this one
1050 resp = self.ins.sr1(pkt, verbose=0, chainCC=True)
1051 if SMB2_Change_Notify_Response not in resp:
1052 raise ValueError("Failed ChangeNotify ! %s" % resp.NTStatus)
1053 return resp.Output
1054
1055
1056class SMB_RPC_SOCKET(ObjectPipe, SMB_SOCKET):
1057 """
1058 Extends SMB_SOCKET (which is a wrapper over SMB_Client.smblink) to send
1059 DCE/RPC messages (bind, reqs, etc.)
1060
1061 This is usable as a normal SuperSocket (sr1, etc.) and performs the
1062 wrapping of the DCE/RPC messages into SMB2_Write/Read packets.
1063 """
1064
1065 def __init__(self, smbsock, use_ioctl=True, timeout=3):
1066 self.use_ioctl = use_ioctl
1067 ObjectPipe.__init__(self, "SMB_RPC_SOCKET")
1068 SMB_SOCKET.__init__(self, smbsock, timeout=timeout)
1069
1070 def open_pipe(self, name):
1071 self.PipeFileId = self.create_request(name, mode="rw", type="pipe")
1072
1073 def close_pipe(self):
1074 self.close_request(self.PipeFileId)
1075 self.PipeFileId = None
1076
1077 def send(self, x, is_sr1=True):
1078 # Reminder: this class is an ObjectPipe ! It doesn't act as a real socket
1079 # but just a queue. When someone calls the "send" function, they pipe
1080 # some data that we must send, and tell us if they expect an answer through
1081 # the is_sr1 flag.
1082
1083 # Detect if DCE/RPC is fragmented. Then we must use Read/Write
1084 is_frag = x.pfc_flags & 3 != 3
1085
1086 if self.use_ioctl and is_sr1 and not is_frag and self.session.Dialect >= 0x0210:
1087 # Use IOCTLRequest
1088 pkt = SMB2_IOCTL_Request(
1089 FileId=self.PipeFileId,
1090 Flags="SMB2_0_IOCTL_IS_FSCTL",
1091 CtlCode="FSCTL_PIPE_TRANSCEIVE",
1092 )
1093 pkt.Input = bytes(x)
1094 resp = self.ins.sr1(pkt, verbose=0, chainCC=True)
1095 if SMB2_IOCTL_Response not in resp:
1096 raise ValueError("Failed reading IOCTL_Response ! %s" % resp.NTStatus)
1097 data = bytes(resp.Output)
1098 super(SMB_RPC_SOCKET, self).send(data)
1099
1100 # Handle BUFFER_OVERFLOW (big DCE/RPC response)
1101 while resp.NTStatus == "STATUS_BUFFER_OVERFLOW" or data[3] & 2 != 2:
1102 # Retrieve DCE/RPC full size
1103 resp = self.ins.sr1(
1104 SMB2_Read_Request(
1105 FileId=self.PipeFileId,
1106 ),
1107 verbose=0,
1108 )
1109 data = resp.Data
1110 super(SMB_RPC_SOCKET, self).send(data)
1111 else:
1112 # Use WriteRequest/ReadRequest
1113 pkt = SMB2_Write_Request(
1114 FileId=self.PipeFileId,
1115 )
1116 pkt.Data = bytes(x)
1117 # We send the Write Request
1118 resp = self.ins.sr1(pkt, verbose=0)
1119 if SMB2_Write_Response not in resp:
1120 raise ValueError("Failed sending WriteResponse ! %s" % resp.NTStatus)
1121
1122 # We may not be expecting an answer
1123 if not is_sr1:
1124 return
1125
1126 # If fragmented, only read if it's the last.
1127 if is_frag and not x.pfc_flags.PFC_LAST_FRAG:
1128 return
1129
1130 # We send a Read Request afterwards
1131 resp = self.ins.sr1(
1132 SMB2_Read_Request(
1133 FileId=self.PipeFileId,
1134 ),
1135 verbose=0,
1136 )
1137 if SMB2_Read_Response not in resp:
1138 raise ValueError("Failed reading ReadResponse ! %s" % resp.NTStatus)
1139 super(SMB_RPC_SOCKET, self).send(resp.Data)
1140 # Handle fragmented response
1141 while resp.Data[3] & 2 != 2: # PFC_LAST_FRAG not set
1142 # Retrieve DCE/RPC full size
1143 resp = self.ins.sr1(
1144 SMB2_Read_Request(
1145 FileId=self.PipeFileId,
1146 ),
1147 verbose=0,
1148 )
1149 super(SMB_RPC_SOCKET, self).send(resp.Data)
1150
1151 def close(self):
1152 SMB_SOCKET.close(self)
1153 ObjectPipe.close(self)
1154
1155
1156@conf.commands.register
1157class smbclient(CLIUtil):
1158 r"""
1159 A simple SMB client CLI powered by Scapy
1160
1161 :param target: can be a hostname, the IPv4 or the IPv6 to connect to
1162 :param UPN: the upn to use (DOMAIN/USER, DOMAIN\USER, USER@DOMAIN or USER)
1163 :param guest: use guest mode (over NTLM)
1164 :param ssp: if provided, use this SSP for auth.
1165 :param kerberos_required: require kerberos
1166 :param port: the TCP port. default 445
1167 :param password: if provided, used for auth
1168 :param HashNt: if provided, used for auth (NTLM)
1169 :param HashAes256Sha96: if provided, used for auth (Kerberos)
1170 :param HashAes128Sha96: if provided, used for auth (Kerberos)
1171 :param use_krb5ccname: (bool) if true, the KRB5CCNAME environment variable will
1172 be used if available.
1173 :param use_winssp: (bool) (only works on Windows). Use implicit authentication
1174 through WinSSP.
1175 :param ST: if provided, the service ticket to use (Kerberos)
1176 :param KEY: if provided, the session key associated to the ticket (Kerberos)
1177 :param cli: CLI mode (default True). False to use for scripting
1178
1179 Some additional SMB parameters are available under help(SMB_Client). Some of
1180 them include the following:
1181
1182 :param REQUIRE_ENCRYPTION: requires encryption.
1183 """
1184
1185 def __init__(
1186 self,
1187 target: str,
1188 UPN: str = None,
1189 password: str = None,
1190 guest: bool = False,
1191 kerberos_required: bool = False,
1192 HashNt: bytes = None,
1193 HashAes256Sha96: bytes = None,
1194 HashAes128Sha96: bytes = None,
1195 use_krb5ccname: bool = False,
1196 use_winssp: bool = False,
1197 port: int = 445,
1198 timeout: int = 5,
1199 debug: int = 0,
1200 ssp=None,
1201 ST=None,
1202 KEY=None,
1203 cli=True,
1204 # SMB arguments
1205 REQUIRE_ENCRYPTION=False,
1206 **kwargs,
1207 ):
1208 if cli:
1209 self._depcheck()
1210 assert (
1211 UPN or ssp or guest or use_winssp
1212 ), "Either UPN, ssp or guest must be provided !"
1213 # Do we need to build a SSP?
1214 if ssp is None:
1215 # Create the SSP (only if not guest mode)
1216 if not guest:
1217 ssp = SPNEGOSSP.from_cli_arguments(
1218 UPN=UPN,
1219 target=target,
1220 password=password,
1221 HashNt=HashNt,
1222 HashAes256Sha96=HashAes256Sha96,
1223 HashAes128Sha96=HashAes128Sha96,
1224 ST=ST,
1225 KEY=KEY,
1226 kerberos_required=kerberos_required,
1227 use_krb5ccname=use_krb5ccname,
1228 use_winssp=use_winssp,
1229 )
1230 else:
1231 # Guest mode
1232 ssp = None
1233 # Check if target is IPv4 or IPv6
1234 if ":" in target:
1235 family = socket.AF_INET6
1236 else:
1237 family = socket.AF_INET
1238 # Open socket
1239 sock = socket.socket(family, socket.SOCK_STREAM)
1240 # Configure socket for SMB:
1241 # - TCP KEEPALIVE, TCP_KEEPIDLE and TCP_KEEPINTVL. Against a Windows server this
1242 # isn't necessary, but samba kills the socket VERY fast otherwise.
1243 # - set TCP_NODELAY to disable Nagle's algorithm (we're streaming data)
1244 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
1245 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1246 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10)
1247 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10)
1248 # Timeout & connect
1249 sock.settimeout(timeout)
1250 if debug:
1251 print("Connecting to %s:%s" % (target, port))
1252 sock.connect((target, port))
1253 self.extra_create_options = []
1254 # Wrap with the automaton
1255 self.timeout = timeout
1256 kwargs.setdefault("HOST", target)
1257 self.sock = SMB_Client.from_tcpsock(
1258 sock,
1259 ssp=ssp,
1260 debug=debug,
1261 REQUIRE_ENCRYPTION=REQUIRE_ENCRYPTION,
1262 timeout=timeout,
1263 **kwargs,
1264 )
1265 try:
1266 # Wrap with SMB_SOCKET
1267 self.smbsock = SMB_SOCKET(self.sock, timeout=self.timeout)
1268 # Wait for either the atmt to fail, or the smb_sock_ready to timeout
1269 _t = time.time()
1270 while True:
1271 if self.sock.atmt.smb_sock_ready.is_set():
1272 # yay
1273 break
1274 if not self.sock.atmt.isrunning():
1275 status = self.sock.atmt.get("Status")
1276 raise Scapy_Exception(
1277 "%s with status %s"
1278 % (
1279 self.sock.atmt.state.state,
1280 STATUS_ERREF.get(status, hex(status)),
1281 )
1282 )
1283 if time.time() - _t > timeout:
1284 self.sock.close()
1285 raise TimeoutError("The SMB handshake timed out.")
1286 time.sleep(0.1)
1287 except Exception:
1288 # Something bad happened, end the socket/automaton
1289 self.sock.close()
1290 raise
1291
1292 # For some usages, we will also need the RPC wrapper
1293 from scapy.layers.msrpce.rpcclient import DCERPC_Client
1294
1295 self.rpcclient = DCERPC_Client.from_smblink(
1296 self.sock,
1297 ndr64=False,
1298 verb=bool(debug),
1299 )
1300 # We have a valid smb connection !
1301 print(
1302 "%s authentication successful using %s%s !"
1303 % (
1304 SMB_DIALECTS.get(
1305 self.smbsock.session.Dialect,
1306 "SMB %s" % self.smbsock.session.Dialect,
1307 ),
1308 repr(self.smbsock.session.sspcontext),
1309 " as GUEST" if self.smbsock.session.IsGuest else "",
1310 )
1311 )
1312 # Now define some variables for our CLI
1313 self.pwd = pathlib.PureWindowsPath("/")
1314 self.localpwd = pathlib.Path(".").resolve()
1315 self.current_tree = None
1316 self.ls_cache = {} # cache the listing of the current directory
1317 self.sh_cache = [] # cache the shares
1318 # Start CLI
1319 if cli:
1320 self.loop(debug=debug)
1321
1322 def ps1(self):
1323 return r"smb: \%s> " % self.normalize_path(self.pwd)
1324
1325 def close(self):
1326 print("Connection closed")
1327 self.smbsock.close()
1328
1329 def _require_share(self, silent=False):
1330 if self.current_tree is None:
1331 if not silent:
1332 print("No share selected ! Try 'shares' then 'use'.")
1333 return True
1334
1335 def collapse_path(self, path):
1336 # the amount of pathlib.wtf you need to do to resolve .. on all platforms
1337 # is ridiculous
1338 return pathlib.PureWindowsPath(os.path.normpath(path.as_posix()))
1339
1340 def normalize_path(self, path):
1341 """
1342 Normalize path for CIFS usage
1343 """
1344 return str(self.collapse_path(path)).lstrip("\\")
1345
1346 @CLIUtil.addcommand()
1347 def shares(self):
1348 """
1349 List the shares available
1350 """
1351 # Poll cache
1352 if self.sh_cache:
1353 return self.sh_cache
1354 # It's an RPC
1355 self.rpcclient.open_smbpipe("srvsvc")
1356 self.rpcclient.bind(find_dcerpc_interface("srvsvc"))
1357 req = NetrShareEnum_Request(
1358 InfoStruct=LPSHARE_ENUM_STRUCT(
1359 Level=1,
1360 ShareInfo=NDRUnion(
1361 tag=1,
1362 value=SHARE_INFO_1_CONTAINER(Buffer=None),
1363 ),
1364 ),
1365 PreferedMaximumLength=0xFFFFFFFF,
1366 ndr64=self.rpcclient.ndr64,
1367 )
1368 resp = self.rpcclient.sr1_req(req, timeout=self.timeout)
1369 self.rpcclient.close_smbpipe()
1370 if resp.status != 0:
1371 resp.show()
1372 raise ValueError("NetrShareEnum_Request failed !")
1373 results = []
1374 for share in resp.valueof("InfoStruct.ShareInfo.Buffer"):
1375 shi1_type = share.valueof("shi1_type") & 0x0FFFFFFF
1376 results.append(
1377 (
1378 share.valueof("shi1_netname").decode(),
1379 SRVSVC_SHARE_TYPES.get(shi1_type, shi1_type),
1380 share.valueof("shi1_remark").decode(),
1381 )
1382 )
1383 self.sh_cache = results # cache
1384 return results
1385
1386 @CLIUtil.addoutput(shares)
1387 def shares_output(self, results):
1388 """
1389 Print the output of 'shares'
1390 """
1391 print(pretty_list(results, [("ShareName", "ShareType", "Comment")]))
1392
1393 @CLIUtil.addcommand(mono=True)
1394 def use(self, share):
1395 """
1396 Open a share
1397 """
1398 self.current_tree = self.smbsock.tree_connect(share)
1399 self.pwd = pathlib.PureWindowsPath("/")
1400 self.ls_cache.clear()
1401
1402 @CLIUtil.addcomplete(use)
1403 def use_complete(self, share):
1404 """
1405 Auto-complete 'use'
1406 """
1407 return [
1408 x[0] for x in self.shares() if x[0].startswith(share) and x[0] != "IPC$"
1409 ]
1410
1411 def _parsepath(self, arg, remote=True):
1412 """
1413 Parse a path. Returns the parent folder and file name
1414 """
1415 # Find parent directory if it exists
1416 elt = (pathlib.PureWindowsPath if remote else pathlib.Path)(arg)
1417 eltpar = (pathlib.PureWindowsPath if remote else pathlib.Path)(".")
1418 eltname = elt.name
1419 if arg.endswith("/") or arg.endswith("\\"):
1420 eltpar = elt
1421 eltname = ""
1422 elif elt.parent and elt.parent.name or elt.is_absolute():
1423 eltpar = elt.parent
1424 return eltpar, eltname
1425
1426 def _fs_complete(self, arg, cond=None):
1427 """
1428 Return a listing of the remote files for completion purposes
1429 """
1430 if cond is None:
1431 cond = lambda _: True
1432 eltpar, eltname = self._parsepath(arg)
1433 # ls in that directory
1434 try:
1435 files = self.ls(parent=eltpar)
1436 except ValueError:
1437 return []
1438 return [
1439 str(eltpar / x[0])
1440 for x in files
1441 if (
1442 x[0].lower().startswith(eltname.lower())
1443 and x[0] not in [".", ".."]
1444 and cond(x[1])
1445 )
1446 ]
1447
1448 def _dir_complete(self, arg):
1449 """
1450 Return a directories of remote files for completion purposes
1451 """
1452 results = self._fs_complete(
1453 arg,
1454 cond=lambda x: x.FILE_ATTRIBUTE_DIRECTORY,
1455 )
1456 if len(results) == 1 and results[0].startswith(arg):
1457 # skip through folders
1458 return [results[0] + "\\"]
1459 return results
1460
1461 @CLIUtil.addcommand(mono=True)
1462 def ls(self, parent=None):
1463 """
1464 List the files in the remote directory
1465 -t: sort by timestamp
1466 -S: sort by size
1467 -r: reverse while sorting
1468 """
1469 if self._require_share():
1470 return
1471 # Get pwd of the ls
1472 pwd = self.pwd
1473 if parent is not None:
1474 pwd /= parent
1475 pwd = self.normalize_path(pwd)
1476 # Poll the cache
1477 if self.ls_cache and pwd in self.ls_cache:
1478 return self.ls_cache[pwd]
1479 self.smbsock.set_TID(self.current_tree)
1480 # Open folder
1481 fileId = self.smbsock.create_request(
1482 pwd,
1483 type="folder",
1484 extra_create_options=self.extra_create_options,
1485 )
1486 # Query the folder
1487 files = self.smbsock.query_directory(fileId)
1488 # Close the folder
1489 self.smbsock.close_request(fileId)
1490 self.ls_cache[pwd] = files # Store cache
1491 return files
1492
1493 @CLIUtil.addoutput(ls)
1494 def ls_output(self, results, *, t=False, S=False, r=False):
1495 """
1496 Print the output of 'ls'
1497 """
1498 fld = UTCTimeField(
1499 "", None, fmt="<Q", epoch=[1601, 1, 1, 0, 0, 0], custom_scaling=1e7
1500 )
1501 if t:
1502 # Sort by time
1503 results.sort(key=lambda x: -x[3])
1504 if S:
1505 # Sort by size
1506 results.sort(key=lambda x: -x[2])
1507 if r:
1508 # Reverse sort
1509 results = results[::-1]
1510 results = [
1511 (
1512 x[0],
1513 "+".join(y.lstrip("FILE_ATTRIBUTE_") for y in str(x[1]).split("+")),
1514 human_size(x[2]),
1515 fld.i2repr(None, x[3]),
1516 )
1517 for x in results
1518 ]
1519 print(
1520 pretty_list(
1521 results,
1522 [("FileName", "FileAttributes", "EndOfFile", "LastWriteTime")],
1523 sortBy=None,
1524 )
1525 )
1526
1527 @CLIUtil.addcomplete(ls)
1528 def ls_complete(self, folder):
1529 """
1530 Auto-complete ls
1531 """
1532 if self._require_share(silent=True):
1533 return []
1534 return self._dir_complete(folder)
1535
1536 @CLIUtil.addcommand(mono=True)
1537 def cd(self, folder):
1538 """
1539 Change the remote current directory
1540 """
1541 if self._require_share():
1542 return
1543 if not folder:
1544 # show mode
1545 return str(self.pwd)
1546 self.pwd /= folder
1547 self.pwd = self.collapse_path(self.pwd)
1548 self.ls_cache.clear()
1549
1550 @CLIUtil.addcomplete(cd)
1551 def cd_complete(self, folder):
1552 """
1553 Auto-complete cd
1554 """
1555 if self._require_share(silent=True):
1556 return []
1557 return self._dir_complete(folder)
1558
1559 def _lfs_complete(self, arg, cond):
1560 """
1561 Return a listing of local files for completion purposes
1562 """
1563 eltpar, eltname = self._parsepath(arg, remote=False)
1564 eltpar = self.localpwd / eltpar
1565 return [
1566 # trickery so that ../<TAB> works
1567 str(eltpar / x.name)
1568 for x in eltpar.resolve().glob("*")
1569 if (x.name.lower().startswith(eltname.lower()) and cond(x))
1570 ]
1571
1572 @CLIUtil.addoutput(cd)
1573 def cd_output(self, result):
1574 """
1575 Print the output of 'cd'
1576 """
1577 if result:
1578 print(result)
1579
1580 @CLIUtil.addcommand()
1581 def lls(self):
1582 """
1583 List the files in the local directory
1584 """
1585 return list(self.localpwd.glob("*"))
1586
1587 @CLIUtil.addoutput(lls)
1588 def lls_output(self, results):
1589 """
1590 Print the output of 'lls'
1591 """
1592 results = [
1593 (
1594 x.name,
1595 human_size(stat.st_size),
1596 time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)),
1597 )
1598 for x, stat in ((x, x.stat()) for x in results)
1599 ]
1600 print(
1601 pretty_list(results, [("FileName", "File Size", "Last Modification Time")])
1602 )
1603
1604 @CLIUtil.addcommand(mono=True)
1605 def lcd(self, folder):
1606 """
1607 Change the local current directory
1608 """
1609 if not folder:
1610 # show mode
1611 return str(self.localpwd)
1612 self.localpwd /= folder
1613 self.localpwd = self.localpwd.resolve()
1614
1615 @CLIUtil.addcomplete(lcd)
1616 def lcd_complete(self, folder):
1617 """
1618 Auto-complete lcd
1619 """
1620 return self._lfs_complete(folder, lambda x: x.is_dir())
1621
1622 @CLIUtil.addoutput(lcd)
1623 def lcd_output(self, result):
1624 """
1625 Print the output of 'lcd'
1626 """
1627 if result:
1628 print(result)
1629
1630 def _get_file(self, file, fd):
1631 """
1632 Gets the file bytes from a remote host
1633 """
1634 # Get pwd of the ls
1635 fpath = self.pwd / file
1636 self.smbsock.set_TID(self.current_tree)
1637
1638 # Open file
1639 fileId = self.smbsock.create_request(
1640 self.normalize_path(fpath),
1641 type="file",
1642 extra_create_options=[
1643 "FILE_SEQUENTIAL_ONLY",
1644 ]
1645 + self.extra_create_options,
1646 )
1647
1648 # Get the file size
1649 info = FileAllInformation(
1650 self.smbsock.query_info(
1651 FileId=fileId,
1652 InfoType="SMB2_0_INFO_FILE",
1653 FileInfoClass="FileAllInformation",
1654 )
1655 )
1656 length = info.StandardInformation.EndOfFile
1657 offset = 0
1658
1659 # Read the file
1660 while length:
1661 lengthRead = min(self.smbsock.session.MaxReadSize, length)
1662 fd.write(
1663 self.smbsock.read_request(fileId, Length=lengthRead, Offset=offset)
1664 )
1665 offset += lengthRead
1666 length -= lengthRead
1667
1668 # Close the file
1669 self.smbsock.close_request(fileId)
1670 return offset
1671
1672 def _send_file(self, fname, fd):
1673 """
1674 Send the file bytes to a remote host
1675 """
1676 # Get destination file
1677 fpath = self.pwd / fname
1678 self.smbsock.set_TID(self.current_tree)
1679 # Open file
1680 fileId = self.smbsock.create_request(
1681 self.normalize_path(fpath),
1682 type="file",
1683 mode="w",
1684 extra_create_options=self.extra_create_options,
1685 )
1686 # Send the file
1687 offset = 0
1688 while True:
1689 data = fd.read(self.smbsock.session.MaxWriteSize)
1690 if not data:
1691 # end of file
1692 break
1693 offset += self.smbsock.write_request(
1694 Data=data,
1695 FileId=fileId,
1696 Offset=offset,
1697 )
1698 # Close the file
1699 self.smbsock.close_request(fileId)
1700 return offset
1701
1702 def _listr(self, directory, regx=None, max_depth=None, depth=0, _verb=True):
1703 """
1704 Internal recursive function that yields the remote files
1705 """
1706 if max_depth is not None and depth > max_depth:
1707 return
1708 for x in self.ls(parent=directory):
1709 if x[0] in [".", ".."]:
1710 # Discard . and ..
1711 continue
1712 remote = directory / x[0]
1713 try:
1714 if x[1].FILE_ATTRIBUTE_DIRECTORY:
1715 # Sub-directory
1716 yield from self._listr(
1717 remote,
1718 regx=regx,
1719 depth=depth + 1,
1720 max_depth=max_depth,
1721 _verb=_verb,
1722 )
1723 else:
1724 # Sub-file
1725 if regx is None or regx.match(str(remote)):
1726 yield remote
1727 except ValueError as ex:
1728 if _verb:
1729 print(conf.color_theme.red(directory), "->", str(ex))
1730
1731 def _getr(self, directory, root, dest, _verb=True):
1732 """
1733 Internal recursive function to get a directory
1734
1735 :param directory: the remote directory to get
1736 :param root: the root directory to store files into
1737 :param dest: locally, the directory to store any found files (rec)
1738 """
1739 size = 0
1740 if dest is None:
1741 dest = root
1742 if not dest.exists():
1743 dest.mkdir()
1744 # ls the directory
1745 for x in self.ls(parent=directory):
1746 if x[0] in [".", ".."]:
1747 # Discard . and ..
1748 continue
1749 remote = directory / x[0]
1750 local = dest / x[0]
1751 # Word of caution: this check ONLY works because root and local have been
1752 # resolve(). Be careful
1753 if root not in local.parents and local != root:
1754 raise FileNotFoundError
1755 try:
1756 if x[1].FILE_ATTRIBUTE_DIRECTORY:
1757 # Sub-directory
1758 size += self._getr(remote, root, local)
1759 else:
1760 # Sub-file
1761 size += self.get(remote, local)[1]
1762 if _verb:
1763 print(remote)
1764 except ValueError as ex:
1765 if _verb:
1766 print(conf.color_theme.red(remote), "->", str(ex))
1767 return size
1768
1769 @CLIUtil.addcommand(mono=True, globsupport=True)
1770 def get(self, file, _dest=None, _verb=True, *, r=False):
1771 """
1772 Retrieve a file
1773 -r: recursively download a directory
1774 """
1775 if self._require_share():
1776 return
1777 if r:
1778 dirpar, dirname = self._parsepath(file)
1779 return file, self._getr(
1780 dirpar / dirname, # Remotely
1781 self.localpwd / dirname, # Locally
1782 None,
1783 _verb=_verb,
1784 )
1785 else:
1786 fname = pathlib.PureWindowsPath(file).name
1787 # Write the buffer
1788 if _dest is None:
1789 _dest = self.localpwd / fname
1790 if not _dest.parent.exists():
1791 _dest.parent.mkdir()
1792 with _dest.open("wb") as fd:
1793 size = self._get_file(file, fd)
1794 return fname, size
1795
1796 @CLIUtil.addoutput(get)
1797 def get_output(self, info):
1798 """
1799 Print the output of 'get'
1800 """
1801 print("Retrieved '%s' of size %s" % (info[0], human_size(info[1])))
1802
1803 @CLIUtil.addcomplete(get)
1804 def get_complete(self, file):
1805 """
1806 Auto-complete get
1807 """
1808 if self._require_share(silent=True):
1809 return []
1810 return self._fs_complete(file)
1811
1812 @CLIUtil.addcommand()
1813 def tree(self, regx: str = None, max_depth=None):
1814 """
1815 Show the tree of files from the current directory
1816 """
1817 if self._require_share():
1818 return
1819 if regx is not None:
1820 regx = re.compile(regx)
1821 if max_depth is not None:
1822 max_depth = int(max_depth)
1823 return self._listr(self.pwd, regx=regx, max_depth=max_depth)
1824
1825 @CLIUtil.addoutput(tree)
1826 def tree_output(self, result):
1827 """
1828 Print the output of 'tree'
1829 """
1830 if self._require_share(silent=True):
1831 return
1832 for file in result:
1833 print(str(file), flush=True)
1834
1835 @CLIUtil.addcommand()
1836 def server(self, command):
1837 """
1838 Get information about the remote server
1839 """
1840 if command == "network":
1841 # We get the list of interfaces
1842 if self._require_share():
1843 return
1844 resp = self.smbsock.ioctl(CtlCode="FSCTL_QUERY_NETWORK_INTERFACE_INFO")
1845 return (command, resp)
1846 elif command == "sessions":
1847 # We get the list of active connections via RPC
1848 self.rpcclient.open_smbpipe("srvsvc")
1849 self.rpcclient.bind(find_dcerpc_interface("srvsvc"))
1850 ResumeHandle = None
1851 results = []
1852 while True:
1853 req = NetrSessionEnum_Request(
1854 ClientName=None,
1855 UserName=None,
1856 InfoStruct=PSESSION_ENUM_STRUCT(
1857 Level=502,
1858 SessionInfo=NDRUnion(
1859 tag=502,
1860 value=SESSION_INFO_502_CONTAINER(Buffer=None),
1861 ),
1862 ),
1863 PreferedMaximumLength=0xFFFFFFFF,
1864 ResumeHandle=ResumeHandle,
1865 )
1866 resp = self.rpcclient.sr1_req(req, timeout=self.timeout)
1867 resp.show()
1868 ResumeHandle = resp.ResumeHandle
1869 if resp.status in [0, 0x000000EA]: # ERROR_SUCCESS / ERROR_MORE_DATA
1870 results.extend(resp.valueof("InfoStruct.SessionInfo.Buffer"))
1871 if resp.status == 0:
1872 break
1873 else:
1874 break
1875 self.rpcclient.close_smbpipe()
1876 return (command, results)
1877 else:
1878 raise ValueError("Unknown server command: %s" % command)
1879
1880 @CLIUtil.addoutput(server)
1881 def server_output(self, result):
1882 """
1883 Print the output of 'server'
1884 """
1885 command, result = result
1886 if command == "network":
1887 # Show the various interfaces, their IP and capabilities
1888 result.interfaces = [x for x in result.interfaces if x.IfIndex != 0]
1889 result.show()
1890 elif command == "sessions":
1891 # Show the list of active sessions
1892 for sess in result:
1893 print("- cname:", sess.valueof("sesi502_cname"))
1894 print(" username:", sess.valueof("sesi502_username"))
1895 print(" num_opens:", sess.valueof("sesi502_num_opens"))
1896 print(" time:", sess.valueof("sesi502_time"))
1897 print(" idle_time:", sess.valueof("sesi502_idle_time"))
1898 print(" user_flags:", sess.valueof("sesi502_user_flags"))
1899 print(" cltype_name:", sess.valueof("sesi502_cltype_name"))
1900 print(" transport:", sess.valueof("sesi502_transport"))
1901
1902 @CLIUtil.addcomplete(server)
1903 def server_complete(self, line):
1904 """
1905 Auto-complete server
1906 """
1907 return ["network", "sessions"]
1908
1909 @CLIUtil.addcommand(mono=True, globsupport=True)
1910 def cat(self, file):
1911 """
1912 Print a file
1913 """
1914 if self._require_share():
1915 return
1916 # Write the buffer to buffer
1917 buf = io.BytesIO()
1918 self._get_file(file, buf)
1919 return buf.getvalue()
1920
1921 @CLIUtil.addoutput(cat)
1922 def cat_output(self, result):
1923 """
1924 Print the output of 'cat'
1925 """
1926 print(result.decode(errors="backslashreplace"))
1927
1928 @CLIUtil.addcomplete(cat)
1929 def cat_complete(self, file):
1930 """
1931 Auto-complete cat
1932 """
1933 if self._require_share(silent=True):
1934 return []
1935 return self._fs_complete(file)
1936
1937 @CLIUtil.addcommand(mono=True, globsupport=True)
1938 def put(self, file):
1939 """
1940 Upload a file
1941 """
1942 if self._require_share():
1943 return
1944 local_file = self.localpwd / file
1945 if local_file.is_dir():
1946 # Directory
1947 raise ValueError("put on dir not impl")
1948 else:
1949 fname = pathlib.Path(file).name
1950 with local_file.open("rb") as fd:
1951 size = self._send_file(fname, fd)
1952 self.ls_cache.clear()
1953 return fname, size
1954
1955 @CLIUtil.addcomplete(put)
1956 def put_complete(self, folder):
1957 """
1958 Auto-complete put
1959 """
1960 return self._lfs_complete(folder, lambda x: not x.is_dir())
1961
1962 @CLIUtil.addcommand(mono=True)
1963 def rm(self, file):
1964 """
1965 Delete a file
1966 """
1967 if self._require_share():
1968 return
1969 # Get pwd of the ls
1970 fpath = self.pwd / file
1971 self.smbsock.set_TID(self.current_tree)
1972 # Open file
1973 fileId = self.smbsock.create_request(
1974 self.normalize_path(fpath),
1975 type="file",
1976 mode="d",
1977 extra_create_options=self.extra_create_options,
1978 )
1979 # Close the file
1980 self.smbsock.close_request(fileId)
1981 self.ls_cache.clear()
1982 return fpath.name
1983
1984 @CLIUtil.addcomplete(rm)
1985 def rm_complete(self, file):
1986 """
1987 Auto-complete rm
1988 """
1989 if self._require_share(silent=True):
1990 return []
1991 return self._fs_complete(file)
1992
1993 @CLIUtil.addcommand()
1994 def backup(self):
1995 """
1996 Turn on or off backup intent
1997 """
1998 if "FILE_OPEN_FOR_BACKUP_INTENT" in self.extra_create_options:
1999 print("Backup Intent: Off")
2000 self.extra_create_options.remove("FILE_OPEN_FOR_BACKUP_INTENT")
2001 else:
2002 print("Backup Intent: On")
2003 self.extra_create_options.append("FILE_OPEN_FOR_BACKUP_INTENT")
2004
2005 @CLIUtil.addcommand(mono=True)
2006 def watch(self, folder):
2007 """
2008 Watch file changes in folder (recursively)
2009 """
2010 if self._require_share():
2011 return
2012 # Get pwd of the ls
2013 fpath = self.pwd / folder
2014 self.smbsock.set_TID(self.current_tree)
2015 # Open file
2016 fileId = self.smbsock.create_request(
2017 self.normalize_path(fpath),
2018 type="folder",
2019 extra_create_options=self.extra_create_options,
2020 )
2021 print("Watching '%s'" % fpath)
2022 # Watch for changes
2023 try:
2024 while True:
2025 changes = self.smbsock.changenotify(fileId)
2026 for chg in changes:
2027 print(chg.sprintf("%.time%: %Action% %FileName%"))
2028 except KeyboardInterrupt:
2029 pass
2030 print("Cancelled.")
2031
2032 @CLIUtil.addcommand(mono=True)
2033 def getsd(self, file):
2034 """
2035 Get the Security Descriptor
2036 """
2037 if self._require_share():
2038 return
2039 fpath = self.pwd / file
2040 self.smbsock.set_TID(self.current_tree)
2041 # Open file
2042 fileId = self.smbsock.create_request(
2043 self.normalize_path(fpath),
2044 type="",
2045 mode="",
2046 extra_desired_access=["READ_CONTROL", "ACCESS_SYSTEM_SECURITY"],
2047 )
2048 # Get the file size
2049 info = self.smbsock.query_info(
2050 FileId=fileId,
2051 InfoType="SMB2_0_INFO_SECURITY",
2052 FileInfoClass=0,
2053 AdditionalInformation=(
2054 0x00000001
2055 | 0x00000002
2056 | 0x00000004
2057 | 0x00000008
2058 | 0x00000010
2059 | 0x00000020
2060 | 0x00000040
2061 | 0x00010000
2062 ),
2063 )
2064 self.smbsock.close_request(fileId)
2065 return info
2066
2067 @CLIUtil.addcomplete(getsd)
2068 def getsd_complete(self, file):
2069 """
2070 Auto-complete getsd
2071 """
2072 if self._require_share(silent=True):
2073 return []
2074 return self._fs_complete(file)
2075
2076 @CLIUtil.addoutput(getsd)
2077 def getsd_output(self, results):
2078 """
2079 Print the output of 'getsd'
2080 """
2081 sd = SECURITY_DESCRIPTOR(results)
2082 sd.show_print()
2083
2084
2085if __name__ == "__main__":
2086 from scapy.utils import AutoArgparse
2087
2088 AutoArgparse(smbclient)