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.base_classes import Net
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 valid_ip,
33 valid_ip6,
34)
35from scapy.volatile import RandUUID
36
37from scapy.layers.dcerpc import NDRUnion, find_dcerpc_interface
38from scapy.layers.gssapi import (
39 GSS_S_COMPLETE,
40 GSS_S_CONTINUE_NEEDED,
41 GSS_C_FLAGS,
42)
43from scapy.layers.inet6 import Net6
44from scapy.layers.kerberos import (
45 KerberosSSP,
46 krb_as_and_tgs,
47 _parse_upn,
48)
49from scapy.layers.msrpce.raw.ms_srvs import (
50 LPSHARE_ENUM_STRUCT,
51 NetrShareEnum_Request,
52 NetrShareEnum_Response,
53 SHARE_INFO_1_CONTAINER,
54)
55from scapy.layers.ntlm import (
56 NTLMSSP,
57 MD4le,
58)
59from scapy.layers.smb import (
60 SMBNegotiate_Request,
61 SMBNegotiate_Response_Extended_Security,
62 SMBNegotiate_Response_Security,
63 SMBSession_Null,
64 SMBSession_Setup_AndX_Request,
65 SMBSession_Setup_AndX_Request_Extended_Security,
66 SMBSession_Setup_AndX_Response,
67 SMBSession_Setup_AndX_Response_Extended_Security,
68 SMB_Dialect,
69 SMB_Header,
70)
71from scapy.layers.smb2 import (
72 DirectTCP,
73 FileAllInformation,
74 FileIdBothDirectoryInformation,
75 SECURITY_DESCRIPTOR,
76 SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2,
77 SMB2_CREATE_REQUEST_LEASE,
78 SMB2_CREATE_REQUEST_LEASE_V2,
79 SMB2_Change_Notify_Request,
80 SMB2_Change_Notify_Response,
81 SMB2_Close_Request,
82 SMB2_Close_Response,
83 SMB2_Create_Context,
84 SMB2_Create_Request,
85 SMB2_Create_Response,
86 SMB2_ENCRYPTION_CIPHERS,
87 SMB2_Encryption_Capabilities,
88 SMB2_Error_Response,
89 SMB2_Header,
90 SMB2_IOCTL_Request,
91 SMB2_IOCTL_Response,
92 SMB2_Negotiate_Context,
93 SMB2_Negotiate_Protocol_Request,
94 SMB2_Negotiate_Protocol_Response,
95 SMB2_Netname_Negotiate_Context_ID,
96 SMB2_Preauth_Integrity_Capabilities,
97 SMB2_Query_Directory_Request,
98 SMB2_Query_Directory_Response,
99 SMB2_Query_Info_Request,
100 SMB2_Query_Info_Response,
101 SMB2_Read_Request,
102 SMB2_Read_Response,
103 SMB2_SIGNING_ALGORITHMS,
104 SMB2_Session_Setup_Request,
105 SMB2_Session_Setup_Response,
106 SMB2_Signing_Capabilities,
107 SMB2_Tree_Connect_Request,
108 SMB2_Tree_Connect_Response,
109 SMB2_Tree_Disconnect_Request,
110 SMB2_Tree_Disconnect_Response,
111 SMB2_Write_Request,
112 SMB2_Write_Response,
113 SMBStreamSocket,
114 SMB_DIALECTS,
115 SRVSVC_SHARE_TYPES,
116 STATUS_ERREF,
117)
118from scapy.layers.spnego import SPNEGOSSP
119
120
121class SMB_Client(Automaton):
122 """
123 SMB client automaton
124
125 :param sock: the SMBStreamSocket to use
126 :param ssp: the SSP to use
127
128 All other options (in caps) are optional, and SMB specific:
129
130 :param REQUIRE_SIGNATURE: set 'Require Signature'
131 :param REQUIRE_ENCRYPTION: set 'Requite Encryption'
132 :param MIN_DIALECT: minimum SMB dialect. Defaults to 0x0202 (2.0.2)
133 :param MAX_DIALECT: maximum SMB dialect. Defaults to 0x0311 (3.1.1)
134 :param DIALECTS: list of supported SMB2 dialects.
135 Constructed from MIN_DIALECT, MAX_DIALECT otherwise.
136 """
137
138 port = 445
139 cls = DirectTCP
140
141 def __init__(self, sock, ssp=None, *args, **kwargs):
142 # Various SMB client arguments
143 self.EXTENDED_SECURITY = kwargs.pop("EXTENDED_SECURITY", True)
144 self.USE_SMB1 = kwargs.pop("USE_SMB1", False)
145 self.REQUIRE_SIGNATURE = kwargs.pop("REQUIRE_SIGNATURE", None)
146 self.REQUIRE_ENCRYPTION = kwargs.pop("REQUIRE_ENCRYPTION", False)
147 self.RETRY = kwargs.pop("RETRY", 0) # optionally: retry n times session setup
148 self.SMB2 = kwargs.pop("SMB2", False) # optionally: start directly in SMB2
149 self.SERVER_NAME = kwargs.pop("SERVER_NAME", "")
150 # Store supported dialects
151 if "DIALECTS" in kwargs:
152 self.DIALECTS = kwargs.pop("DIALECTS")
153 else:
154 MIN_DIALECT = kwargs.pop("MIN_DIALECT", 0x0202)
155 self.MAX_DIALECT = kwargs.pop("MAX_DIALECT", 0x0311)
156 self.DIALECTS = sorted(
157 [
158 x
159 for x in [0x0202, 0x0210, 0x0300, 0x0302, 0x0311]
160 if x >= MIN_DIALECT and x <= self.MAX_DIALECT
161 ]
162 )
163 # Internal Session information
164 self.ErrorStatus = None
165 self.NegotiateCapabilities = None
166 self.GUID = RandUUID()._fix()
167 self.SequenceWindow = (0, 0) # keep track of allowed MIDs
168 if ssp is None:
169 # We got no SSP. Assuming the server allows anonymous
170 ssp = SPNEGOSSP(
171 [
172 NTLMSSP(
173 UPN="guest",
174 HASHNT=b"",
175 )
176 ]
177 )
178 # Initialize
179 kwargs["sock"] = sock
180 Automaton.__init__(
181 self,
182 *args,
183 **kwargs,
184 )
185 if self.is_atmt_socket:
186 self.smb_sock_ready = threading.Event()
187 # Set session options
188 self.session.ssp = ssp
189 self.session.SigningRequired = (
190 self.REQUIRE_SIGNATURE if self.REQUIRE_SIGNATURE is not None else bool(ssp)
191 )
192 self.session.Dialect = self.MAX_DIALECT
193
194 @classmethod
195 def from_tcpsock(cls, sock, **kwargs):
196 return cls.smblink(
197 None,
198 SMBStreamSocket(sock, DirectTCP),
199 **kwargs,
200 )
201
202 @property
203 def session(self):
204 # session shorthand
205 return self.sock.session
206
207 def send(self, pkt):
208 # Calculate what CreditCharge to send.
209 if self.session.Dialect > 0x0202 and isinstance(pkt.payload, SMB2_Header):
210 # [MS-SMB2] sect 3.2.4.1.5
211 typ = type(pkt.payload.payload)
212 if typ is SMB2_Negotiate_Protocol_Request:
213 # See [MS-SMB2] 3.2.4.1.2 note
214 pkt.CreditCharge = 0
215 elif typ in [
216 SMB2_Read_Request,
217 SMB2_Write_Request,
218 SMB2_IOCTL_Request,
219 SMB2_Query_Directory_Request,
220 SMB2_Change_Notify_Request,
221 SMB2_Query_Info_Request,
222 ]:
223 # [MS-SMB2] 3.1.5.2
224 # "For READ, WRITE, IOCTL, and QUERY_DIRECTORY requests"
225 # "CHANGE_NOTIFY, QUERY_INFO, or SET_INFO"
226 if typ == SMB2_Read_Request:
227 Length = pkt.payload.Length
228 elif typ == SMB2_Write_Request:
229 Length = len(pkt.payload.Data)
230 elif typ == SMB2_IOCTL_Request:
231 # [MS-SMB2] 3.3.5.15
232 Length = max(len(pkt.payload.Input), pkt.payload.MaxOutputResponse)
233 elif typ in [
234 SMB2_Query_Directory_Request,
235 SMB2_Change_Notify_Request,
236 SMB2_Query_Info_Request,
237 ]:
238 Length = pkt.payload.OutputBufferLength
239 else:
240 raise RuntimeError("impossible case")
241 pkt.CreditCharge = 1 + (Length - 1) // 65536
242 else:
243 # "For all other requests, the client MUST set CreditCharge to 1"
244 pkt.CreditCharge = 1
245 # [MS-SMB2] 3.2.4.1.2
246 pkt.CreditRequest = pkt.CreditCharge + 1 # this code is a bit lazy
247 # Get first available message ID: [MS-SMB2] 3.2.4.1.3 and 3.2.4.1.5
248 pkt.MID = self.SequenceWindow[0]
249 return super(SMB_Client, self).send(pkt)
250
251 @ATMT.state(initial=1)
252 def BEGIN(self):
253 pass
254
255 @ATMT.condition(BEGIN)
256 def continue_smb2(self):
257 if self.SMB2: # Directly started in SMB2
258 self.smb_header = DirectTCP() / SMB2_Header(PID=0xFEFF)
259 raise self.SMB2_NEGOTIATE()
260
261 @ATMT.condition(BEGIN, prio=1)
262 def send_negotiate(self):
263 raise self.SENT_NEGOTIATE()
264
265 @ATMT.action(send_negotiate)
266 def on_negotiate(self):
267 # [MS-SMB2] sect 3.2.4.2.2.1 - Multi-Protocol Negotiate
268 self.smb_header = DirectTCP() / SMB_Header(
269 Flags2=(
270 "LONG_NAMES+EAS+NT_STATUS+UNICODE+"
271 "SMB_SECURITY_SIGNATURE+EXTENDED_SECURITY"
272 ),
273 TID=0xFFFF,
274 PIDLow=0xFEFF,
275 UID=0,
276 MID=0,
277 )
278 if self.EXTENDED_SECURITY:
279 self.smb_header.Flags2 += "EXTENDED_SECURITY"
280 pkt = self.smb_header.copy() / SMBNegotiate_Request(
281 Dialects=[
282 SMB_Dialect(DialectString=x)
283 for x in [
284 "PC NETWORK PROGRAM 1.0",
285 "LANMAN1.0",
286 "Windows for Workgroups 3.1a",
287 "LM1.2X002",
288 "LANMAN2.1",
289 "NT LM 0.12",
290 ]
291 + (["SMB 2.002", "SMB 2.???"] if not self.USE_SMB1 else [])
292 ],
293 )
294 if not self.EXTENDED_SECURITY:
295 pkt.Flags2 -= "EXTENDED_SECURITY"
296 pkt[SMB_Header].Flags2 = (
297 pkt[SMB_Header].Flags2
298 - "SMB_SECURITY_SIGNATURE"
299 + "SMB_SECURITY_SIGNATURE_REQUIRED+IS_LONG_NAME"
300 )
301 self.send(pkt)
302
303 @ATMT.state()
304 def SENT_NEGOTIATE(self):
305 pass
306
307 @ATMT.state()
308 def SMB2_NEGOTIATE(self):
309 pass
310
311 @ATMT.condition(SMB2_NEGOTIATE)
312 def send_negotiate_smb2(self):
313 raise self.SENT_NEGOTIATE()
314
315 @ATMT.action(send_negotiate_smb2)
316 def on_negotiate_smb2(self):
317 # [MS-SMB2] sect 3.2.4.2.2.2 - SMB2-Only Negotiate
318 pkt = self.smb_header.copy() / SMB2_Negotiate_Protocol_Request(
319 Dialects=self.DIALECTS,
320 SecurityMode=(
321 "SIGNING_ENABLED+SIGNING_REQUIRED"
322 if self.session.SigningRequired
323 else "SIGNING_ENABLED"
324 ),
325 )
326 if self.MAX_DIALECT >= 0x0210:
327 # "If the client implements the SMB 2.1 or SMB 3.x dialect, ClientGuid
328 # MUST be set to the global ClientGuid value"
329 pkt.ClientGUID = self.GUID
330 # Capabilities: same as [MS-SMB2] 3.3.5.4
331 self.NegotiateCapabilities = "+".join(
332 [
333 "DFS",
334 "LEASING",
335 "LARGE_MTU",
336 ]
337 )
338 if self.MAX_DIALECT >= 0x0300:
339 # "if Connection.Dialect belongs to the SMB 3.x dialect family ..."
340 self.NegotiateCapabilities += "+" + "+".join(
341 [
342 "MULTI_CHANNEL",
343 "PERSISTENT_HANDLES",
344 "DIRECTORY_LEASING",
345 "ENCRYPTION",
346 ]
347 )
348 if self.MAX_DIALECT >= 0x0311:
349 # "If the client implements the SMB 3.1.1 dialect, it MUST do"
350 pkt.NegotiateContexts = [
351 SMB2_Negotiate_Context()
352 / SMB2_Preauth_Integrity_Capabilities(
353 # As for today, no other hash algorithm is described by the spec
354 HashAlgorithms=["SHA-512"],
355 Salt=self.session.Salt,
356 ),
357 SMB2_Negotiate_Context()
358 / SMB2_Encryption_Capabilities(
359 Ciphers=self.session.SupportedCipherIds,
360 ),
361 # TODO support compression and RDMA
362 SMB2_Negotiate_Context()
363 / SMB2_Netname_Negotiate_Context_ID(
364 NetName=self.SERVER_NAME,
365 ),
366 SMB2_Negotiate_Context()
367 / SMB2_Signing_Capabilities(
368 SigningAlgorithms=self.session.SupportedSigningAlgorithmIds,
369 ),
370 ]
371 pkt.Capabilities = self.NegotiateCapabilities
372 # Send
373 self.send(pkt)
374 # If required, compute sessions
375 self.session.computeSMBConnectionPreauth(
376 bytes(pkt[SMB2_Header]), # nego request
377 )
378
379 @ATMT.receive_condition(SENT_NEGOTIATE)
380 def receive_negotiate_response(self, pkt):
381 if (
382 SMBNegotiate_Response_Extended_Security in pkt
383 or SMB2_Negotiate_Protocol_Response in pkt
384 ):
385 # Extended SMB1 / SMB2
386 try:
387 ssp_blob = pkt.SecurityBlob # eventually SPNEGO server initiation
388 except AttributeError:
389 ssp_blob = None
390 if (
391 SMB2_Negotiate_Protocol_Response in pkt
392 and pkt.DialectRevision & 0xFF == 0xFF
393 ):
394 # Version is SMB X.???
395 # [MS-SMB2] 3.2.5.2
396 # If the DialectRevision field in the SMB2 NEGOTIATE Response is
397 # 0x02FF ... the client MUST allocate sequence number 1 from
398 # Connection.SequenceWindow, and MUST set MessageId field of the
399 # SMB2 header to 1.
400 self.SequenceWindow = (1, 1)
401 self.smb_header = DirectTCP() / SMB2_Header(PID=0xFEFF, MID=1)
402 self.SMB2 = True # We're now using SMB2 to talk to the server
403 raise self.SMB2_NEGOTIATE()
404 else:
405 if SMB2_Negotiate_Protocol_Response in pkt:
406 # SMB2 was negotiated !
407 self.session.Dialect = pkt.DialectRevision
408 # If required, compute sessions
409 self.session.computeSMBConnectionPreauth(
410 bytes(pkt[SMB2_Header]), # nego response
411 )
412 # Process max sizes
413 self.session.MaxReadSize = pkt.MaxReadSize
414 self.session.MaxTransactionSize = pkt.MaxTransactionSize
415 self.session.MaxWriteSize = pkt.MaxWriteSize
416 # Process SecurityMode
417 if pkt.SecurityMode.SIGNING_REQUIRED:
418 self.session.SigningRequired = True
419 # Process capabilities
420 if self.session.Dialect >= 0x0300:
421 self.session.SupportsEncryption = pkt.Capabilities.ENCRYPTION
422 # Process NegotiateContext
423 if self.session.Dialect >= 0x0311 and pkt.NegotiateContextsCount:
424 for ngctx in pkt.NegotiateContexts:
425 if ngctx.ContextType == 0x0002:
426 # SMB2_ENCRYPTION_CAPABILITIES
427 if ngctx.Ciphers[0] != 0:
428 self.session.CipherId = SMB2_ENCRYPTION_CIPHERS[
429 ngctx.Ciphers[0]
430 ]
431 self.session.SupportsEncryption = True
432 elif ngctx.ContextType == 0x0008:
433 # SMB2_SIGNING_CAPABILITIES
434 self.session.SigningAlgorithmId = (
435 SMB2_SIGNING_ALGORITHMS[ngctx.SigningAlgorithms[0]]
436 )
437 if self.REQUIRE_ENCRYPTION and not self.session.SupportsEncryption:
438 self.ErrorStatus = "NEGOTIATE FAILURE: encryption."
439 raise self.NEGO_FAILED()
440 self.update_smbheader(pkt)
441 raise self.NEGOTIATED(ssp_blob)
442 elif SMBNegotiate_Response_Security in pkt:
443 # Non-extended SMB1
444 # Never tested. FIXME. probably broken
445 raise self.NEGOTIATED(pkt.Challenge)
446
447 @ATMT.state(final=1)
448 def NEGO_FAILED(self):
449 self.smb_sock_ready.set()
450
451 @ATMT.state()
452 def NEGOTIATED(self, ssp_blob=None):
453 # Negotiated ! We now know the Dialect
454 if self.session.Dialect > 0x0202:
455 # [MS-SMB2] sect 3.2.5.1.4
456 self.smb_header.CreditRequest = 1
457 # Begin session establishment
458 ssp_tuple = self.session.ssp.GSS_Init_sec_context(
459 self.session.sspcontext,
460 token=ssp_blob,
461 req_flags=(
462 GSS_C_FLAGS.GSS_C_MUTUAL_FLAG
463 | (GSS_C_FLAGS.GSS_C_INTEG_FLAG if self.session.SigningRequired else 0)
464 ),
465 )
466 return ssp_tuple
467
468 def update_smbheader(self, pkt):
469 """
470 Called when receiving a SMB2 packet to update the current smb_header
471 """
472 # Some values should not be updated when ASYNC
473 if not pkt.Flags.SMB2_FLAGS_ASYNC_COMMAND:
474 # Update IDs
475 self.smb_header.SessionId = pkt.SessionId
476 self.smb_header.TID = pkt.TID
477 self.smb_header.PID = pkt.PID
478 # [MS-SMB2] 3.2.5.1.4
479 self.SequenceWindow = (
480 self.SequenceWindow[0] + max(pkt.CreditCharge, 1),
481 self.SequenceWindow[1] + pkt.CreditRequest,
482 )
483
484 # DEV: add a condition on NEGOTIATED with prio=0
485
486 @ATMT.condition(NEGOTIATED, prio=1)
487 def should_send_session_setup_request(self, ssp_tuple):
488 _, _, negResult = ssp_tuple
489 if negResult not in [GSS_S_COMPLETE, GSS_S_CONTINUE_NEEDED]:
490 raise ValueError("Internal error: the SSP completed with an error.")
491 raise self.SENT_SESSION_REQUEST().action_parameters(ssp_tuple)
492
493 @ATMT.state()
494 def SENT_SESSION_REQUEST(self):
495 pass
496
497 @ATMT.action(should_send_session_setup_request)
498 def send_setup_session_request(self, ssp_tuple):
499 self.session.sspcontext, token, negResult = ssp_tuple
500 if self.SMB2 and negResult == GSS_S_CONTINUE_NEEDED:
501 # New session: force 0
502 self.SessionId = 0
503 if self.SMB2 or self.EXTENDED_SECURITY:
504 # SMB1 extended / SMB2
505 if self.SMB2:
506 # SMB2
507 pkt = self.smb_header.copy() / SMB2_Session_Setup_Request(
508 Capabilities="DFS",
509 SecurityMode=(
510 "SIGNING_ENABLED+SIGNING_REQUIRED"
511 if self.session.SigningRequired
512 else "SIGNING_ENABLED"
513 ),
514 )
515 else:
516 # SMB1 extended
517 pkt = (
518 self.smb_header.copy()
519 / SMBSession_Setup_AndX_Request_Extended_Security(
520 ServerCapabilities=(
521 "UNICODE+NT_SMBS+STATUS32+LEVEL_II_OPLOCKS+"
522 "DYNAMIC_REAUTH+EXTENDED_SECURITY"
523 ),
524 NativeOS=b"",
525 NativeLanMan=b"",
526 )
527 )
528 pkt.SecurityBlob = token
529 else:
530 # Non-extended security.
531 pkt = self.smb_header.copy() / SMBSession_Setup_AndX_Request(
532 ServerCapabilities="UNICODE+NT_SMBS+STATUS32+LEVEL_II_OPLOCKS",
533 NativeOS=b"",
534 NativeLanMan=b"",
535 OEMPassword=b"\0" * 24,
536 UnicodePassword=token,
537 )
538 self.send(pkt)
539 if self.SMB2:
540 # If required, compute sessions
541 self.session.computeSMBSessionPreauth(
542 bytes(pkt[SMB2_Header]), # session request
543 )
544
545 @ATMT.receive_condition(SENT_SESSION_REQUEST)
546 def receive_session_setup_response(self, pkt):
547 if (
548 SMBSession_Null in pkt
549 or SMBSession_Setup_AndX_Response_Extended_Security in pkt
550 or SMBSession_Setup_AndX_Response in pkt
551 ):
552 # SMB1
553 if SMBSession_Null in pkt:
554 # Likely an error
555 raise self.NEGOTIATED()
556 # Logging
557 if pkt.Status != 0 and pkt.Status != 0xC0000016:
558 # Not SUCCESS nor MORE_PROCESSING_REQUIRED: log
559 self.ErrorStatus = pkt.sprintf("%SMB2_Header.Status%")
560 self.debug(
561 lvl=1,
562 msg=conf.color_theme.red(
563 pkt.sprintf("SMB Session Setup Response: %SMB2_Header.Status%")
564 ),
565 )
566 if self.SMB2:
567 self.update_smbheader(pkt)
568 # Cases depending on the response packet
569 if (
570 SMBSession_Setup_AndX_Response_Extended_Security in pkt
571 or SMB2_Session_Setup_Response in pkt
572 ):
573 # The server assigns us a SessionId
574 self.smb_header.SessionId = pkt.SessionId
575 # SMB1 extended / SMB2
576 if pkt.Status == 0: # Authenticated
577 if SMB2_Session_Setup_Response in pkt:
578 # [MS-SMB2] sect 3.2.5.3.1
579 if pkt.SessionFlags.IS_GUEST:
580 # "If the security subsystem indicates that the session
581 # was established by a guest user, Session.SigningRequired
582 # MUST be set to FALSE and Session.IsGuest MUST be set to TRUE."
583 self.session.IsGuest = True
584 self.session.SigningRequired = False
585 elif self.session.Dialect >= 0x0300:
586 if pkt.SessionFlags.ENCRYPT_DATA or self.REQUIRE_ENCRYPTION:
587 self.session.EncryptData = True
588 self.session.SigningRequired = False
589 raise self.AUTHENTICATED(pkt.SecurityBlob)
590 else:
591 if SMB2_Header in pkt:
592 # If required, compute sessions
593 self.session.computeSMBSessionPreauth(
594 bytes(pkt[SMB2_Header]), # session response
595 )
596 # Ongoing auth
597 raise self.NEGOTIATED(pkt.SecurityBlob)
598 elif SMBSession_Setup_AndX_Response_Extended_Security in pkt:
599 # SMB1 non-extended
600 pass
601 elif SMB2_Error_Response in pkt:
602 # Authentication failure
603 self.session.sspcontext.clifailure()
604 # Reset Session preauth (SMB 3.1.1)
605 self.session.SessionPreauthIntegrityHashValue = None
606 if not self.RETRY:
607 raise self.AUTH_FAILED()
608 self.debug(lvl=2, msg="RETRY: %s" % self.RETRY)
609 self.RETRY -= 1
610 raise self.NEGOTIATED()
611
612 @ATMT.state(final=1)
613 def AUTH_FAILED(self):
614 self.smb_sock_ready.set()
615
616 @ATMT.state()
617 def AUTHENTICATED(self, ssp_blob=None):
618 self.session.sspcontext, _, status = self.session.ssp.GSS_Init_sec_context(
619 self.session.sspcontext,
620 token=ssp_blob,
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.ins.atmt.session.sspcontext:
687 self.ins.atmt.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,
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,
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:
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 smbclient CLI
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: if available, whether to use Kerberos or not
1108 :param kerberos_required: require kerberos
1109 :param port: the TCP port. default 445
1110 :param password: (string) if provided, used for auth
1111 :param HashNt: (bytes) if provided, used for auth (NTLM)
1112 :param ST: if provided, the service ticket to use (Kerberos)
1113 :param KEY: if provided, the session key associated to the ticket (Kerberos)
1114 :param cli: CLI mode (default True). False to use for scripting
1115
1116 Some additional SMB parameters are available under help(SMB_Client). Some of
1117 them include the following:
1118
1119 :param REQUIRE_ENCRYPTION: requires encryption.
1120 """
1121
1122 def __init__(
1123 self,
1124 target: str,
1125 UPN: str = None,
1126 password: str = None,
1127 guest: bool = False,
1128 kerberos: bool = True,
1129 kerberos_required: bool = False,
1130 HashNt: str = None,
1131 port: int = 445,
1132 timeout: int = 2,
1133 debug: int = 0,
1134 ssp=None,
1135 ST=None,
1136 KEY=None,
1137 cli=True,
1138 # SMB arguments
1139 REQUIRE_ENCRYPTION=False,
1140 **kwargs,
1141 ):
1142 if cli:
1143 self._depcheck()
1144 hostname = None
1145 # Check if target is a hostname / Check IP
1146 if ":" in target:
1147 family = socket.AF_INET6
1148 if not valid_ip6(target):
1149 hostname = target
1150 target = str(Net6(target))
1151 else:
1152 family = socket.AF_INET
1153 if not valid_ip(target):
1154 hostname = target
1155 target = str(Net(target))
1156 assert UPN or ssp or guest, "Either UPN, ssp or guest must be provided !"
1157 # Do we need to build a SSP?
1158 if ssp is None:
1159 # Create the SSP (only if not guest mode)
1160 if not guest:
1161 # Check UPN
1162 try:
1163 _, realm = _parse_upn(UPN)
1164 if realm == ".":
1165 # Local
1166 kerberos = False
1167 except ValueError:
1168 # not a UPN: NTLM
1169 kerberos = False
1170 # Do we need to ask the password?
1171 if HashNt is None and password is None and ST is None:
1172 # yes.
1173 from prompt_toolkit import prompt
1174
1175 password = prompt("Password: ", is_password=True)
1176 ssps = []
1177 # Kerberos
1178 if kerberos and hostname:
1179 if ST is None:
1180 resp = krb_as_and_tgs(
1181 upn=UPN,
1182 spn="cifs/%s" % hostname,
1183 password=password,
1184 debug=debug,
1185 )
1186 if resp is not None:
1187 ST, KEY = resp.tgsrep.ticket, resp.sessionkey
1188 if ST:
1189 ssps.append(KerberosSSP(UPN=UPN, ST=ST, KEY=KEY, debug=debug))
1190 elif kerberos_required:
1191 raise ValueError(
1192 "Kerberos required but target isn't a hostname !"
1193 )
1194 elif kerberos_required:
1195 raise ValueError(
1196 "Kerberos required but domain not specified in the UPN, "
1197 "or target isn't a hostname !"
1198 )
1199 # NTLM
1200 if not kerberos_required:
1201 if HashNt is None and password is not None:
1202 HashNt = MD4le(password)
1203 ssps.append(NTLMSSP(UPN=UPN, HASHNT=HashNt))
1204 # Build the SSP
1205 ssp = SPNEGOSSP(ssps)
1206 else:
1207 # Guest mode
1208 ssp = None
1209 # Open socket
1210 sock = socket.socket(family, socket.SOCK_STREAM)
1211 # Configure socket for SMB:
1212 # - TCP KEEPALIVE, TCP_KEEPIDLE and TCP_KEEPINTVL. Against a Windows server this
1213 # isn't necessary, but samba kills the socket VERY fast otherwise.
1214 # - set TCP_NODELAY to disable Nagle's algorithm (we're streaming data)
1215 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
1216 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1217 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10)
1218 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10)
1219 # Timeout & connect
1220 sock.settimeout(timeout)
1221 sock.connect((target, port))
1222 self.extra_create_options = []
1223 # Wrap with the automaton
1224 self.timeout = timeout
1225 kwargs.setdefault("SERVER_NAME", target)
1226 self.sock = SMB_Client.from_tcpsock(
1227 sock,
1228 ssp=ssp,
1229 debug=debug,
1230 REQUIRE_ENCRYPTION=REQUIRE_ENCRYPTION,
1231 timeout=timeout,
1232 **kwargs,
1233 )
1234 try:
1235 # Wrap with SMB_SOCKET
1236 self.smbsock = SMB_SOCKET(self.sock, timeout=self.timeout)
1237 # Wait for either the atmt to fail, or the smb_sock_ready to timeout
1238 _t = time.time()
1239 while True:
1240 if self.sock.atmt.smb_sock_ready.is_set():
1241 # yay
1242 break
1243 if not self.sock.atmt.isrunning():
1244 status = self.sock.atmt.get("Status")
1245 raise Scapy_Exception(
1246 "%s with status %s"
1247 % (
1248 self.sock.atmt.state.state,
1249 STATUS_ERREF.get(status, hex(status)),
1250 )
1251 )
1252 if time.time() - _t > timeout:
1253 self.sock.close()
1254 raise TimeoutError("The SMB handshake timed out.")
1255 time.sleep(0.1)
1256 except Exception:
1257 # Something bad happened, end the socket/automaton
1258 self.sock.close()
1259 raise
1260
1261 # For some usages, we will also need the RPC wrapper
1262 from scapy.layers.msrpce.rpcclient import DCERPC_Client
1263
1264 self.rpcclient = DCERPC_Client.from_smblink(self.sock, ndr64=False, verb=False)
1265 # We have a valid smb connection !
1266 print(
1267 "%s authentication successful using %s%s !"
1268 % (
1269 SMB_DIALECTS.get(
1270 self.smbsock.session.Dialect,
1271 "SMB %s" % self.smbsock.session.Dialect,
1272 ),
1273 repr(self.smbsock.session.sspcontext),
1274 " as GUEST" if self.smbsock.session.IsGuest else "",
1275 )
1276 )
1277 # Now define some variables for our CLI
1278 self.pwd = pathlib.PureWindowsPath("/")
1279 self.localpwd = pathlib.Path(".").resolve()
1280 self.current_tree = None
1281 self.ls_cache = {} # cache the listing of the current directory
1282 self.sh_cache = [] # cache the shares
1283 # Start CLI
1284 if cli:
1285 self.loop(debug=debug)
1286
1287 def ps1(self):
1288 return r"smb: \%s> " % self.normalize_path(self.pwd)
1289
1290 def close(self):
1291 print("Connection closed")
1292 self.smbsock.close()
1293
1294 def _require_share(self, silent=False):
1295 if self.current_tree is None:
1296 if not silent:
1297 print("No share selected ! Try 'shares' then 'use'.")
1298 return True
1299
1300 def collapse_path(self, path):
1301 # the amount of pathlib.wtf you need to do to resolve .. on all platforms
1302 # is ridiculous
1303 return pathlib.PureWindowsPath(os.path.normpath(path.as_posix()))
1304
1305 def normalize_path(self, path):
1306 """
1307 Normalize path for CIFS usage
1308 """
1309 return str(self.collapse_path(path)).lstrip("\\")
1310
1311 @CLIUtil.addcommand()
1312 def shares(self):
1313 """
1314 List the shares available
1315 """
1316 # Poll cache
1317 if self.sh_cache:
1318 return self.sh_cache
1319 # One of the 'hardest' considering it's an RPC
1320 self.rpcclient.open_smbpipe("srvsvc")
1321 self.rpcclient.bind(find_dcerpc_interface("srvsvc"))
1322 req = NetrShareEnum_Request(
1323 InfoStruct=LPSHARE_ENUM_STRUCT(
1324 Level=1,
1325 ShareInfo=NDRUnion(
1326 tag=1,
1327 value=SHARE_INFO_1_CONTAINER(Buffer=None),
1328 ),
1329 ),
1330 PreferedMaximumLength=0xFFFFFFFF,
1331 )
1332 resp = self.rpcclient.sr1_req(req, timeout=self.timeout)
1333 self.rpcclient.close_smbpipe()
1334 if not isinstance(resp, NetrShareEnum_Response):
1335 raise ValueError("NetrShareEnum_Request failed !")
1336 results = []
1337 for share in resp.valueof("InfoStruct.ShareInfo.Buffer"):
1338 shi1_type = share.valueof("shi1_type") & 0x0FFFFFFF
1339 results.append(
1340 (
1341 share.valueof("shi1_netname").decode(),
1342 SRVSVC_SHARE_TYPES.get(shi1_type, shi1_type),
1343 share.valueof("shi1_remark").decode(),
1344 )
1345 )
1346 self.sh_cache = results # cache
1347 return results
1348
1349 @CLIUtil.addoutput(shares)
1350 def shares_output(self, results):
1351 """
1352 Print the output of 'shares'
1353 """
1354 print(pretty_list(results, [("ShareName", "ShareType", "Comment")]))
1355
1356 @CLIUtil.addcommand()
1357 def use(self, share):
1358 """
1359 Open a share
1360 """
1361 self.current_tree = self.smbsock.tree_connect(share)
1362 self.pwd = pathlib.PureWindowsPath("/")
1363 self.ls_cache.clear()
1364
1365 @CLIUtil.addcomplete(use)
1366 def use_complete(self, share):
1367 """
1368 Auto-complete 'use'
1369 """
1370 return [
1371 x[0] for x in self.shares() if x[0].startswith(share) and x[0] != "IPC$"
1372 ]
1373
1374 def _parsepath(self, arg, remote=True):
1375 """
1376 Parse a path. Returns the parent folder and file name
1377 """
1378 # Find parent directory if it exists
1379 elt = (pathlib.PureWindowsPath if remote else pathlib.Path)(arg)
1380 eltpar = (pathlib.PureWindowsPath if remote else pathlib.Path)(".")
1381 eltname = elt.name
1382 if arg.endswith("/") or arg.endswith("\\"):
1383 eltpar = elt
1384 eltname = ""
1385 elif elt.parent and elt.parent.name or elt.is_absolute():
1386 eltpar = elt.parent
1387 return eltpar, eltname
1388
1389 def _fs_complete(self, arg, cond=None):
1390 """
1391 Return a listing of the remote files for completion purposes
1392 """
1393 if cond is None:
1394 cond = lambda _: True
1395 eltpar, eltname = self._parsepath(arg)
1396 # ls in that directory
1397 try:
1398 files = self.ls(parent=eltpar)
1399 except ValueError:
1400 return []
1401 return [
1402 str(eltpar / x[0])
1403 for x in files
1404 if (
1405 x[0].lower().startswith(eltname.lower())
1406 and x[0] not in [".", ".."]
1407 and cond(x[1])
1408 )
1409 ]
1410
1411 def _dir_complete(self, arg):
1412 """
1413 Return a directories of remote files for completion purposes
1414 """
1415 results = self._fs_complete(
1416 arg,
1417 cond=lambda x: x.FILE_ATTRIBUTE_DIRECTORY,
1418 )
1419 if len(results) == 1 and results[0].startswith(arg):
1420 # skip through folders
1421 return [results[0] + "\\"]
1422 return results
1423
1424 @CLIUtil.addcommand(spaces=True)
1425 def ls(self, parent=None):
1426 """
1427 List the files in the remote directory
1428 -t: sort by timestamp
1429 -S: sort by size
1430 -r: reverse while sorting
1431 """
1432 if self._require_share():
1433 return
1434 # Get pwd of the ls
1435 pwd = self.pwd
1436 if parent is not None:
1437 pwd /= parent
1438 pwd = self.normalize_path(pwd)
1439 # Poll the cache
1440 if self.ls_cache and pwd in self.ls_cache:
1441 return self.ls_cache[pwd]
1442 self.smbsock.set_TID(self.current_tree)
1443 # Open folder
1444 fileId = self.smbsock.create_request(
1445 pwd,
1446 type="folder",
1447 extra_create_options=self.extra_create_options,
1448 )
1449 # Query the folder
1450 files = self.smbsock.query_directory(fileId)
1451 # Close the folder
1452 self.smbsock.close_request(fileId)
1453 self.ls_cache[pwd] = files # Store cache
1454 return files
1455
1456 @CLIUtil.addoutput(ls)
1457 def ls_output(self, results, *, t=False, S=False, r=False):
1458 """
1459 Print the output of 'ls'
1460 """
1461 fld = UTCTimeField(
1462 "", None, fmt="<Q", epoch=[1601, 1, 1, 0, 0, 0], custom_scaling=1e7
1463 )
1464 if t:
1465 # Sort by time
1466 results.sort(key=lambda x: -x[3])
1467 if S:
1468 # Sort by size
1469 results.sort(key=lambda x: -x[2])
1470 if r:
1471 # Reverse sort
1472 results = results[::-1]
1473 results = [
1474 (
1475 x[0],
1476 "+".join(y.lstrip("FILE_ATTRIBUTE_") for y in str(x[1]).split("+")),
1477 human_size(x[2]),
1478 fld.i2repr(None, x[3]),
1479 )
1480 for x in results
1481 ]
1482 print(
1483 pretty_list(
1484 results,
1485 [("FileName", "FileAttributes", "EndOfFile", "LastWriteTime")],
1486 sortBy=None,
1487 )
1488 )
1489
1490 @CLIUtil.addcomplete(ls)
1491 def ls_complete(self, folder):
1492 """
1493 Auto-complete ls
1494 """
1495 if self._require_share(silent=True):
1496 return []
1497 return self._dir_complete(folder)
1498
1499 @CLIUtil.addcommand(spaces=True)
1500 def cd(self, folder):
1501 """
1502 Change the remote current directory
1503 """
1504 if self._require_share():
1505 return
1506 if not folder:
1507 # show mode
1508 return str(self.pwd)
1509 self.pwd /= folder
1510 self.pwd = self.collapse_path(self.pwd)
1511 self.ls_cache.clear()
1512
1513 @CLIUtil.addcomplete(cd)
1514 def cd_complete(self, folder):
1515 """
1516 Auto-complete cd
1517 """
1518 if self._require_share(silent=True):
1519 return []
1520 return self._dir_complete(folder)
1521
1522 def _lfs_complete(self, arg, cond):
1523 """
1524 Return a listing of local files for completion purposes
1525 """
1526 eltpar, eltname = self._parsepath(arg, remote=False)
1527 eltpar = self.localpwd / eltpar
1528 return [
1529 # trickery so that ../<TAB> works
1530 str(eltpar / x.name)
1531 for x in eltpar.resolve().glob("*")
1532 if (x.name.lower().startswith(eltname.lower()) and cond(x))
1533 ]
1534
1535 @CLIUtil.addoutput(cd)
1536 def cd_output(self, result):
1537 """
1538 Print the output of 'cd'
1539 """
1540 if result:
1541 print(result)
1542
1543 @CLIUtil.addcommand()
1544 def lls(self):
1545 """
1546 List the files in the local directory
1547 """
1548 return list(self.localpwd.glob("*"))
1549
1550 @CLIUtil.addoutput(lls)
1551 def lls_output(self, results):
1552 """
1553 Print the output of 'lls'
1554 """
1555 results = [
1556 (
1557 x.name,
1558 human_size(stat.st_size),
1559 time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)),
1560 )
1561 for x, stat in ((x, x.stat()) for x in results)
1562 ]
1563 print(
1564 pretty_list(results, [("FileName", "File Size", "Last Modification Time")])
1565 )
1566
1567 @CLIUtil.addcommand(spaces=True)
1568 def lcd(self, folder):
1569 """
1570 Change the local current directory
1571 """
1572 if not folder:
1573 # show mode
1574 return str(self.localpwd)
1575 self.localpwd /= folder
1576 self.localpwd = self.localpwd.resolve()
1577
1578 @CLIUtil.addcomplete(lcd)
1579 def lcd_complete(self, folder):
1580 """
1581 Auto-complete lcd
1582 """
1583 return self._lfs_complete(folder, lambda x: x.is_dir())
1584
1585 @CLIUtil.addoutput(lcd)
1586 def lcd_output(self, result):
1587 """
1588 Print the output of 'lcd'
1589 """
1590 if result:
1591 print(result)
1592
1593 def _get_file(self, file, fd):
1594 """
1595 Gets the file bytes from a remote host
1596 """
1597 # Get pwd of the ls
1598 fpath = self.pwd / file
1599 self.smbsock.set_TID(self.current_tree)
1600 # Open file
1601 fileId = self.smbsock.create_request(
1602 self.normalize_path(fpath),
1603 type="file",
1604 extra_create_options=[
1605 "FILE_SEQUENTIAL_ONLY",
1606 ]
1607 + self.extra_create_options,
1608 )
1609 # Get the file size
1610 info = FileAllInformation(
1611 self.smbsock.query_info(
1612 FileId=fileId,
1613 InfoType="SMB2_0_INFO_FILE",
1614 FileInfoClass="FileAllInformation",
1615 )
1616 )
1617 length = info.StandardInformation.EndOfFile
1618 offset = 0
1619 # Read the file
1620 while length:
1621 lengthRead = min(self.smbsock.session.MaxReadSize, length)
1622 fd.write(
1623 self.smbsock.read_request(fileId, Length=lengthRead, Offset=offset)
1624 )
1625 offset += lengthRead
1626 length -= lengthRead
1627 # Close the file
1628 self.smbsock.close_request(fileId)
1629 return offset
1630
1631 def _send_file(self, fname, fd):
1632 """
1633 Send the file bytes to a remote host
1634 """
1635 # Get destination file
1636 fpath = self.pwd / fname
1637 self.smbsock.set_TID(self.current_tree)
1638 # Open file
1639 fileId = self.smbsock.create_request(
1640 self.normalize_path(fpath),
1641 type="file",
1642 mode="w",
1643 extra_create_options=self.extra_create_options,
1644 )
1645 # Send the file
1646 offset = 0
1647 while True:
1648 data = fd.read(self.smbsock.session.MaxWriteSize)
1649 if not data:
1650 # end of file
1651 break
1652 offset += self.smbsock.write_request(
1653 Data=data,
1654 FileId=fileId,
1655 Offset=offset,
1656 )
1657 # Close the file
1658 self.smbsock.close_request(fileId)
1659 return offset
1660
1661 def _getr(self, directory, _root, _verb=True):
1662 """
1663 Internal recursive function to get a directory
1664
1665 :param directory: the remote directory to get
1666 :param _root: locally, the directory to store any found files
1667 """
1668 size = 0
1669 if not _root.exists():
1670 _root.mkdir()
1671 # ls the directory
1672 for x in self.ls(parent=directory):
1673 if x[0] in [".", ".."]:
1674 # Discard . and ..
1675 continue
1676 remote = directory / x[0]
1677 local = _root / x[0]
1678 try:
1679 if x[1].FILE_ATTRIBUTE_DIRECTORY:
1680 # Sub-directory
1681 size += self._getr(remote, local)
1682 else:
1683 # Sub-file
1684 size += self.get(remote, local)[1]
1685 if _verb:
1686 print(remote)
1687 except ValueError as ex:
1688 if _verb:
1689 print(conf.color_theme.red(remote), "->", str(ex))
1690 return size
1691
1692 @CLIUtil.addcommand(spaces=True, globsupport=True)
1693 def get(self, file, _dest=None, _verb=True, *, r=False):
1694 """
1695 Retrieve a file
1696 -r: recursively download a directory
1697 """
1698 if self._require_share():
1699 return
1700 if r:
1701 dirpar, dirname = self._parsepath(file)
1702 return file, self._getr(
1703 dirpar / dirname, # Remotely
1704 _root=self.localpwd / dirname, # Locally
1705 _verb=_verb,
1706 )
1707 else:
1708 fname = pathlib.PureWindowsPath(file).name
1709 # Write the buffer
1710 if _dest is None:
1711 _dest = self.localpwd / fname
1712 with _dest.open("wb") as fd:
1713 size = self._get_file(file, fd)
1714 return fname, size
1715
1716 @CLIUtil.addoutput(get)
1717 def get_output(self, info):
1718 """
1719 Print the output of 'get'
1720 """
1721 print("Retrieved '%s' of size %s" % (info[0], human_size(info[1])))
1722
1723 @CLIUtil.addcomplete(get)
1724 def get_complete(self, file):
1725 """
1726 Auto-complete get
1727 """
1728 if self._require_share(silent=True):
1729 return []
1730 return self._fs_complete(file)
1731
1732 @CLIUtil.addcommand(spaces=True, globsupport=True)
1733 def cat(self, file):
1734 """
1735 Print a file
1736 """
1737 if self._require_share():
1738 return
1739 # Write the buffer to buffer
1740 buf = io.BytesIO()
1741 self._get_file(file, buf)
1742 return buf.getvalue()
1743
1744 @CLIUtil.addoutput(cat)
1745 def cat_output(self, result):
1746 """
1747 Print the output of 'cat'
1748 """
1749 print(result.decode(errors="backslashreplace"))
1750
1751 @CLIUtil.addcomplete(cat)
1752 def cat_complete(self, file):
1753 """
1754 Auto-complete cat
1755 """
1756 if self._require_share(silent=True):
1757 return []
1758 return self._fs_complete(file)
1759
1760 @CLIUtil.addcommand(spaces=True)
1761 def put(self, file):
1762 """
1763 Upload a file
1764 """
1765 if self._require_share():
1766 return
1767 local_file = self.localpwd / file
1768 if local_file.is_dir():
1769 # Directory
1770 raise ValueError("put on dir not impl")
1771 else:
1772 fname = pathlib.Path(file).name
1773 with local_file.open("rb") as fd:
1774 size = self._send_file(fname, fd)
1775 self.ls_cache.clear()
1776 return fname, size
1777
1778 @CLIUtil.addcomplete(put)
1779 def put_complete(self, folder):
1780 """
1781 Auto-complete put
1782 """
1783 return self._lfs_complete(folder, lambda x: not x.is_dir())
1784
1785 @CLIUtil.addcommand(spaces=True)
1786 def rm(self, file):
1787 """
1788 Delete a file
1789 """
1790 if self._require_share():
1791 return
1792 # Get pwd of the ls
1793 fpath = self.pwd / file
1794 self.smbsock.set_TID(self.current_tree)
1795 # Open file
1796 fileId = self.smbsock.create_request(
1797 self.normalize_path(fpath),
1798 type="file",
1799 mode="d",
1800 extra_create_options=self.extra_create_options,
1801 )
1802 # Close the file
1803 self.smbsock.close_request(fileId)
1804 self.ls_cache.clear()
1805 return fpath.name
1806
1807 @CLIUtil.addcomplete(rm)
1808 def rm_complete(self, file):
1809 """
1810 Auto-complete rm
1811 """
1812 if self._require_share(silent=True):
1813 return []
1814 return self._fs_complete(file)
1815
1816 @CLIUtil.addcommand()
1817 def backup(self):
1818 """
1819 Turn on or off backup intent
1820 """
1821 if "FILE_OPEN_FOR_BACKUP_INTENT" in self.extra_create_options:
1822 print("Backup Intent: Off")
1823 self.extra_create_options.remove("FILE_OPEN_FOR_BACKUP_INTENT")
1824 else:
1825 print("Backup Intent: On")
1826 self.extra_create_options.append("FILE_OPEN_FOR_BACKUP_INTENT")
1827
1828 @CLIUtil.addcommand(spaces=True)
1829 def watch(self, folder):
1830 """
1831 Watch file changes in folder (recursively)
1832 """
1833 if self._require_share():
1834 return
1835 # Get pwd of the ls
1836 fpath = self.pwd / folder
1837 self.smbsock.set_TID(self.current_tree)
1838 # Open file
1839 fileId = self.smbsock.create_request(
1840 self.normalize_path(fpath),
1841 type="folder",
1842 extra_create_options=self.extra_create_options,
1843 )
1844 print("Watching '%s'" % fpath)
1845 # Watch for changes
1846 try:
1847 while True:
1848 changes = self.smbsock.changenotify(fileId)
1849 for chg in changes:
1850 print(chg.sprintf("%.time%: %Action% %FileName%"))
1851 except KeyboardInterrupt:
1852 pass
1853 # Close the file
1854 self.smbsock.close_request(fileId)
1855 print("Cancelled.")
1856
1857 @CLIUtil.addcommand(spaces=True)
1858 def getsd(self, file):
1859 """
1860 Get the Security Descriptor
1861 """
1862 if self._require_share():
1863 return
1864 fpath = self.pwd / file
1865 self.smbsock.set_TID(self.current_tree)
1866 # Open file
1867 fileId = self.smbsock.create_request(
1868 self.normalize_path(fpath),
1869 type="",
1870 mode="",
1871 extra_desired_access=["READ_CONTROL", "ACCESS_SYSTEM_SECURITY"],
1872 )
1873 # Get the file size
1874 info = self.smbsock.query_info(
1875 FileId=fileId,
1876 InfoType="SMB2_0_INFO_SECURITY",
1877 FileInfoClass=0,
1878 AdditionalInformation=(
1879 0x00000001
1880 | 0x00000002
1881 | 0x00000004
1882 | 0x00000008
1883 | 0x00000010
1884 | 0x00000020
1885 | 0x00000040
1886 | 0x00010000
1887 ),
1888 )
1889 self.smbsock.close_request(fileId)
1890 return info
1891
1892 @CLIUtil.addcomplete(getsd)
1893 def getsd_complete(self, file):
1894 """
1895 Auto-complete getsd
1896 """
1897 if self._require_share(silent=True):
1898 return []
1899 return self._fs_complete(file)
1900
1901 @CLIUtil.addoutput(getsd)
1902 def getsd_output(self, results):
1903 """
1904 Print the output of 'getsd'
1905 """
1906 sd = SECURITY_DESCRIPTOR(results)
1907 print("Owner:", sd.OwnerSid.summary())
1908 print("Group:", sd.GroupSid.summary())
1909 if getattr(sd, "DACL", None):
1910 print("DACL:")
1911 for ace in sd.DACL.Aces:
1912 print(" - ", ace.toSDDL())
1913 if getattr(sd, "SACL", None):
1914 print("SACL:")
1915 for ace in sd.SACL.Aces:
1916 print(" - ", ace.toSDDL())
1917
1918
1919if __name__ == "__main__":
1920 from scapy.utils import AutoArgparse
1921
1922 AutoArgparse(smbclient)