-
Notifications
You must be signed in to change notification settings - Fork 14
/
smb3.py
2084 lines (1754 loc) · 95.2 KB
/
smb3.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
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved.
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Author: Alberto Solino (@agsolino)
#
# Description:
# [MS-SMB2] Protocol Implementation (SMB2 and SMB3)
# As you might see in the code, it's implemented strictly following
# the structures defined in the protocol specification. This may
# not be the most efficient way (e.g. self._Connection is the
# same to self._Session in the context of this library ) but
# it certainly helps following the document way easier.
#
# ToDo:
# [X] Implement SMB2_CHANGE_NOTIFY
# [X] Implement SMB2_QUERY_INFO
# [X] Implement SMB2_SET_INFO
# [ ] Implement SMB2_OPLOCK_BREAK
# [X] Implement SMB3 signing
# [X] Implement SMB3 encryption
# [ ] Add more backward compatible commands from the smb.py code
# [ ] Fix up all the 'ToDo' comments inside the code
#
from __future__ import division
from __future__ import print_function
import socket
import ntpath
import random
import string
import struct
from asn1crypto import core
from impacket.krb5.gssapi import KRB5_AP_REQ
from six import indexbytes, b
from binascii import a2b_hex
from contextlib import contextmanager
from Cryptodome.Cipher import AES
from impacket import nmb, ntlm, uuid, crypto
from impacket.smb3structs import *
from impacket.nt_errors import STATUS_SUCCESS, STATUS_MORE_PROCESSING_REQUIRED, STATUS_INVALID_PARAMETER, \
STATUS_NO_MORE_FILES, STATUS_PENDING, STATUS_NOT_IMPLEMENTED, ERROR_MESSAGES
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID
#from impacket.krb5.gssapi import KRB5_AP_REQ
# For signing
import hashlib, hmac, copy
# Our random number generator
try:
rand = random.SystemRandom()
except NotImplementedError:
rand = random
pass
# Structs to be used
TREE_CONNECT = {
'ShareName' : '',
'TreeConnectId' : 0,
'Session' : 0,
'IsDfsShare' : False,
# If the client implements the SMB 3.0 dialect,
# the client MUST also implement the following
'IsCAShare' : False,
'EncryptData' : False,
'IsScaleoutShare' : False,
# Outside the protocol
'NumberOfUses' : 0,
}
FILE = {
'OpenTable' : [],
'LeaseKey' : '',
'LeaseState' : 0,
'LeaseEpoch' : 0,
}
OPEN = {
'FileID' : '',
'TreeConnect' : 0,
'Connection' : 0, # Not Used
'Oplocklevel' : 0,
'Durable' : False,
'FileName' : '',
'ResilientHandle' : False,
'LastDisconnectTime' : 0,
'ResilientTimeout' : 0,
'OperationBuckets' : [],
# If the client implements the SMB 3.0 dialect,
# the client MUST implement the following
'CreateGuid' : '',
'IsPersistent' : False,
'DesiredAccess' : '',
'ShareMode' : 0,
'CreateOption' : '',
'FileAttributes' : '',
'CreateDisposition' : '',
}
REQUEST = {
'CancelID' : '',
'Message' : '',
'Timestamp' : 0,
}
CHANNEL = {
'SigningKey' : '',
'Connection' : 0,
}
SMB2_DIALECT_311 = 0x0311
class SessionError(Exception):
def __init__( self, error = 0, packet=0):
Exception.__init__(self)
self.error = error
self.packet = packet
def get_error_code( self ):
return self.error
def get_error_packet( self ):
return self.packet
def __str__( self ):
return 'SMB SessionError: %s(%s)' % (ERROR_MESSAGES[self.error])
class SMB3:
class HostnameValidationException(Exception):
pass
def __init__(self, remote_name, remote_host, my_name=None, host_type=nmb.TYPE_SERVER, sess_port=445, timeout=60,
UDP=0, preferredDialect=None, session=None, negSessionResponse=None):
# [MS-SMB2] Section 3
self.RequireMessageSigning = False #
self.ConnectionTable = {}
self.GlobalFileTable = {}
self.ClientGuid = ''.join([random.choice(string.ascii_letters) for i in range(16)])
# Only for SMB 3.0
self.EncryptionAlgorithmList = ['AES-CCM']
self.MaxDialect = []
self.RequireSecureNegotiate = False
# Per Transport Connection Data
self._Connection = {
# Indexed by SessionID
#'SessionTable' : {},
# Indexed by MessageID
'OutstandingRequests' : {},
'OutstandingResponses' : {}, #
'SequenceWindow' : 0, #
'GSSNegotiateToken' : '', #
'MaxTransactSize' : 0, #
'MaxReadSize' : 0, #
'MaxWriteSize' : 0, #
'ServerGuid' : '', #
'RequireSigning' : False, #
'ServerName' : '', #
# If the client implements the SMB 2.1 or SMB 3.0 dialects, it MUST
# also implement the following
'Dialect' : 0, #
'SupportsFileLeasing' : False, #
'SupportsMultiCredit' : False, #
# If the client implements the SMB 3.0 dialect,
# it MUST also implement the following
'SupportsDirectoryLeasing' : False, #
'SupportsMultiChannel' : False, #
'SupportsPersistentHandles': False, #
'SupportsEncryption' : False, #
'ClientCapabilities' : 0,
'ServerCapabilities' : 0, #
'ClientSecurityMode' : 0, #
'ServerSecurityMode' : 0, #
# Outside the protocol
'ServerIP' : '', #
'ClientName' : '', #
}
self._Session = {
'SessionID' : 0, #
'TreeConnectTable' : {}, #
'SessionKey' : b'', #
'SigningRequired' : False, #
'Connection' : 0, #
'UserCredentials' : '', #
'OpenTable' : {}, #
# If the client implements the SMB 3.0 dialect,
# it MUST also implement the following
'ChannelList' : [],
'ChannelSequence' : 0,
#'EncryptData' : False,
'EncryptData' : True,
'EncryptionKey' : '',
'DecryptionKey' : '',
'SigningKey' : '',
'ApplicationKey' : b'',
# Outside the protocol
'SessionFlags' : 0, #
'ServerName' : '', #
'ServerDomain' : '', #
'ServerDNSDomainName' : '', #
'ServerDNSHostName' : '', #
'ServerOS' : '', #
'SigningActivated' : False, #
'PreauthIntegrityHashValue': a2b_hex(b'0'*128),
'CalculatePreAuthHash' : True,
}
self.SMB_PACKET = SMB2Packet
self._timeout = timeout
self._Connection['ServerIP'] = remote_host
self._NetBIOSSession = None
self._preferredDialect = preferredDialect
self._doKerberos = False
# Strict host validation - off by default
self._strict_hostname_validation = False
self._validation_allow_absent = True
self._accepted_hostname = ''
self.__userName = ''
self.__password = ''
self.__domain = ''
self.__lmhash = ''
self.__nthash = ''
self.__kdc = ''
self.__aesKey = ''
self.__TGT = None
self.__TGS = None
if sess_port == 445 and remote_name == '*SMBSERVER':
self._Connection['ServerName'] = remote_host
else:
self._Connection['ServerName'] = remote_name
# This is on purpose. I'm still not convinced to do a socket.gethostname() if not specified
if my_name is None:
self._Connection['ClientName'] = ''
else:
self._Connection['ClientName'] = my_name
if session is None:
if not my_name:
# If destination port is 139 yes, there's some client disclosure
my_name = socket.gethostname()
i = my_name.find('.')
if i > -1:
my_name = my_name[:i]
if UDP:
self._NetBIOSSession = nmb.NetBIOSUDPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout)
else:
self._NetBIOSSession = nmb.NetBIOSTCPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout)
self.negotiateSession(preferredDialect)
else:
self._NetBIOSSession = session
# We should increase the SequenceWindow since a packet was already received.
self._Connection['SequenceWindow'] += 1
# Let's negotiate again if needed (or parse the existing response) using the same connection
self.negotiateSession(preferredDialect, negSessionResponse)
def printStatus(self):
print("CONNECTION")
for i in list(self._Connection.items()):
print("%-40s : %s" % i)
print()
print("SESSION")
for i in list(self._Session.items()):
print("%-40s : %s" % i)
def __UpdatePreAuthHash(self, data):
from Cryptodome.Hash import SHA512
calculatedHash = SHA512.new()
calculatedHash.update(self._Session['PreauthIntegrityHashValue'])
calculatedHash.update(data)
self._Session['PreauthIntegrityHashValue'] = calculatedHash.digest()
def getKerberos(self):
return self._doKerberos
def getServerName(self):
return self._Session['ServerName']
def getClientName(self):
return self._Session['ClientName']
def getRemoteName(self):
if self._Session['ServerName'] == '':
return self._Connection['ServerName']
return self._Session['ServerName']
def setRemoteName(self, name):
self._Session['ServerName'] = name
return True
def getServerIP(self):
return self._Connection['ServerIP']
def getServerDomain(self):
return self._Session['ServerDomain']
def getServerDNSDomainName(self):
return self._Session['ServerDNSDomainName']
def getServerDNSHostName(self):
return self._Session['ServerDNSHostName']
def getServerOS(self):
return self._Session['ServerOS']
def getServerOSMajor(self):
return self._Session['ServerOSMajor']
def getServerOSMinor(self):
return self._Session['ServerOSMinor']
def getServerOSBuild(self):
return self._Session['ServerOSBuild']
def isGuestSession(self):
return self._Session['SessionFlags'] & SMB2_SESSION_FLAG_IS_GUEST
def setTimeout(self, timeout):
self._timeout = timeout
@contextmanager
def useTimeout(self, timeout):
prev_timeout = self.getTimeout(timeout)
try:
yield
finally:
self.setTimeout(prev_timeout)
def getDialect(self):
return self._Connection['Dialect']
def signSMB(self, packet):
packet['Signature'] = '\x00'*16
if self._Connection['Dialect'] == SMB2_DIALECT_21 or self._Connection['Dialect'] == SMB2_DIALECT_002:
if len(self._Session['SessionKey']) > 0:
signature = hmac.new(self._Session['SessionKey'], packet.getData(), hashlib.sha256).digest()
packet['Signature'] = signature[:16]
else:
if len(self._Session['SessionKey']) > 0:
p = packet.getData()
signature = crypto.AES_CMAC(self._Session['SigningKey'], p, len(p))
packet['Signature'] = signature
def sendSMB(self, packet):
# The idea here is to receive multiple/single commands and create a compound request, and send it
# Should return the MessageID for later retrieval. Implement compounded related requests.
# If Connection.Dialect is equal to "3.000" and if Connection.SupportsMultiChannel or
# Connection.SupportsPersistentHandles is TRUE, the client MUST set ChannelSequence in the
# SMB2 header to Session.ChannelSequence
# Check this is not a CANCEL request. If so, don't consume sequence numbers
if packet['Command'] is not SMB2_CANCEL:
packet['MessageID'] = self._Connection['SequenceWindow']
self._Connection['SequenceWindow'] += 1
packet['SessionID'] = self._Session['SessionID']
# Default the credit charge to 1 unless set by the caller
if ('CreditCharge' in packet.fields) is False:
packet['CreditCharge'] = 1
# Standard credit request after negotiating protocol
if self._Connection['SequenceWindow'] > 3:
packet['CreditRequestResponse'] = 33
messageId = packet['MessageID']
if self._Session['SigningActivated'] is True and self._Connection['SequenceWindow'] > 2:
if packet['TreeID'] > 0 and (packet['TreeID'] in self._Session['TreeConnectTable']) is True:
if self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is False:
packet['Flags'] = SMB2_FLAGS_SIGNED
self.signSMB(packet)
elif packet['TreeID'] == 0:
packet['Flags'] = SMB2_FLAGS_SIGNED
self.signSMB(packet)
if (self._Session['SessionFlags'] & SMB2_SESSION_FLAG_ENCRYPT_DATA) or ( packet['TreeID'] != 0 and self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is True):
plainText = packet.getData()
transformHeader = SMB2_TRANSFORM_HEADER()
transformHeader['Nonce'] = ''.join([rand.choice(string.ascii_letters) for _ in range(11)])
transformHeader['OriginalMessageSize'] = len(plainText)
transformHeader['EncryptionAlgorithm'] = SMB2_ENCRYPTION_AES128_CCM
transformHeader['SessionID'] = self._Session['SessionID']
cipher = AES.new(self._Session['EncryptionKey'], AES.MODE_CCM, b(transformHeader['Nonce']))
cipher.update(transformHeader.getData()[20:])
cipherText = cipher.encrypt(plainText)
transformHeader['Signature'] = cipher.digest()
packet = transformHeader.getData() + cipherText
self._NetBIOSSession.send_packet(packet)
else:
data = packet.getData()
if self._Session['CalculatePreAuthHash'] is True:
self.__UpdatePreAuthHash(data)
self._NetBIOSSession.send_packet(data)
return messageId
def recvSMB(self, packetID = None):
# First, verify we don't have the packet already
if packetID in self._Connection['OutstandingResponses']:
return self._Connection['OutstandingResponses'].pop(packetID)
data = self._NetBIOSSession.recv_packet(self._timeout)
if data.get_trailer().startswith(b'\xfdSMB'):
# Packet is encrypted
transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer())
cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM, transformHeader['Nonce'][:11])
cipher.update(transformHeader.getData()[20:])
plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):])
#cipher.verify(transformHeader['Signature'])
packet = SMB2Packet(plainText)
else:
# In all SMB dialects for a response this field is interpreted as the Status field.
# This field can be set to any value. For a list of valid status codes,
# see [MS-ERREF] section 2.3.
packet = SMB2Packet(data.get_trailer())
# Loop while we receive pending requests
if packet['Status'] == STATUS_PENDING:
status = STATUS_PENDING
while status == STATUS_PENDING:
data = self._NetBIOSSession.recv_packet(self._timeout)
if data.get_trailer().startswith(b'\xfeSMB'):
packet = SMB2Packet(data.get_trailer())
else:
# Packet is encrypted
transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer())
cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM, transformHeader['Nonce'][:11])
cipher.update(transformHeader.getData()[20:])
plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):])
#cipher.verify(transformHeader['Signature'])
packet = SMB2Packet(plainText)
status = packet['Status']
if packet['MessageID'] == packetID or packetID is None:
# Let's update the sequenceWindow based on the CreditsCharged
# In the SMB 2.0.2 dialect, this field MUST NOT be used and MUST be reserved.
# The sender MUST set this to 0, and the receiver MUST ignore it.
# In all other dialects, this field indicates the number of credits that this request consumes.
if self._Connection['Dialect'] > SMB2_DIALECT_002:
self._Connection['SequenceWindow'] += (packet['CreditCharge'] - 1)
return packet
else:
self._Connection['OutstandingResponses'][packet['MessageID']] = packet
return self.recvSMB(packetID)
def negotiateSession(self, preferredDialect = None, negSessionResponse = None):
# Let's store some data for later use
self._Connection['ClientSecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED
if self.RequireMessageSigning is True:
self._Connection['ClientSecurityMode'] |= SMB2_NEGOTIATE_SIGNING_REQUIRED
self._Connection['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION
currentDialect = SMB2_DIALECT_WILDCARD
# Do we have a negSessionPacket already?
if negSessionResponse is not None:
# Yes, let's store the dialect answered back
negResp = SMB2Negotiate_Response(negSessionResponse['Data'])
currentDialect = negResp['DialectRevision']
if currentDialect == SMB2_DIALECT_WILDCARD:
# Still don't know the chosen dialect, let's send our options
packet = self.SMB_PACKET()
packet['Command'] = SMB2_NEGOTIATE
negSession = SMB2Negotiate()
negSession['SecurityMode'] = self._Connection['ClientSecurityMode']
negSession['Capabilities'] = self._Connection['Capabilities']
negSession['ClientGuid'] = self.ClientGuid
if preferredDialect is not None:
negSession['Dialects'] = [preferredDialect]
if preferredDialect == SMB2_DIALECT_311:
# Build the Contexts
contextData = SMB311ContextData()
contextData['NegotiateContextOffset'] = 64+38+2
contextData['NegotiateContextCount'] = 0
# Add an SMB2_NEGOTIATE_CONTEXT with ContextType as SMB2_PREAUTH_INTEGRITY_CAPABILITIES
# to the negotiate request as specified in section 2.2.3.1:
negotiateContext = SMB2NegotiateContext()
negotiateContext['ContextType'] = SMB2_PREAUTH_INTEGRITY_CAPABILITIES
preAuthIntegrityCapabilities = SMB2PreAuthIntegrityCapabilities()
preAuthIntegrityCapabilities['HashAlgorithmCount'] = 1
preAuthIntegrityCapabilities['SaltLength'] = 32
preAuthIntegrityCapabilities['HashAlgorithms'] = b'\x01\x00'
preAuthIntegrityCapabilities['Salt'] = ''.join([rand.choice(string.ascii_letters) for _ in
range(preAuthIntegrityCapabilities['SaltLength'])])
negotiateContext['Data'] = preAuthIntegrityCapabilities.getData()
negotiateContext['DataLength'] = len(negotiateContext['Data'])
contextData['NegotiateContextCount'] += 1
pad = b'\xFF' * (8 - (negotiateContext['DataLength'] % 8))
# Add an SMB2_NEGOTIATE_CONTEXT with ContextType as SMB2_ENCRYPTION_CAPABILITIES
# to the negotiate request as specified in section 2.2.3.1 and initialize
# the Ciphers field with the ciphers supported by the client in the order of preference.
negotiateContext2 = SMB2NegotiateContext ()
negotiateContext2['ContextType'] = SMB2_ENCRYPTION_CAPABILITIES
encryptionCapabilities = SMB2EncryptionCapabilities()
encryptionCapabilities['CipherCount'] = 1
encryptionCapabilities['Ciphers'] = 1
negotiateContext2['Data'] = encryptionCapabilities.getData()
negotiateContext2['DataLength'] = len(negotiateContext2['Data'])
contextData['NegotiateContextCount'] += 1
negSession['ClientStartTime'] = contextData.getData()
negSession['Padding'] = b'\xFF\xFF'
# Subsequent negotiate contexts MUST appear at the first 8-byte aligned offset following the
# previous negotiate context.
negSession['NegotiateContextList'] = negotiateContext.getData() + pad + negotiateContext2.getData()
# Do you want to enforce encryption? Uncomment here:
#self._Connection['SupportsEncryption'] = True
else:
negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]
negSession['DialectCount'] = len(negSession['Dialects'])
packet['Data'] = negSession
packetID = self.sendSMB(packet)
ans = self.recvSMB(packetID)
if ans.isValidAnswer(STATUS_SUCCESS):
negResp = SMB2Negotiate_Response(ans['Data'])
if negResp['DialectRevision'] == SMB2_DIALECT_311:
self.__UpdatePreAuthHash(ans.rawData)
self._Connection['MaxTransactSize'] = min(0x100000,negResp['MaxTransactSize'])
self._Connection['MaxReadSize'] = min(0x100000,negResp['MaxReadSize'])
self._Connection['MaxWriteSize'] = min(0x100000,negResp['MaxWriteSize'])
self._Connection['ServerGuid'] = negResp['ServerGuid']
self._Connection['GSSNegotiateToken'] = negResp['Buffer']
self._Connection['Dialect'] = negResp['DialectRevision']
if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED or \
self._Connection['Dialect'] == SMB2_DIALECT_311:
self._Connection['RequireSigning'] = True
if self._Connection['Dialect'] == SMB2_DIALECT_311:
# Always Sign
self._Connection['RequireSigning'] = True
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING:
self._Connection['SupportsFileLeasing'] = True
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LARGE_MTU) == SMB2_GLOBAL_CAP_LARGE_MTU:
self._Connection['SupportsMultiCredit'] = True
if self._Connection['Dialect'] >= SMB2_DIALECT_30:
# Switching to the right packet format
self.SMB_PACKET = SMB3Packet
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) == SMB2_GLOBAL_CAP_DIRECTORY_LEASING:
self._Connection['SupportsDirectoryLeasing'] = True
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_MULTI_CHANNEL) == SMB2_GLOBAL_CAP_MULTI_CHANNEL:
self._Connection['SupportsMultiChannel'] = True
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == SMB2_GLOBAL_CAP_PERSISTENT_HANDLES:
self._Connection['SupportsPersistentHandles'] = True
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION:
self._Connection['SupportsEncryption'] = True
self._Connection['ServerCapabilities'] = negResp['Capabilities']
self._Connection['ServerSecurityMode'] = negResp['SecurityMode']
def getCredentials(self):
return (
self.__userName,
self.__password,
self.__domain,
self.__lmhash,
self.__nthash,
self.__aesKey,
self.__TGT,
self.__TGS)
def getCertificate(self):
return (
self.__userCert,
self.__certPass)
def kerberosLogin(self, user, password, domain = '', lmhash = '', nthash = '', aesKey='', kdcHost = '', TGT=None, TGS=None):
# If TGT or TGS are specified, they are in the form of:
# TGS['KDC_REP'] = the response from the server
# TGS['cipher'] = the cipher used
# TGS['sessionKey'] = the sessionKey
# If we have hashes, normalize them
if lmhash != '' or nthash != '':
if len(lmhash) % 2: lmhash = '0%s' % lmhash
if len(nthash) % 2: nthash = '0%s' % nthash
try: # just in case they were converted already
lmhash = a2b_hex(lmhash)
nthash = a2b_hex(nthash)
except:
pass
self.__userName = user
self.__password = password
self.__domain = domain
self.__lmhash = lmhash
self.__nthash = nthash
self.__kdc = kdcHost
self.__aesKey = aesKey
self.__TGT = TGT
self.__TGS = TGS
self._doKerberos= True
sessionSetup = SMB2SessionSetup()
if self.RequireMessageSigning is True:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED
else:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED
sessionSetup['Flags'] = 0
#sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS
# Importing down here so pyasn1 is not required if kerberos is not used.
from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.krb5 import constants
from impacket.krb5.types import Principal, KerberosTime, Ticket
from pyasn1.codec.der import decoder, encoder
import datetime
# First of all, we need to get a TGT for the user
userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
if TGT is None:
if TGS is None:
tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)
else:
tgt = TGT['KDC_REP']
cipher = TGT['cipher']
sessionKey = TGT['sessionKey']
# Save the ticket
# If you want, for debugging purposes
# from impacket.krb5.ccache import CCache
# ccache = CCache()
# try:
# if TGS is None:
# ccache.fromTGT(tgt, oldSessionKey, sessionKey)
# else:
# ccache.fromTGS(TGS['KDC_REP'], TGS['oldSessionKey'], TGS['sessionKey'] )
# ccache.saveFile('/tmp/ticket.bin')
# except Exception, e:
# print e
# pass
# Now that we have the TGT, we should ask for a TGS for cifs
if TGS is None:
serverName = Principal('cifs/%s' % (self._Connection['ServerName']), type=constants.PrincipalNameType.NT_SRV_INST.value)
tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)
else:
tgs = TGS['KDC_REP']
cipher = TGS['cipher']
sessionKey = TGS['sessionKey']
# Let's build a NegTokenInit with a Kerberos REQ_AP
blob = SPNEGO_NegTokenInit()
# Kerberos
blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]
# Let's extract the ticket from the TGS
tgs = decoder.decode(tgs, asn1Spec = TGS_REP())[0]
ticket = Ticket()
ticket.from_asn1(tgs['ticket'])
# Now let's build the AP_REQ
apReq = AP_REQ()
apReq['pvno'] = 5
apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)
opts = list()
apReq['ap-options'] = constants.encodeFlags(opts)
seq_set(apReq,'ticket', ticket.to_asn1)
authenticator = Authenticator()
authenticator['authenticator-vno'] = 5
authenticator['crealm'] = domain
seq_set(authenticator, 'cname', userName.components_to_asn1)
now = datetime.datetime.utcnow()
authenticator['cusec'] = now.microsecond
authenticator['ctime'] = KerberosTime.to_asn1(now)
encodedAuthenticator = encoder.encode(authenticator)
# Key Usage 11
# AP-REQ Authenticator (includes application authenticator
# subkey), encrypted with the application session key
# (Section 5.5.1)
encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)
apReq['authenticator'] = None
apReq['authenticator']['etype'] = cipher.enctype
apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator
blob['MechToken'] = struct.pack('B', ASN1_AID) + asn1encode( struct.pack('B', ASN1_OID) + asn1encode(
TypesMech['KRB5 - Kerberos 5'] ) + KRB5_AP_REQ + encoder.encode(apReq))
sessionSetup['SecurityBufferLength'] = len(blob)
sessionSetup['Buffer'] = blob.getData()
packet = self.SMB_PACKET()
packet['Command'] = SMB2_SESSION_SETUP
packet['Data'] = sessionSetup
packetID = self.sendSMB(packet)
ans = self.recvSMB(packetID)
if ans.isValidAnswer(STATUS_SUCCESS):
self._Session['SessionID'] = ans['SessionID']
self._Session['SigningRequired'] = self._Connection['RequireSigning']
self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash)
self._Session['Connection'] = self._NetBIOSSession.get_socket()
self._Session['SessionKey'] = sessionKey.contents[:16]
if self._Session['SigningRequired'] is True and self._Connection['Dialect'] >= SMB2_DIALECT_30:
# If Connection.Dialect is "3.1.1", the case-sensitive ASCII string "SMBSigningKey" as the label;
# otherwise, the case - sensitive ASCII string "SMB2AESCMAC" as the label.
# If Connection.Dialect is "3.1.1", Session.PreauthIntegrityHashValue as the context; otherwise,
# the case-sensitive ASCII string "SmbSign" as context for the algorithm.
if self._Connection['Dialect'] == SMB2_DIALECT_311:
self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBSigningKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
else:
self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCMAC\x00",
b"SmbSign\x00", 128)
# Do not encrypt anonymous connections
if user == '' or self.isGuestSession():
self._Connection['SupportsEncryption'] = False
if self._Session['SigningRequired'] is True:
self._Session['SigningActivated'] = True
if self._Connection['Dialect'] >= SMB2_DIALECT_30 and self._Connection['SupportsEncryption'] is True:
# Encryption available. Let's enforce it if we have AES CCM available
self._Session['SessionFlags'] |= SMB2_SESSION_FLAG_ENCRYPT_DATA
# Application Key
# If Connection.Dialect is "3.1.1",the case-sensitive ASCII string "SMBAppKey" as the label;
# otherwise, the case-sensitive ASCII string "SMB2APP" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "SmbRpc" as context for the algorithm.
# Encryption Key
# If Connection.Dialect is "3.1.1",the case-sensitive ASCII string "SMBC2SCipherKey" as # the label;
# otherwise, the case-sensitive ASCII string "SMB2AESCCM" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "ServerIn " as context for the algorithm
# (note the blank space at the end)
# Decryption Key
# If Connection.Dialect is "3.1.1", the case-sensitive ASCII string "SMBS2CCipherKey" as the label;
# otherwise, the case-sensitive ASCII string "SMB2AESCCM" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "ServerOut" as context for the algorithm.
if self._Connection['Dialect'] == SMB2_DIALECT_311:
self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBAppKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBC2SCipherKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBS2CCipherKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
else:
self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2APP\x00",
b"SmbRpc\x00", 128)
self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCCM\x00",
b"ServerIn \x00", 128)
self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCCM\x00",
b"ServerOut\x00", 128)
self._Session['CalculatePreAuthHash'] = False
return True
else:
# We clean the stuff we used in case we want to authenticate again
# within the same connection
self._Session['UserCredentials'] = ''
self._Session['Connection'] = 0
self._Session['SessionID'] = 0
self._Session['SigningRequired'] = False
self._Session['SigningKey'] = ''
self._Session['SessionKey'] = ''
self._Session['SigningActivated'] = False
self._Session['CalculatePreAuthHash'] = False
self._Session['PreauthIntegrityHashValue'] = a2b_hex(b'0'*128)
raise Exception('Unsuccessful Login')
# changed from original impacket
def kerberosCertificateLogin(self, userCert, certPass):
self.__userCert = userCert
self.__certPass = certPass
self._doKerberos= True
remoteComputer = self._Connection['ServerName']
sessionSetup = SMB2SessionSetup()
if self.RequireMessageSigning is True:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED
else:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED
sessionSetup['Flags'] = 0
#sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS
# Importing down here so pyasn1 is not required if kerberos is not used.
from AzureADPTC.Helper import NegoExHelper
negoExHelper = NegoExHelper(self.__userCert, self.__certPass, remoteComputer)
NegoExKerberosAsReq = negoExHelper.GenerateNegoExKerberosAs()
blob = SPNEGO_NegTokenInit()
blob['MechTypes'] = [TypesMech['NEGOEX - SPNEGO Extended Negotiation Security Mechanism'],
TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
blob['MechToken'] = bytes.fromhex(NegoExKerberosAsReq)
sessionSetup = SMB2SessionSetup()
sessionSetup['SecurityMode'] = 1
sessionSetup['SecurityBufferLength'] = len(blob)
sessionSetup['Buffer'] = blob.getData()
self.SMB_PACKET = SMB2Packet
packet = self.SMB_PACKET()
packet['Command'] = SMB2_SESSION_SETUP
packet['Flags'] = 16
packet['process_id'] = 0xfeff
packet['Data'] = sessionSetup
packetID = self.sendSMB(packet)
ans = self.recvSMB(packetID)
if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED):
self._Session['SessionID'] = ans['SessionID']
self._Session['SigningRequired'] = self._Connection['RequireSigning']
NegoExKerberosApReq = negoExHelper.GenerateNegoExKerberosAp(ans)
sessionSetup = SMB2SessionSetup()
blob = SPNEGO_NegTokenResp()
blob['negState'] = 'accept-incomplete'
blob['ResponseToken'] = bytearray.fromhex(NegoExKerberosApReq)
sessionSetup['SecurityMode'] = 1
sessionSetup['SecurityBufferLength'] = len(blob)
sessionSetup['Buffer'] = blob.getData()
packet = self.SMB_PACKET()
packet['Command'] = SMB2_SESSION_SETUP
packet['Flags'] = 16
packet['Data'] = sessionSetup
packetID = self.sendSMB(packet)
ans = self.recvSMB(packetID)
self._Session['Connection'] = self._NetBIOSSession.get_socket()
return True
self._Session['SessionKey'] = sessionKey.contents[:16]
if self._Session['SigningRequired'] is True and self._Connection['Dialect'] >= SMB2_DIALECT_30:
# If Connection.Dialect is "3.1.1", the case-sensitive ASCII string "SMBSigningKey" as the label;
# otherwise, the case - sensitive ASCII string "SMB2AESCMAC" as the label.
# If Connection.Dialect is "3.1.1", Session.PreauthIntegrityHashValue as the context; otherwise,
# the case-sensitive ASCII string "SmbSign" as context for the algorithm.
if self._Connection['Dialect'] == SMB2_DIALECT_311:
self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBSigningKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
else:
self._Session['SigningKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCMAC\x00",
b"SmbSign\x00", 128)
# Do not encrypt anonymous connections
if user == '' or self.isGuestSession():
self._Connection['SupportsEncryption'] = False
if self._Session['SigningRequired'] is True:
self._Session['SigningActivated'] = True
if self._Connection['Dialect'] >= SMB2_DIALECT_30 and self._Connection['SupportsEncryption'] is True:
# Encryption available. Let's enforce it if we have AES CCM available
self._Session['SessionFlags'] |= SMB2_SESSION_FLAG_ENCRYPT_DATA
# Application Key
# If Connection.Dialect is "3.1.1",the case-sensitive ASCII string "SMBAppKey" as the label;
# otherwise, the case-sensitive ASCII string "SMB2APP" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "SmbRpc" as context for the algorithm.
# Encryption Key
# If Connection.Dialect is "3.1.1",the case-sensitive ASCII string "SMBC2SCipherKey" as # the label;
# otherwise, the case-sensitive ASCII string "SMB2AESCCM" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "ServerIn " as context for the algorithm
# (note the blank space at the end)
# Decryption Key
# If Connection.Dialect is "3.1.1", the case-sensitive ASCII string "SMBS2CCipherKey" as the label;
# otherwise, the case-sensitive ASCII string "SMB2AESCCM" as the label. Session.PreauthIntegrityHashValue
# as the context; otherwise, the case-sensitive ASCII string "ServerOut" as context for the algorithm.
if self._Connection['Dialect'] == SMB2_DIALECT_311:
self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBAppKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBC2SCipherKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMBS2CCipherKey\x00",
self._Session['PreauthIntegrityHashValue'], 128)
else:
self._Session['ApplicationKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2APP\x00",
b"SmbRpc\x00", 128)
self._Session['EncryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCCM\x00",
b"ServerIn \x00", 128)
self._Session['DecryptionKey'] = crypto.KDF_CounterMode (self._Session['SessionKey'], b"SMB2AESCCM\x00",
b"ServerOut\x00", 128)
self._Session['CalculatePreAuthHash'] = False
return True
else:
# We clean the stuff we used in case we want to authenticate again
# within the same connection
self._Session['UserCredentials'] = ''
self._Session['Connection'] = 0
self._Session['SessionID'] = 0
self._Session['SigningRequired'] = False
self._Session['SigningKey'] = ''
self._Session['SessionKey'] = ''
self._Session['SigningActivated'] = False
self._Session['CalculatePreAuthHash'] = False
self._Session['PreauthIntegrityHashValue'] = a2b_hex(b'0'*128)
raise Exception('Unsuccessful Login')
def login(self, user, password, domain = '', lmhash = '', nthash = ''):
# If we have hashes, normalize them
if lmhash != '' or nthash != '':
if len(lmhash) % 2: lmhash = '0%s' % lmhash
if len(nthash) % 2: nthash = '0%s' % nthash
try: # just in case they were converted already
lmhash = a2b_hex(lmhash)
nthash = a2b_hex(nthash)
except:
pass
self.__userName = user
self.__password = password
self.__domain = domain
self.__lmhash = lmhash
self.__nthash = nthash
self.__aesKey = ''
self.__TGT = None
self.__TGS = None
sessionSetup = SMB2SessionSetup()
if self.RequireMessageSigning is True:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED
else:
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED
sessionSetup['Flags'] = 0
#sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS
# Let's build a NegTokenInit with the NTLMSSP
# TODO: In the future we should be able to choose different providers
blob = SPNEGO_NegTokenInit()
# NTLMSSP
blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
auth = ntlm.getNTLMSSPType1(self._Connection['ClientName'],domain, self._Connection['RequireSigning'])
blob['MechToken'] = auth.getData()
sessionSetup['SecurityBufferLength'] = len(blob)
sessionSetup['Buffer'] = blob.getData()
# ToDo:
# If this authentication is for establishing an alternative channel for an existing Session, as specified
# in section 3.2.4.1.7, the client MUST also set the following values:
# The SessionId field in the SMB2 header MUST be set to the Session.SessionId for the new
# channel being established.
# The SMB2_SESSION_FLAG_BINDING bit MUST be set in the Flags field.
# The PreviousSessionId field MUST be set to zero.
packet = self.SMB_PACKET()
packet['Command'] = SMB2_SESSION_SETUP
packet['Data'] = sessionSetup
packetID = self.sendSMB(packet)
ans = self.recvSMB(packetID)
if self._Connection['Dialect'] == SMB2_DIALECT_311:
self.__UpdatePreAuthHash (ans.rawData)
if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED):
self._Session['SessionID'] = ans['SessionID']
self._Session['SigningRequired'] = self._Connection['RequireSigning']
self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash)