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