-
Notifications
You must be signed in to change notification settings - Fork 95
/
base.py
3115 lines (2719 loc) · 166 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging, binascii, time, hmac
from datetime import datetime
from tqdm import tqdm
from .smb_constants import *
from .smb2_constants import *
from .smb_structs import *
from .smb2_structs import *
from .security_descriptors import SecurityDescriptor
from nmb.base import NMBSession
from .utils import convertFILETIMEtoEpoch
from . import ntlm, securityblob
from .strategy import DataFaultToleranceStrategy
try:
import hashlib
sha256 = hashlib.sha256
except ImportError:
from .utils import sha256
class NotReadyError(Exception):
"""Raised when SMB connection is not ready (i.e. not authenticated or authentication failed)"""
pass
class NotConnectedError(Exception):
"""Raised when underlying SMB connection has been disconnected or not connected yet"""
pass
class SMBTimeout(Exception):
"""Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete."""
pass
class SMB(NMBSession):
"""
This class represents a "connection" to the remote SMB/CIFS server.
It is not meant to be used directly in an application as it does not have any network transport implementations.
For application use, please refer to
- L{SMBProtocol.SMBProtocolFactory<smb.SMBProtocol>} if you are using Twisted framework
In [MS-CIFS], this class will contain attributes of Client, Client.Connection and Client.Session abstract data models.
References:
===========
- [MS-CIFS]: 3.2.1
"""
log = logging.getLogger('SMB.SMB')
SIGN_NEVER = 0
SIGN_WHEN_SUPPORTED = 1
SIGN_WHEN_REQUIRED = 2
def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False):
NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp)
self.username = username
self._password = password
self.domain = domain
self.sign_options = sign_options
self.is_direct_tcp = is_direct_tcp
self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1
self.smb_message = SMBMessage()
self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True
self.async_requests = { } #: AsyncID mapped to _PendingRequest instance
self.pending_requests = { } #: MID mapped to _PendingRequest instance
self.connected_trees = { } #: Share name mapped to TID
self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages
self.has_negotiated = False
self.has_authenticated = False
self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2
self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2
self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2
self.mid = 0
self.uid = 0
self.next_signing_id = 2 #: Similar to ClientNextSendSequenceNumber as described in [MS-CIFS] 3.2.1.2
# SMB1 and SMB2 attributes
# Note that the interpretations of the values may differ between SMB1 and SMB2 protocols
self.capabilities = 0
self.security_mode = 0 #: Initialized from the SecurityMode field of the SMB_COM_NEGOTIATE message
# SMB1 attributes
# Most of the following attributes will be initialized upon receipt of SMB_COM_NEGOTIATE message from server (via self._updateServerInfo_SMB1 method)
self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1
self.max_raw_size = 0
self.max_buffer_size = 0 #: Similar to MaxBufferSize as described in [MS-CIFS] 3.2.1.1
self.max_mpx_count = 0 #: Similar to MaxMpxCount as described in [MS-CIFS] 3.2.1.1
# SMB2 attributes
self.max_read_size = 0 #: Similar to MaxReadSize as described in [MS-SMB2] 2.2.4
self.max_write_size = 0 #: Similar to MaxWriteSize as described in [MS-SMB2] 2.2.4
self.max_transact_size = 0 #: Similar to MaxTransactSize as described in [MS-SMB2] 2.2.4
self.session_id = 0 #: Similar to SessionID as described in [MS-SMB2] 2.2.4. This will be set in _updateState_SMB2 method
# tqdm attributes for tracking progress
self.pbar = None #: If not None, it means there is an active tqdm progress bar being shown
self._setupSMB1Methods()
self.log.info('Authentication with remote machine "%s" for user "%s" will be using NTLM %s authentication (%s extended security)',
self.remote_name, self.username,
(self.use_ntlm_v2 and 'v2') or 'v1',
(SUPPORT_EXTENDED_SECURITY and 'with') or 'without')
@property
def password(self):
if callable(self._password):
return self._password()
return self._password
#
# NMBSession Methods
#
def onNMBSessionOK(self):
self._sendSMBMessage(SMBMessage(ComNegotiateRequest()))
def onNMBSessionFailed(self):
pass
def onNMBSessionMessage(self, flags, data):
while True:
try:
i = self.smb_message.decode(data)
except SMB2ProtocolHeaderError:
self.log.info('Now switching over to SMB2 protocol communication')
self.is_using_smb2 = True
self.mid = 0 # Must reset messageID counter, or else remote SMB2 server will disconnect
self._setupSMB2Methods()
self.smb_message = self._klassSMBMessage()
i = self.smb_message.decode(data)
next_message_offset = 0
if self.is_using_smb2:
next_message_offset = self.smb_message.next_command_offset
if i > 0:
if not self.is_using_smb2:
self.log.debug('Received SMB message "%s" (command:0x%2X flags:0x%02X flags2:0x%04X TID:%d UID:%d)',
SMB_COMMAND_NAMES.get(self.smb_message.command, '<unknown>'),
self.smb_message.command, self.smb_message.flags, self.smb_message.flags2, self.smb_message.tid, self.smb_message.uid)
else:
self.log.debug('Received SMB2 message "%s" (command:0x%04X flags:0x%04x)',
SMB2_COMMAND_NAMES.get(self.smb_message.command, '<unknown>'),
self.smb_message.command, self.smb_message.flags)
if self._updateState(self.smb_message):
# We need to create a new instance instead of calling reset() because the instance could be captured in the message history.
self.smb_message = self._klassSMBMessage()
if next_message_offset > 0:
data = data[next_message_offset:]
else:
break
#
# Public Methods for Overriding in Subclasses
#
def onAuthOK(self):
pass
def onAuthFailed(self):
pass
#
# Protected Methods
#
def _setupSMB1Methods(self):
self._klassSMBMessage = SMBMessage
self._updateState = self._updateState_SMB1
self._updateServerInfo = self._updateServerInfo_SMB1
self._handleNegotiateResponse = self._handleNegotiateResponse_SMB1
self._sendSMBMessage = self._sendSMBMessage_SMB1
self._handleSessionChallenge = self._handleSessionChallenge_SMB1
self._listShares = self._listShares_SMB1
self._listPath = self._listPath_SMB1
self._listSnapshots = self._listSnapshots_SMB1
self._getSecurity = self._getSecurity_SMB1
self._getAttributes = self._getAttributes_SMB1
self._retrieveFile = self._retrieveFile_SMB1
self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1
self._storeFile = self._storeFile_SMB1
self._storeFileFromOffset = self._storeFileFromOffset_SMB1
self._deleteFiles = self._deleteFiles_SMB1
self._resetFileAttributes = self._resetFileAttributes_SMB1
self._createDirectory = self._createDirectory_SMB1
self._deleteDirectory = self._deleteDirectory_SMB1
self._rename = self._rename_SMB1
self._echo = self._echo_SMB1
def _setupSMB2Methods(self):
self._klassSMBMessage = SMB2Message
self._updateState = self._updateState_SMB2
self._updateServerInfo = self._updateServerInfo_SMB2
self._handleNegotiateResponse = self._handleNegotiateResponse_SMB2
self._sendSMBMessage = self._sendSMBMessage_SMB2
self._handleSessionChallenge = self._handleSessionChallenge_SMB2
self._listShares = self._listShares_SMB2
self._listPath = self._listPath_SMB2
self._listSnapshots = self._listSnapshots_SMB2
self._getSecurity = self._getSecurity_SMB2
self._getAttributes = self._getAttributes_SMB2
self._retrieveFile = self._retrieveFile_SMB2
self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2
self._storeFile = self._storeFile_SMB2
self._storeFileFromOffset = self._storeFileFromOffset_SMB2
self._deleteFiles = self._deleteFiles_SMB2
self._resetFileAttributes = self._resetFileAttributes_SMB2
self._createDirectory = self._createDirectory_SMB2
self._deleteDirectory = self._deleteDirectory_SMB2
self._rename = self._rename_SMB2
self._echo = self._echo_SMB2
def _getNextRPCCallID(self):
self.next_rpc_call_id += 1
return self.next_rpc_call_id
#
# SMB2 Methods Family
#
def _sendSMBMessage_SMB2(self, smb_message):
if smb_message.mid == 0:
smb_message.mid = self._getNextMID_SMB2()
if smb_message.command != SMB2_COM_NEGOTIATE:
smb_message.session_id = self.session_id
if self.is_signing_active:
smb_message.flags |= SMB2_FLAGS_SIGNED
raw_data = smb_message.encode()
smb_message.signature = hmac.new(self.signing_session_key, raw_data, sha256).digest()[:16]
smb_message.raw_data = smb_message.encode()
self.log.debug('MID is %d. Signature is %s. Total raw message is %d bytes', smb_message.mid, binascii.hexlify(smb_message.signature), len(smb_message.raw_data))
else:
smb_message.raw_data = smb_message.encode()
self.sendNMBMessage(smb_message.raw_data)
def _getNextMID_SMB2(self):
self.mid += 1
return self.mid
def _updateState_SMB2(self, message):
if message.isReply:
if message.command == SMB2_COM_NEGOTIATE:
if message.status == 0:
self.has_negotiated = True
self.log.info('SMB2 dialect negotiation successful')
self._updateServerInfo(message.payload)
self._handleNegotiateResponse(message)
else:
raise ProtocolError('Unknown status value (0x%08X) in SMB2_COM_NEGOTIATE' % message.status,
message.raw_data, message)
elif message.command == SMB2_COM_SESSION_SETUP:
if message.status == 0:
self.session_id = message.session_id
try:
result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob)
if result == securityblob.RESULT_ACCEPT_COMPLETED:
self.has_authenticated = True
self.log.info('Authentication (on SMB2) successful!')
# [MS-SMB2]: 3.2.5.3.1
# If the security subsystem indicates that the session was established by an anonymous user,
# Session.SigningRequired MUST be set to FALSE.
# If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the
# SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP
# failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags
# field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired
# MUST be set to FALSE.
if message.payload.isGuestSession or message.payload.isAnonymousSession:
self.is_signing_active = False
self.log.info('Signing disabled because session is guest/anonymous')
self.onAuthOK()
else:
raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message)
except securityblob.BadSecurityBlobError as ex:
raise ProtocolError(str(ex), message.raw_data, message)
elif message.status == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED
self.session_id = message.session_id
try:
result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob)
if result == securityblob.RESULT_ACCEPT_INCOMPLETE:
self._handleSessionChallenge(message, ntlm_token)
except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex:
raise ProtocolError(str(ex), message.raw_data, message)
elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE
or message.status == 0xc0000064 # STATUS_NO_SUCH_USER
or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Please check username and password.')
self.onAuthFailed()
elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED
or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Account or password has expired.')
self.onAuthFailed()
elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.')
self.onAuthFailed()
elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Account has been disabled.')
self.onAuthFailed()
elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS
or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED
or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Not allowed.')
self.onAuthFailed()
elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Domain not trusted.')
self.onAuthFailed()
elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE
self.has_authenticated = False
self.log.info('Authentication (on SMB2) failed. Workstation not trusted.')
self.onAuthFailed()
else:
raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status,
message.raw_data, message)
if message.isAsync:
if message.status == 0x00000103: # STATUS_PENDING
req = self.pending_requests.pop(message.mid, None)
if req:
self.async_requests[message.async_id] = req
else: # All other status including SUCCESS
req = self.async_requests.pop(message.async_id, None)
if req:
req.callback(message, **req.kwargs)
return True
else:
req = self.pending_requests.pop(message.mid, None)
if req:
req.callback(message, **req.kwargs)
return True
def _updateServerInfo_SMB2(self, payload):
self.capabilities = payload.capabilities
self.security_mode = payload.security_mode
self.max_transact_size = payload.max_transact_size
self.max_read_size = payload.max_read_size
self.max_write_size = payload.max_write_size
self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication
def _handleNegotiateResponse_SMB2(self, message):
ntlm_data = ntlm.generateNegotiateMessage()
blob = securityblob.generateNegotiateSecurityBlob(ntlm_data)
self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob)))
def _handleSessionChallenge_SMB2(self, message, ntlm_token):
server_challenge, server_flags, server_info = ntlm.decodeChallengeMessage(ntlm_token)
self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge))
if self.use_ntlm_v2:
self.log.info('Performing NTLMv2 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge))
nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password,
self.username,
server_challenge,
server_info,
self.domain)
else:
self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge))
nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True)
ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags,
nt_challenge_response,
lm_challenge_response,
session_key,
self.username,
self.domain,
self.my_name)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response))
self.log.debug('LM challenge response is "%s" (%d bytes)', binascii.hexlify(lm_challenge_response), len(lm_challenge_response))
blob = securityblob.generateAuthSecurityBlob(ntlm_data)
self._sendSMBMessage(SMB2Message(SMB2SessionSetupRequest(blob)))
if self.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED:
self.log.info('Server requires all SMB messages to be signed')
self.is_signing_active = (self.sign_options != SMB.SIGN_NEVER)
elif self.security_mode & SMB2_NEGOTIATE_SIGNING_ENABLED:
self.log.info('Server supports SMB signing')
self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED)
else:
self.is_signing_active = False
if self.is_signing_active:
self.log.info("SMB signing activated. All SMB messages will be signed.")
self.signing_session_key = session_signing_key
if self.log.isEnabledFor(logging.DEBUG):
self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key))
if self.capabilities & CAP_EXTENDED_SECURITY:
self.signing_challenge_response = None
else:
self.signing_challenge_response = blob
else:
self.log.info("SMB signing deactivated. SMB messages will NOT be signed.")
def _listShares_SMB2(self, callback, errback, timeout = 30):
if not self.has_authenticated:
raise NotReadyError('SMB connection not authenticated')
expiry_time = time.time() + timeout
path = 'IPC$'
messages_history = [ ]
def connectSrvSvc(tid):
m = SMB2Message(SMB2CreateRequest('srvsvc',
file_attributes = 0,
access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE,
share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
oplock = SMB2_OPLOCK_LEVEL_NONE,
impersonation = SEC_IMPERSONATE,
create_options = FILE_NON_DIRECTORY_FILE | FILE_OPEN_NO_RECALL,
create_disp = FILE_OPEN))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid)
messages_history.append(m)
def connectSrvSvcCB(create_message, **kwargs):
messages_history.append(create_message)
if create_message.status == 0:
call_id = self._getNextRPCCallID()
# The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706]
# If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream
data_bytes = \
binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(b' ', b'')) + \
struct.pack('<I', call_id) + \
binascii.unhexlify(b"""
b8 10 b8 10 00 00 00 00 02 00 00 00 00 00 01 00
c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88
03 00 00 00 04 5d 88 8a eb 1c c9 11 9f e8 08 00
2b 10 48 60 02 00 00 00 01 00 01 00 c8 4f 32 4b
70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00
2c 1c b7 6c 12 98 40 45 03 00 00 00 00 00 00 00
01 00 00 00
""".replace(b' ', b'').replace(b'\n', b''))
m = SMB2Message(SMB2WriteRequest(create_message.payload.fid, data_bytes, 0))
m.tid = kwargs['tid']
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid)
messages_history.append(m)
else:
errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history))
def rpcBindCB(trans_message, **kwargs):
messages_history.append(trans_message)
if trans_message.status == 0:
m = SMB2Message(SMB2ReadRequest(kwargs['fid'], read_len = 1024, read_offset = 0))
m.tid = kwargs['tid']
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, tid = kwargs['tid'], fid = kwargs['fid'])
messages_history.append(m)
else:
closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint')
def rpcReadCB(read_message, **kwargs):
messages_history.append(read_message)
if read_message.status == 0:
call_id = self._getNextRPCCallID()
padding = b''
remote_name = '\\\\' + self.remote_name
server_len = len(remote_name) + 1
server_bytes_len = server_len * 2
if server_len % 2 != 0:
padding = b'\0\0'
server_bytes_len += 2
# The data bytes are the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC.
# If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream
data_bytes = \
binascii.unhexlify(b"""05 00 00 03 10 00 00 00""".replace(b' ', b'')) + \
struct.pack('<HHI', 72+server_bytes_len, 0, call_id) + \
binascii.unhexlify(b"""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(b' ', b'')) + \
struct.pack('<III', server_len, 0, server_len) + \
(remote_name + '\0').encode('UTF-16LE') + padding + \
binascii.unhexlify(b"""
01 00 00 00 01 00 00 00 04 00 02 00 00 00 00 00
00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00
""".replace(b' ', b'').replace(b'\n', b''))
m = SMB2Message(SMB2IoctlRequest(kwargs['fid'], 0x0011C017, flags = 0x01, max_out_size = 8196, in_data = data_bytes))
m.tid = kwargs['tid']
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, tid = kwargs['tid'], fid = kwargs['fid'])
messages_history.append(m)
else:
closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint')
def listShareResultsCB(result_message, **kwargs):
messages_history.append(result_message)
if result_message.status == 0:
# The payload.data_bytes will contain the results of the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC.
data_bytes = result_message.payload.out_data
if data_bytes[3] & 0x02 == 0:
sendReadRequest(kwargs['tid'], kwargs['fid'], data_bytes)
else:
decodeResults(kwargs['tid'], kwargs['fid'], data_bytes)
else:
closeFid(kwargs['tid'], kwargs['fid'])
errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history))
def decodeResults(tid, fid, data_bytes):
shares_count = struct.unpack('<I', data_bytes[36:40])[0]
results = [ ] # A list of SharedDevice instances
offset = 36 + 12 # You need to study the byte stream to understand the meaning of these constants
for i in range(0, shares_count):
results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None))
offset += 12
for i in range(0, shares_count):
max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12])
offset += 12
results[i].name = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2])
if length % 2 != 0:
offset += (length * 2 + 2)
else:
offset += (length * 2)
max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12])
offset += 12
results[i].comments = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset:offset+length*2-2])
if length % 2 != 0:
offset += (length * 2 + 2)
else:
offset += (length * 2)
closeFid(tid, fid)
callback(results)
def sendReadRequest(tid, fid, data_bytes):
read_count = min(4280, self.max_read_size)
m = SMB2Message(SMB2ReadRequest(fid, 0, read_count))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback,
tid = tid, fid = fid, data_bytes = data_bytes)
def readCB(read_message, **kwargs):
messages_history.append(read_message)
if read_message.status == 0:
data_bytes = read_message.payload.data
if data_bytes[3] & 0x02 == 0:
sendReadRequest(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:])
else:
decodeResults(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:])
else:
closeFid(kwargs['tid'], kwargs['fid'])
errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history))
def closeFid(tid, fid, results = None, error = None):
m = SMB2Message(SMB2CloseRequest(fid))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error)
messages_history.append(m)
def closeCB(close_message, **kwargs):
if kwargs['results'] is not None:
callback(kwargs['results'])
elif kwargs['error'] is not None:
errback(OperationFailure(kwargs['error'], messages_history))
if path not in self.connected_trees:
def connectCB(connect_message, **kwargs):
messages_history.append(connect_message)
if connect_message.status == 0:
self.connected_trees[path] = connect_message.tid
connectSrvSvc(connect_message.tid)
else:
errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history))
m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), path )))
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = path)
messages_history.append(m)
else:
connectSrvSvc(self.connected_trees[path])
def _listPath_SMB2(self, service_name, path, callback, errback, search, pattern, timeout = 30):
if not self.has_authenticated:
raise NotReadyError('SMB connection not authenticated')
expiry_time = time.time() + timeout
path = path.replace('/', '\\')
if path.startswith('\\'):
path = path[1:]
if path.endswith('\\'):
path = path[:-1]
messages_history = [ ]
results = [ ]
def sendCreate(tid):
create_context_data = binascii.unhexlify(b"""
28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00
44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00
00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00
00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00
51 46 69 64 00 00 00 00
""".replace(b' ', b'').replace(b'\n', b''))
m = SMB2Message(SMB2CreateRequest(path,
file_attributes = 0,
access_mask = FILE_READ_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
oplock = SMB2_OPLOCK_LEVEL_NONE,
impersonation = SEC_IMPERSONATE,
create_options = FILE_DIRECTORY_FILE,
create_disp = FILE_OPEN,
create_context_data = create_context_data))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid)
messages_history.append(m)
def createCB(create_message, **kwargs):
messages_history.append(create_message)
if create_message.status == 0:
sendQuery(kwargs['tid'], create_message.payload.fid, b'')
elif create_message.status == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID
errback(OperationFailure('Failed to list %s on %s: Path not found' % ( path, service_name ), messages_history))
else:
errback(OperationFailure('Failed to list %s on %s: Unable to open directory' % ( path, service_name ), messages_history))
def sendQuery(tid, fid, data_buf):
m = SMB2Message(SMB2QueryDirectoryRequest(fid, pattern,
info_class = 0x25, # FileIdBothDirectoryInformation
flags = 0,
output_buf_len = self.max_transact_size))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = tid, fid = fid, data_buf = data_buf)
messages_history.append(m)
def queryCB(query_message, **kwargs):
messages_history.append(query_message)
if query_message.status == 0:
data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data)
sendQuery(kwargs['tid'], kwargs['fid'], data_buf)
elif query_message.status == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE
# If there are no matching files, we just treat as success instead of failing
closeFid(kwargs['tid'], kwargs['fid'], results = results)
elif query_message.status == 0x80000006: # STATUS_NO_MORE_FILES
closeFid(kwargs['tid'], kwargs['fid'], results = results)
else:
closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status)
def decodeQueryStruct(data_bytes):
# FileIdBothDirectoryInformation structure. See [MS-SMB]: 2.2.8.1.3 and [MS-FSCC]: 2.4.17
info_format = '<IIQQQQQQIIIBB24sHQ'
info_size = struct.calcsize(info_format)
data_length = len(data_bytes)
offset = 0
while offset < data_length:
if offset + info_size > data_length:
return data_bytes[offset:]
next_offset, _, \
create_time, last_access_time, last_write_time, last_attr_change_time, \
file_size, alloc_size, file_attributes, filename_length, ea_size, \
short_name_length, _, short_name, _, file_id = struct.unpack(info_format, data_bytes[offset:offset+info_size])
offset2 = offset + info_size
if offset2 + filename_length > data_length:
return data_bytes[offset:]
filename = DataFaultToleranceStrategy.data_bytes_decode(data_bytes[offset2:offset2+filename_length])
short_name = DataFaultToleranceStrategy.data_bytes_decode(short_name[:short_name_length])
accept_result = False
if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc
accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL)
else:
accept_result = (file_attributes & search) > 0
if accept_result:
results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time),
convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time),
file_size, alloc_size, file_attributes, short_name, filename, file_id))
if next_offset:
offset += next_offset
else:
break
return b''
def closeFid(tid, fid, results = None, error = None):
m = SMB2Message(SMB2CloseRequest(fid))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, results = results, error = error)
messages_history.append(m)
def closeCB(close_message, **kwargs):
if kwargs['results'] is not None:
callback(kwargs['results'])
elif kwargs['error'] is not None:
if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE
# Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files
callback([ ])
else:
errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history))
if service_name not in self.connected_trees:
def connectCB(connect_message, **kwargs):
messages_history.append(connect_message)
if connect_message.status == 0:
self.connected_trees[service_name] = connect_message.tid
sendCreate(connect_message.tid)
else:
errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history))
m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name )))
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name)
messages_history.append(m)
else:
sendCreate(self.connected_trees[service_name])
def _getAttributes_SMB2(self, service_name, path, callback, errback, timeout = 30):
if not self.has_authenticated:
raise NotReadyError('SMB connection not authenticated')
expiry_time = time.time() + timeout
path = path.replace('/', '\\')
if path.startswith('\\'):
path = path[1:]
if path.endswith('\\'):
path = path[:-1]
messages_history = [ ]
def sendCreate(tid):
create_context_data = binascii.unhexlify("""
28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00
44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00
00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00
00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00
51 46 69 64 00 00 00 00
""".replace(' ', '').replace('\n', ''))
m = SMB2Message(SMB2CreateRequest(path,
file_attributes = 0,
access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
oplock = SMB2_OPLOCK_LEVEL_NONE,
impersonation = SEC_IMPERSONATE,
create_options = 0,
create_disp = FILE_OPEN,
create_context_data = create_context_data))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid)
messages_history.append(m)
def createCB(create_message, **kwargs):
messages_history.append(create_message)
if create_message.status == 0:
p = create_message.payload
filename = self._extractLastPathComponent(path)
info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time,
p.file_size, p.allocation_size, p.file_attributes,
filename, filename)
closeFid(kwargs['tid'], p.fid, info = info)
else:
errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history))
def closeFid(tid, fid, info = None, error = None):
m = SMB2Message(SMB2CloseRequest(fid))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, info = info, error = error)
messages_history.append(m)
def closeCB(close_message, **kwargs):
if kwargs['info'] is not None:
callback(kwargs['info'])
elif kwargs['error'] is not None:
errback(OperationFailure('Failed to get attributes for %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history))
if service_name not in self.connected_trees:
def connectCB(connect_message, **kwargs):
messages_history.append(connect_message)
if connect_message.status == 0:
self.connected_trees[service_name] = connect_message.tid
sendCreate(connect_message.tid)
else:
errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history))
m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name )))
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name)
messages_history.append(m)
else:
sendCreate(self.connected_trees[service_name])
def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30):
if not self.has_authenticated:
raise NotReadyError('SMB connection not authenticated')
expiry_time = time.time() + timeout
path = path.replace('/', '\\')
if path.startswith('\\'):
path = path[1:]
if path.endswith('\\'):
path = path[:-1]
messages_history = [ ]
results = [ ]
def sendCreate(tid):
m = SMB2Message(SMB2CreateRequest(path,
file_attributes = 0,
access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
oplock = SMB2_OPLOCK_LEVEL_NONE,
impersonation = SEC_IMPERSONATE,
create_options = 0,
create_disp = FILE_OPEN))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid)
messages_history.append(m)
def createCB(create_message, **kwargs):
messages_history.append(create_message)
if create_message.status == 0:
m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid,
flags = 0,
additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
info_type = SMB2_INFO_SECURITY,
file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12
input_buf = '',
output_buf_len = self.max_transact_size))
m.tid = kwargs['tid']
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid)
messages_history.append(m)
else:
errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history))
def queryCB(query_message, **kwargs):
messages_history.append(query_message)
if query_message.status == 0:
security = SecurityDescriptor.from_bytes(query_message.payload.data)
closeFid(kwargs['tid'], kwargs['fid'], result = security)
else:
closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status)
def closeFid(tid, fid, result = None, error = None):
m = SMB2Message(SMB2CloseRequest(fid))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error)
messages_history.append(m)
def closeCB(close_message, **kwargs):
if kwargs['result'] is not None:
callback(kwargs['result'])
elif kwargs['error'] is not None:
errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history))
if service_name not in self.connected_trees:
def connectCB(connect_message, **kwargs):
messages_history.append(connect_message)
if connect_message.status == 0:
self.connected_trees[service_name] = connect_message.tid
sendCreate(connect_message.tid)
else:
errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history))
m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name )))
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name)
messages_history.append(m)
else:
sendCreate(self.connected_trees[service_name])
def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30):
return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout)
def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30, show_progress = False, tqdm_kwargs = { }):
if not self.has_authenticated:
raise NotReadyError('SMB connection not authenticated')
expiry_time = time.time() + timeout
path = path.replace('/', '\\')
if path.startswith('\\'):
path = path[1:]
if path.endswith('\\'):
path = path[:-1]
messages_history = [ ]
results = [ ]
def sendCreate(tid):
create_context_data = binascii.unhexlify(b"""
28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00
44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00
00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00
00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00
51 46 69 64 00 00 00 00
""".replace(b' ', b'').replace(b'\n', b''))
m = SMB2Message(SMB2CreateRequest(path,
file_attributes = 0,
access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE,
share_access = FILE_SHARE_READ | FILE_SHARE_WRITE,
oplock = SMB2_OPLOCK_LEVEL_NONE,
impersonation = SEC_IMPERSONATE,
create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE,
create_disp = FILE_OPEN,
create_context_data = create_context_data))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid)
messages_history.append(m)
def createCB(create_message, **kwargs):
messages_history.append(create_message)
if create_message.status == 0:
m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid,
flags = 0,
additional_info = 0,
info_type = SMB2_INFO_FILE,
file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4
input_buf = b'',
output_buf_len = 4096))
m.tid = kwargs['tid']
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback,
tid = kwargs['tid'],
fid = create_message.payload.fid,
file_attributes = create_message.payload.file_attributes)
messages_history.append(m)
else:
errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history))
def infoCB(info_message, **kwargs):
messages_history.append(info_message)
if info_message.status == 0:
file_len = struct.unpack('<Q', info_message.payload.data[8:16])[0]
if max_length == 0 or starting_offset > file_len:
if self.pbar:
self.pbar.close()
self.pbar = None
closeFid(info_message.tid, kwargs['fid'])
callback(( file_obj, kwargs['file_attributes'], 0 )) # Note that this is a tuple of 3-elements
else:
remaining_len = max_length
if remaining_len < 0:
remaining_len = file_len
if starting_offset + remaining_len > file_len:
remaining_len = file_len - starting_offset
if show_progress:
self.pbar = tqdm(
total = remaining_len,
unit="B",
unit_scale=True,
unit_divisor=1024,
desc = f"Downloading {path}",
**tqdm_kwargs
)
sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes'])
else:
errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history))
def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes):
read_count = min(self.max_read_size, remaining_len)
m = SMB2Message(SMB2ReadRequest(fid, offset, read_count))
m.tid = tid
self._sendSMBMessage(m)
self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback,
tid = tid, fid = fid, offset = offset,
remaining_len = remaining_len,
read_len = read_len,
file_attributes = file_attributes)