-
Notifications
You must be signed in to change notification settings - Fork 1
/
smbserver.py
4913 lines (4183 loc) · 224 KB
/
smbserver.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
# Impacket - Collection of Python classes for working with network protocols.
#
# SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Author:
# Alberto Solino (@agsolino)
#
# TODO:
# [-] Functions should return NT error codes
# [-] Handling errors in all situations, right now it's just raising exceptions.
# [*] Standard authentication support
# [ ] Organize the connectionData stuff
# [*] Add capability to send a bad user ID if the user is not authenticated,
# right now you can ask for any command without actually being authenticated
# [ ] PATH TRAVERSALS EVERYWHERE.. BE WARNED!
# [ ] Check error situation (now many places assume the right data is coming)
# [ ] Implement IPC to the main process so the connectionData is on a single place
# [ ] Hence.. implement locking
# estamos en la B
import calendar
import socket
import time
import datetime
import struct
import threading
import logging
import logging.config
import ntpath
import os
import fnmatch
import errno
import sys
import random
import shutil
import string
import hashlib
import hmac
from binascii import unhexlify, hexlify, a2b_hex
from six import PY2, b, text_type
from six.moves import configparser, socketserver
# For signing
from impacket import smb, nmb, ntlm, uuid
from impacket import smb3structs as smb2
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, MechTypes, SPNEGO_NegTokenResp, ASN1_AID, \
ASN1_SUPPORTED_MECH
from impacket.nt_errors import STATUS_NO_MORE_FILES, STATUS_NETWORK_NAME_DELETED, STATUS_INVALID_PARAMETER, \
STATUS_FILE_CLOSED, STATUS_MORE_PROCESSING_REQUIRED, STATUS_OBJECT_PATH_NOT_FOUND, STATUS_DIRECTORY_NOT_EMPTY, \
STATUS_FILE_IS_A_DIRECTORY, STATUS_NOT_IMPLEMENTED, STATUS_INVALID_HANDLE, STATUS_OBJECT_NAME_COLLISION, \
STATUS_NO_SUCH_FILE, STATUS_CANCELLED, STATUS_OBJECT_NAME_NOT_FOUND, STATUS_SUCCESS, STATUS_ACCESS_DENIED, \
STATUS_NOT_SUPPORTED, STATUS_INVALID_DEVICE_REQUEST, STATUS_FS_DRIVER_REQUIRED, STATUS_INVALID_INFO_CLASS, \
STATUS_LOGON_FAILURE, STATUS_OBJECT_PATH_SYNTAX_BAD
# Setting LOG to current's module name
LOG = logging.getLogger(__name__)
# These ones not defined in nt_errors
STATUS_SMB_BAD_UID = 0x005B0002
STATUS_SMB_BAD_TID = 0x00050002
# Utility functions
# and general functions.
# There are some common functions that can be accessed from more than one SMB
# command (or either TRANSACTION). That's why I'm putting them here
# TODO: Return NT ERROR Codes
def computeNTLMv2(identity, lmhash, nthash, serverChallenge, authenticateMessage, ntlmChallenge, type1):
# Let's calculate the NTLMv2 Response
responseKeyNT = ntlm.NTOWFv2(identity, '', authenticateMessage['domain_name'].decode('utf-16le'), nthash)
responseKeyLM = ntlm.LMOWFv2(identity, '', authenticateMessage['domain_name'].decode('utf-16le'), lmhash)
ntProofStr = authenticateMessage['ntlm'][:16]
temp = authenticateMessage['ntlm'][16:]
ntProofStr2 = ntlm.hmac_md5(responseKeyNT, serverChallenge + temp)
lmChallengeResponse = authenticateMessage['lanman']
sessionBaseKey = ntlm.hmac_md5(responseKeyNT, ntProofStr)
responseFlags = type1['flags']
# Let's check the return flags
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) == 0:
# No extended session security, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_128) == 0:
# No support for 128 key len, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_128
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH) == 0:
# No key exchange supported, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_SEAL) == 0:
# No sign available, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_SEAL
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_SIGN) == 0:
# No sign available, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_SIGN
if (ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN) == 0:
# No sign available, taking it out
responseFlags &= 0xffffffff ^ ntlm.NTLMSSP_NEGOTIATE_ALWAYS_SIGN
keyExchangeKey = ntlm.KXKEY(ntlmChallenge['flags'], sessionBaseKey, lmChallengeResponse,
ntlmChallenge['challenge'], '',
lmhash, nthash, True)
# If we set up key exchange, let's fill the right variables
if ntlmChallenge['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH:
exportedSessionKey = authenticateMessage['session_key']
exportedSessionKey = ntlm.generateEncryptedSessionKey(keyExchangeKey, exportedSessionKey)
else:
encryptedRandomSessionKey = None
# [MS-NLMP] page 46
exportedSessionKey = keyExchangeKey
# Do they match?
if ntProofStr == ntProofStr2:
# Yes!, process login
return STATUS_SUCCESS, exportedSessionKey
else:
return STATUS_LOGON_FAILURE, exportedSessionKey
def outputToJohnFormat(challenge, username, domain, lmresponse, ntresponse):
# We don't want to add a possible failure here, since this is an
# extra bonus. We try, if it fails, returns nothing
# ToDo: Document the parameter's types (bytes / string) and check all the places where it's called
ret_value = ''
if type(challenge) is not bytes:
challenge = challenge.decode('latin-1')
try:
if len(ntresponse) > 24:
# Extended Security - NTLMv2
ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (
username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(challenge).decode('latin-1'),
hexlify(ntresponse).decode('latin-1')[:32],
hexlify(ntresponse).decode()[32:]), 'hash_version': 'ntlmv2'}
else:
# NTLMv1
ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (
username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(lmresponse).decode('latin-1'),
hexlify(ntresponse).decode('latin-1'),
hexlify(challenge).decode()), 'hash_version': 'ntlm'}
except:
# Let's try w/o decoding Unicode
try:
if len(ntresponse) > 24:
# Extended Security - NTLMv2
ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (
username.decode('latin-1'), domain.decode('latin-1'), hexlify(challenge).decode('latin-1'),
hexlify(ntresponse)[:32].decode('latin-1'), hexlify(ntresponse)[32:].decode('latin-1')),
'hash_version': 'ntlmv2'}
else:
# NTLMv1
ret_value = {'hash_string': '%s::%s:%s:%s:%s' % (
username, domain, hexlify(lmresponse).decode('latin-1'), hexlify(ntresponse).decode('latin-1'),
hexlify(challenge).decode('latin-1')), 'hash_version': 'ntlm'}
except Exception as e:
import traceback
traceback.print_exc()
LOG.error("outputToJohnFormat: %s" % e)
pass
return ret_value
def writeJohnOutputToFile(hash_string, hash_version, file_name):
fn_data = os.path.splitext(file_name)
if hash_version == "ntlmv2":
output_filename = fn_data[0] + "_ntlmv2" + fn_data[1]
else:
output_filename = fn_data[0] + "_ntlm" + fn_data[1]
with open(output_filename, "a") as f:
f.write(hash_string)
f.write('\n')
def decodeSMBString(flags, text):
if flags & smb.SMB.FLAGS2_UNICODE:
return text.decode('utf-16le')
else:
return text
def encodeSMBString(flags, text):
if flags & smb.SMB.FLAGS2_UNICODE:
return (text).encode('utf-16le')
else:
return text.encode('ascii')
def getFileTime(t):
t *= 10000000
t += 116444736000000000
return t
def getUnixTime(t):
t -= 116444736000000000
t //= 10000000
return t
def getSMBDate(t):
# TODO: Fix this :P
d = datetime.date.fromtimestamp(t)
year = d.year - 1980
ret = (year << 8) + (d.month << 4) + d.day
return ret
def getSMBTime(t):
# TODO: Fix this :P
d = datetime.datetime.fromtimestamp(t)
return (d.hour << 8) + (d.minute << 4) + d.second
def getShares(connId, smbServer):
config = smbServer.getServerConfig()
sections = config.sections()
# Remove the global one
del (sections[sections.index('global')])
shares = {}
for i in sections:
shares[i] = dict(config.items(i))
return shares
def searchShare(connId, share, smbServer):
config = smbServer.getServerConfig()
if config.has_section(share):
return dict(config.items(share))
else:
return None
def normalize_path(file_name, path=None):
"""Normalizes a path by replacing "\" with "/" and stripping potential
leading "/" chars. If a path is provided, only strip leading '/' when
the path is empty.
:param file_name: file name to normalize
:type file_name: string
:param path: path to normalize
:type path: string
:return normalized file name
:rtype string
"""
file_name = os.path.normpath(file_name.replace('\\', '/'))
if len(file_name) > 0 and (file_name[0] == '/' or file_name[0] == '\\'):
if path is None or path != '':
# Strip leading "/"
file_name = file_name[1:]
return file_name
def isInFileJail(path, file_name):
"""Validates if a provided file name path is inside a path. This function is used
to check for path traversals.
:param path: base path to check
:type path: string
:param file_name: file name to validate
:type file_name: string
:return whether the file name is inside the base path or not
:rtype bool
"""
path_name = os.path.join(path, file_name)
share_real_path = os.path.realpath(path)
return os.path.commonprefix((os.path.realpath(path_name), share_real_path)) == share_real_path
def openFile(path, fileName, accessMode, fileAttributes, openMode):
fileName = normalize_path(fileName)
pathName = os.path.join(path, fileName)
errorCode = 0
mode = 0
if not isInFileJail(path, fileName):
LOG.error("Path not in current working directory")
errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD
return 0, mode, pathName, errorCode
# Check the Open Mode
if openMode & 0x10:
# If the file does not exist, create it.
mode = os.O_CREAT
else:
# If file does not exist, return an error
if os.path.exists(pathName) is not True:
errorCode = STATUS_NO_SUCH_FILE
return 0, mode, pathName, errorCode
if os.path.isdir(pathName) and (fileAttributes & smb.ATTR_DIRECTORY) == 0:
# Request to open a normal file and this is actually a directory
errorCode = STATUS_FILE_IS_A_DIRECTORY
return 0, mode, pathName, errorCode
# Check the Access Mode
if accessMode & 0x7 == 1:
mode |= os.O_WRONLY
elif accessMode & 0x7 == 2:
mode |= os.O_RDWR
else:
mode = os.O_RDONLY
try:
if sys.platform == 'win32':
mode |= os.O_BINARY
fid = os.open(pathName, mode)
except Exception as e:
LOG.error("openFile: %s,%s" % (pathName, mode), e)
fid = 0
errorCode = STATUS_ACCESS_DENIED
return fid, mode, pathName, errorCode
def queryFsInformation(path, filename, level=None, pktFlags=smb.SMB.FLAGS2_UNICODE):
if pktFlags & smb.SMB.FLAGS2_UNICODE:
encoding = 'utf-16le'
else:
encoding = 'ascii'
fileName = normalize_path(filename)
pathName = os.path.join(path, fileName)
fileSize = os.path.getsize(pathName)
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName)
if level is None:
lastWriteTime = mtime
attribs = 0
if os.path.isdir(pathName):
attribs |= smb.SMB_FILE_ATTRIBUTE_DIRECTORY
if os.path.isfile(pathName):
attribs |= smb.SMB_FILE_ATTRIBUTE_NORMAL
fileAttributes = attribs
return fileSize, lastWriteTime, fileAttributes
elif level == smb.SMB_QUERY_FS_ATTRIBUTE_INFO or level == smb2.SMB2_FILESYSTEM_ATTRIBUTE_INFO:
data = smb.SMBQueryFsAttributeInfo()
data['FileSystemAttributes'] = smb.FILE_CASE_SENSITIVE_SEARCH | smb.FILE_CASE_PRESERVED_NAMES
data['MaxFilenNameLengthInBytes'] = 255
data['LengthOfFileSystemName'] = len('XTFS') * 2
data['FileSystemName'] = 'XTFS'.encode('utf-16le')
return data.getData()
elif level == smb.SMB_INFO_VOLUME:
data = smb.SMBQueryFsInfoVolume(flags=pktFlags)
data['VolumeLabel'] = 'SHARE'.encode(encoding)
return data.getData()
elif level == smb.SMB_QUERY_FS_VOLUME_INFO or level == smb2.SMB2_FILESYSTEM_VOLUME_INFO:
data = smb.SMBQueryFsVolumeInfo()
data['VolumeLabel'] = ''
data['VolumeCreationTime'] = getFileTime(ctime)
return data.getData()
elif level == smb.SMB_QUERY_FS_SIZE_INFO:
data = smb.SMBQueryFsSizeInfo()
return data.getData()
elif level == smb.SMB_QUERY_FS_DEVICE_INFO or level == smb2.SMB2_FILESYSTEM_DEVICE_INFO:
data = smb.SMBQueryFsDeviceInfo()
data['DeviceType'] = smb.FILE_DEVICE_DISK
return data.getData()
elif level == smb.FILE_FS_FULL_SIZE_INFORMATION:
data = smb.SMBFileFsFullSizeInformation()
return data.getData()
elif level == smb.FILE_FS_SIZE_INFORMATION:
data = smb.FileFsSizeInformation()
return data.getData()
else:
return None
def findFirst2(path, fileName, level, searchAttributes, pktFlags=smb.SMB.FLAGS2_UNICODE, isSMB2=False):
# TODO: Depending on the level, this could be done much simpler
# Let's choose the right encoding depending on the request
if pktFlags & smb.SMB.FLAGS2_UNICODE:
encoding = 'utf-16le'
else:
encoding = 'ascii'
fileName = normalize_path(fileName)
pathName = os.path.join(path, fileName)
if not isInFileJail(path, fileName):
LOG.error("Path not in current working directory")
return [], 0, STATUS_OBJECT_PATH_SYNTAX_BAD
files = []
if pathName.find('*') == -1 and pathName.find('?') == -1:
# No search patterns
pattern = ''
else:
pattern = os.path.basename(pathName)
dirName = os.path.dirname(pathName)
# Always add . and .. Not that important for Windows, but Samba whines if
# not present (for * search only)
if pattern == '*':
files.append(os.path.join(dirName, '.'))
files.append(os.path.join(dirName, '..'))
if pattern != '':
for file in os.listdir(dirName):
if fnmatch.fnmatch(file.lower(), pattern.lower()):
entry = os.path.join(dirName, file)
if os.path.isdir(entry):
if searchAttributes & smb.ATTR_DIRECTORY:
files.append(entry)
else:
files.append(entry)
else:
if os.path.exists(pathName):
files.append(pathName)
searchResult = []
searchCount = len(files)
errorCode = STATUS_SUCCESS
for i in files:
if level == smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_BOTH_DIRECTORY_INFO:
item = smb.SMBFindFileBothDirectoryInfo(flags=pktFlags)
elif level == smb.SMB_FIND_FILE_DIRECTORY_INFO or level == smb2.SMB2_FILE_DIRECTORY_INFO:
item = smb.SMBFindFileDirectoryInfo(flags=pktFlags)
elif level == smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO or level == smb2.SMB2_FULL_DIRECTORY_INFO:
item = smb.SMBFindFileFullDirectoryInfo(flags=pktFlags)
elif level == smb.SMB_FIND_INFO_STANDARD:
item = smb.SMBFindInfoStandard(flags=pktFlags)
elif level == smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_FULL_DIRECTORY_INFO:
item = smb.SMBFindFileIdFullDirectoryInfo(flags=pktFlags)
elif level == smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO:
item = smb.SMBFindFileIdBothDirectoryInfo(flags=pktFlags)
elif level == smb.SMB_FIND_FILE_NAMES_INFO or level == smb2.SMB2_FILE_NAMES_INFO:
item = smb.SMBFindFileNamesInfo(flags=pktFlags)
else:
LOG.error("Wrong level %d!" % level)
return searchResult, searchCount, STATUS_NOT_SUPPORTED
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(i)
if os.path.isdir(i):
item['ExtFileAttributes'] = smb.ATTR_DIRECTORY
else:
item['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE
item['FileName'] = os.path.basename(i).encode(encoding)
if level in [smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO, smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO,
smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO]:
item['EaSize'] = 0
item['EndOfFile'] = size
item['AllocationSize'] = size
item['CreationTime'] = getFileTime(ctime)
item['LastAccessTime'] = getFileTime(atime)
item['LastWriteTime'] = getFileTime(mtime)
item['LastChangeTime'] = getFileTime(mtime)
item['ShortName'] = '\x00' * 24
item['FileName'] = os.path.basename(i).encode(encoding)
padLen = (8 - (len(item) % 8)) % 8
item['NextEntryOffset'] = len(item) + padLen
elif level in [smb.SMB_FIND_FILE_DIRECTORY_INFO, smb2.SMB2_FILE_DIRECTORY_INFO]:
item['EndOfFile'] = size
item['AllocationSize'] = size
item['CreationTime'] = getFileTime(ctime)
item['LastAccessTime'] = getFileTime(atime)
item['LastWriteTime'] = getFileTime(mtime)
item['LastChangeTime'] = getFileTime(mtime)
item['FileName'] = os.path.basename(i).encode(encoding)
padLen = (8 - (len(item) % 8)) % 8
item['NextEntryOffset'] = len(item) + padLen
elif level in [smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO, smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO,
smb2.SMB2_FULL_DIRECTORY_INFO, smb2.SMB2_FILE_ID_FULL_DIRECTORY_INFO]:
item['EaSize'] = 0
item['EndOfFile'] = size
item['AllocationSize'] = size
item['CreationTime'] = getFileTime(ctime)
item['LastAccessTime'] = getFileTime(atime)
item['LastWriteTime'] = getFileTime(mtime)
item['LastChangeTime'] = getFileTime(mtime)
padLen = (8 - (len(item) % 8)) % 8
item['NextEntryOffset'] = len(item) + padLen
elif level == smb.SMB_FIND_INFO_STANDARD:
item['EaSize'] = size
item['CreationDate'] = getSMBDate(ctime)
item['CreationTime'] = getSMBTime(ctime)
item['LastAccessDate'] = getSMBDate(atime)
item['LastAccessTime'] = getSMBTime(atime)
item['LastWriteDate'] = getSMBDate(mtime)
item['LastWriteTime'] = getSMBTime(mtime)
searchResult.append(item)
# No more files
if (level >= smb.SMB_FIND_FILE_DIRECTORY_INFO or isSMB2 is True) and searchCount > 0:
searchResult[-1]['NextEntryOffset'] = 0
return searchResult, searchCount, errorCode
def queryFileInformation(path, filename, level):
# print "queryFileInfo path: %s, filename: %s, level:0x%x" % (path,filename,level)
return queryPathInformation(path, filename, level)
def queryPathInformation(path, filename, level):
# TODO: Depending on the level, this could be done much simpler
try:
errorCode = 0
fileName = normalize_path(filename, path)
pathName = os.path.join(path, fileName)
if not isInFileJail(path, fileName):
LOG.error("Path not in current working directory")
return None, STATUS_OBJECT_PATH_SYNTAX_BAD
if os.path.exists(pathName):
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName)
if level == smb.SMB_QUERY_FILE_BASIC_INFO:
infoRecord = smb.SMBQueryFileBasicInfo()
infoRecord['CreationTime'] = getFileTime(ctime)
infoRecord['LastAccessTime'] = getFileTime(atime)
infoRecord['LastWriteTime'] = getFileTime(mtime)
infoRecord['LastChangeTime'] = getFileTime(mtime)
if os.path.isdir(pathName):
infoRecord['ExtFileAttributes'] = smb.ATTR_DIRECTORY
else:
infoRecord['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE
elif level == smb.SMB_QUERY_FILE_STANDARD_INFO or level == smb2.SMB2_FILE_STANDARD_INFO:
infoRecord = smb.SMBQueryFileStandardInfo()
infoRecord['AllocationSize'] = size
infoRecord['EndOfFile'] = size
if os.path.isdir(pathName):
infoRecord['Directory'] = 1
else:
infoRecord['Directory'] = 0
elif level == smb.SMB_QUERY_FILE_ALL_INFO:
infoRecord = smb.SMBQueryFileAllInfo()
infoRecord['CreationTime'] = getFileTime(ctime)
infoRecord['LastAccessTime'] = getFileTime(atime)
infoRecord['LastWriteTime'] = getFileTime(mtime)
infoRecord['LastChangeTime'] = getFileTime(mtime)
if os.path.isdir(pathName):
infoRecord['ExtFileAttributes'] = smb.ATTR_DIRECTORY
else:
infoRecord['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE
infoRecord['AllocationSize'] = size
infoRecord['EndOfFile'] = size
if os.path.isdir(pathName):
infoRecord['Directory'] = 1
else:
infoRecord['Directory'] = 0
infoRecord['FileName'] = filename.encode('utf-16le')
elif level == smb2.SMB2_FILE_ALL_INFO:
infoRecord = smb2.FILE_ALL_INFORMATION()
infoRecord['BasicInformation'] = smb2.FILE_BASIC_INFORMATION()
infoRecord['StandardInformation'] = smb2.FILE_STANDARD_INFORMATION()
infoRecord['InternalInformation'] = smb2.FILE_INTERNAL_INFORMATION()
infoRecord['EaInformation'] = smb2.FILE_EA_INFORMATION()
infoRecord['AccessInformation'] = smb2.FILE_ACCESS_INFORMATION()
infoRecord['PositionInformation'] = smb2.FILE_POSITION_INFORMATION()
infoRecord['ModeInformation'] = smb2.FILE_MODE_INFORMATION()
infoRecord['AlignmentInformation'] = smb2.FILE_ALIGNMENT_INFORMATION()
infoRecord['NameInformation'] = smb2.FILE_NAME_INFORMATION()
infoRecord['BasicInformation']['CreationTime'] = getFileTime(ctime)
infoRecord['BasicInformation']['LastAccessTime'] = getFileTime(atime)
infoRecord['BasicInformation']['LastWriteTime'] = getFileTime(mtime)
infoRecord['BasicInformation']['ChangeTime'] = getFileTime(mtime)
if os.path.isdir(pathName):
infoRecord['BasicInformation']['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY
infoRecord['StandardInformation']['Directory'] = 1
infoRecord['EaInformation']['EaSize'] = smb.ATTR_DIRECTORY
else:
infoRecord['BasicInformation']['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_NORMAL | smb.SMB_FILE_ATTRIBUTE_ARCHIVE
infoRecord['StandardInformation']['Directory'] = 0
infoRecord['EaInformation']['EaSize'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE
infoRecord['StandardInformation']['AllocationSize'] = size
infoRecord['StandardInformation']['EndOfFile'] = size
infoRecord['StandardInformation']['NumberOfLinks'] = nlink
infoRecord['StandardInformation']['DeletePending'] = 0
infoRecord['InternalInformation']['IndexNumber'] = ino
infoRecord['AccessInformation']['AccessFlags'] = 0 #
infoRecord['PositionInformation']['CurrentByteOffset'] = 0 #
infoRecord['ModeInformation']['mode'] = mode
infoRecord['AlignmentInformation']['AlignmentRequirement'] = 0 #
infoRecord['NameInformation']['FileName'] = fileName
infoRecord['NameInformation']['FileNameLength'] = len(fileName)
elif level == smb2.SMB2_FILE_NETWORK_OPEN_INFO:
infoRecord = smb.SMBFileNetworkOpenInfo()
infoRecord['CreationTime'] = getFileTime(ctime)
infoRecord['LastAccessTime'] = getFileTime(atime)
infoRecord['LastWriteTime'] = getFileTime(mtime)
infoRecord['ChangeTime'] = getFileTime(mtime)
infoRecord['AllocationSize'] = size
infoRecord['EndOfFile'] = size
if os.path.isdir(pathName):
infoRecord['FileAttributes'] = smb.ATTR_DIRECTORY
else:
infoRecord['FileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE
elif level == smb.SMB_QUERY_FILE_EA_INFO or level == smb2.SMB2_FILE_EA_INFO:
infoRecord = smb.SMBQueryFileEaInfo()
elif level == smb2.SMB2_FILE_STREAM_INFO:
infoRecord = smb.SMBFileStreamInformation()
else:
LOG.error('Unknown level for query path info! 0x%x' % level)
# UNSUPPORTED
return None, STATUS_NOT_SUPPORTED
return infoRecord, errorCode
else:
# NOT FOUND
return None, STATUS_OBJECT_NAME_NOT_FOUND
except Exception as e:
LOG.error('queryPathInfo: %s' % e)
raise
def queryDiskInformation(path):
# TODO: Do something useful here :)
# For now we just return fake values
totalUnits = 65535
freeUnits = 65535
return totalUnits, freeUnits
# Here we implement the NT transaction handlers
class NTTRANSCommands:
def default(self, connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
pass
# Here we implement the NT transaction handlers
class TRANSCommands:
@staticmethod
def lanMan(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
# Minimal [MS-RAP] implementation, just to return the shares
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = STATUS_SUCCESS
if struct.unpack('<H', parameters[:2])[0] == 0:
# NetShareEnum Request
netShareEnum = smb.SMBNetShareEnum(parameters)
if netShareEnum['InfoLevel'] == 1:
shares = getShares(connId, smbServer)
respParameters = smb.SMBNetShareEnumResponse()
respParameters['EntriesReturned'] = len(shares)
respParameters['EntriesAvailable'] = len(shares)
tailData = ''
for i in shares:
# NetShareInfo1 len == 20
entry = smb.NetShareInfo1()
entry['NetworkName'] = i + '\x00' * (13 - len(i))
entry['Type'] = int(shares[i]['share type'])
# (beto) If offset == 0 it crashes explorer.exe on windows 7
entry['RemarkOffsetLow'] = 20 * len(shares) + len(tailData)
respData += entry.getData()
if 'comment' in shares[i]:
tailData += shares[i]['comment'] + '\x00'
else:
tailData += '\x00'
respData += tailData
else:
# We don't support other info levels
errorCode = STATUS_NOT_SUPPORTED
elif struct.unpack('<H', parameters[:2])[0] == 13:
# NetrServerGetInfo Request
respParameters = smb.SMBNetServerGetInfoResponse()
netServerInfo = smb.SMBNetServerInfo1()
netServerInfo['ServerName'] = smbServer.getServerName()
respData = netServerInfo.getData()
respParameters['TotalBytesAvailable'] = len(respData)
elif struct.unpack('<H', parameters[:2])[0] == 1:
# NetrShareGetInfo Request
request = smb.SMBNetShareGetInfo(parameters)
respParameters = smb.SMBNetShareGetInfoResponse()
shares = getShares(connId, smbServer)
share = shares[request['ShareName'].upper()]
shareInfo = smb.NetShareInfo1()
shareInfo['NetworkName'] = request['ShareName'].upper() + '\x00'
shareInfo['Type'] = int(share['share type'])
respData = shareInfo.getData()
if 'comment' in share:
shareInfo['RemarkOffsetLow'] = len(respData)
respData += share['comment'] + '\x00'
respParameters['TotalBytesAvailable'] = len(respData)
else:
# We don't know how to handle anything else
errorCode = STATUS_NOT_SUPPORTED
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def transactNamedPipe(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = STATUS_SUCCESS
SMBCommand = smb.SMBCommand(recvPacket['Data'][0])
transParameters = smb.SMBTransaction_Parameters(SMBCommand['Parameters'])
# Extract the FID
fid = struct.unpack('<H', transParameters['Setup'][2:])[0]
if fid in connData['OpenedFiles']:
fileHandle = connData['OpenedFiles'][fid]['FileHandle']
if fileHandle != PIPE_FILE_DESCRIPTOR:
os.write(fileHandle, data)
respData = os.read(fileHandle, data)
else:
sock = connData['OpenedFiles'][fid]['Socket']
sock.send(data)
respData = sock.recv(maxDataCount)
else:
errorCode = STATUS_INVALID_HANDLE
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
# Here we implement the transaction2 handlers
class TRANS2Commands:
# All these commands return setup, parameters, data, errorCode
@staticmethod
def setPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = STATUS_SUCCESS
setPathInfoParameters = smb.SMBSetPathInformation_Parameters(flags=recvPacket['Flags2'], data=parameters)
if recvPacket['Tid'] in connData['ConnectedShares']:
path = connData['ConnectedShares'][recvPacket['Tid']]['path']
fileName = normalize_path(decodeSMBString(recvPacket['Flags2'], setPathInfoParameters['FileName']), path)
pathName = os.path.join(path, fileName)
if isInFileJail(path, fileName):
smbServer.log("Path not in current working directory")
errorCode = STATUS_OBJECT_PATH_SYNTAX_BAD
elif os.path.exists(pathName):
informationLevel = setPathInfoParameters['InformationLevel']
if informationLevel == smb.SMB_SET_FILE_BASIC_INFO:
infoRecord = smb.SMBSetFileBasicInfo(data)
# Creation time won't be set, the other ones we play with.
atime = infoRecord['LastAccessTime']
if atime == 0:
atime = -1
else:
atime = getUnixTime(atime)
mtime = infoRecord['LastWriteTime']
if mtime == 0:
mtime = -1
else:
mtime = getUnixTime(mtime)
if mtime != -1 or atime != -1:
os.utime(pathName, (atime, mtime))
else:
smbServer.log('Unknown level for set path info! 0x%x' % setPathInfoParameters['InformationLevel'],
logging.ERROR)
# UNSUPPORTED
errorCode = STATUS_NOT_SUPPORTED
else:
errorCode = STATUS_OBJECT_NAME_NOT_FOUND
if errorCode == STATUS_SUCCESS:
respParameters = smb.SMBSetPathInformationResponse_Parameters()
else:
errorCode = STATUS_SMB_BAD_TID
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def setFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = STATUS_SUCCESS
setFileInfoParameters = smb.SMBSetFileInformation_Parameters(parameters)
if recvPacket['Tid'] in connData['ConnectedShares']:
if setFileInfoParameters['FID'] in connData['OpenedFiles']:
fileName = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileName']
informationLevel = setFileInfoParameters['InformationLevel']
if informationLevel == smb.SMB_SET_FILE_DISPOSITION_INFO:
infoRecord = smb.SMBSetFileDispositionInfo(parameters)
if infoRecord['DeletePending'] > 0:
# Mark this file for removal after closed
connData['OpenedFiles'][setFileInfoParameters['FID']]['DeleteOnClose'] = True
respParameters = smb.SMBSetFileInformationResponse_Parameters()
elif informationLevel == smb.SMB_SET_FILE_BASIC_INFO:
infoRecord = smb.SMBSetFileBasicInfo(data)
# Creation time won't be set, the other ones we play with.
atime = infoRecord['LastAccessTime']
if atime == 0:
atime = -1
else:
atime = getUnixTime(atime)
mtime = infoRecord['LastWriteTime']
if mtime == 0:
mtime = -1
else:
mtime = getUnixTime(mtime)
os.utime(fileName, (atime, mtime))
elif informationLevel == smb.SMB_SET_FILE_END_OF_FILE_INFO:
fileHandle = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileHandle']
infoRecord = smb.SMBSetFileEndOfFileInfo(data)
if infoRecord['EndOfFile'] > 0:
os.lseek(fileHandle, infoRecord['EndOfFile'] - 1, 0)
os.write(fileHandle, b'\x00')
else:
smbServer.log('Unknown level for set file info! 0x%x' % setFileInfoParameters['InformationLevel'],
logging.ERROR)
# UNSUPPORTED
errorCode = STATUS_NOT_SUPPORTED
else:
errorCode = STATUS_NO_SUCH_FILE
if errorCode == STATUS_SUCCESS:
respParameters = smb.SMBSetFileInformationResponse_Parameters()
else:
errorCode = STATUS_SMB_BAD_TID
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def queryFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
queryFileInfoParameters = smb.SMBQueryFileInformation_Parameters(parameters)
if recvPacket['Tid'] in connData['ConnectedShares']:
if queryFileInfoParameters['FID'] in connData['OpenedFiles']:
pathName = connData['OpenedFiles'][queryFileInfoParameters['FID']]['FileName']
infoRecord, errorCode = queryFileInformation(os.path.dirname(pathName), os.path.basename(pathName),
queryFileInfoParameters['InformationLevel'])
if infoRecord is not None:
respParameters = smb.SMBQueryFileInformationResponse_Parameters()
respData = infoRecord
else:
errorCode = STATUS_INVALID_HANDLE
else:
errorCode = STATUS_SMB_BAD_TID
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def queryPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = 0
queryPathInfoParameters = smb.SMBQueryPathInformation_Parameters(flags=recvPacket['Flags2'], data=parameters)
if recvPacket['Tid'] in connData['ConnectedShares']:
path = connData['ConnectedShares'][recvPacket['Tid']]['path']
try:
infoRecord, errorCode = queryPathInformation(path, decodeSMBString(recvPacket['Flags2'],
queryPathInfoParameters['FileName']),
queryPathInfoParameters['InformationLevel'])
except Exception as e:
smbServer.log("queryPathInformation: %s" % e, logging.ERROR)
if infoRecord is not None:
respParameters = smb.SMBQueryPathInformationResponse_Parameters()
respData = infoRecord
else:
errorCode = STATUS_SMB_BAD_TID
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def queryFsInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount=0):
connData = smbServer.getConnectionData(connId)
errorCode = 0
# Get the Tid associated
if recvPacket['Tid'] in connData['ConnectedShares']:
data = queryFsInformation(connData['ConnectedShares'][recvPacket['Tid']]['path'], '',
struct.unpack('<H', parameters)[0], pktFlags=recvPacket['Flags2'])
smbServer.setConnectionData(connId, connData)
return b'', b'', data, errorCode
@staticmethod
def findNext2(connId, smbServer, recvPacket, parameters, data, maxDataCount):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
errorCode = STATUS_SUCCESS
findNext2Parameters = smb.SMBFindNext2_Parameters(flags=recvPacket['Flags2'], data=parameters)
sid = findNext2Parameters['SID']
if recvPacket['Tid'] in connData['ConnectedShares']:
if sid in connData['SIDs']:
searchResult = connData['SIDs'][sid]
respParameters = smb.SMBFindNext2Response_Parameters()
endOfSearch = 1
searchCount = 1
totalData = 0
for i in enumerate(searchResult):
data = i[1].getData()
lenData = len(data)
if (totalData + lenData) >= maxDataCount or (i[0] + 1) >= findNext2Parameters['SearchCount']:
# We gotta stop here and continue on a find_next2
endOfSearch = 0
connData['SIDs'][sid] = searchResult[i[0]:]
respParameters['LastNameOffset'] = totalData
break
else:
searchCount += 1
respData += data
totalData += lenData
# Have we reached the end of the search or still stuff to send?
if endOfSearch > 0:
# Let's remove the SID from our ConnData
del (connData['SIDs'][sid])
respParameters['EndOfSearch'] = endOfSearch
respParameters['SearchCount'] = searchCount
else:
errorCode = STATUS_INVALID_HANDLE
else:
errorCode = STATUS_SMB_BAD_TID
smbServer.setConnectionData(connId, connData)
return respSetup, respParameters, respData, errorCode
@staticmethod
def findFirst2(connId, smbServer, recvPacket, parameters, data, maxDataCount):
connData = smbServer.getConnectionData(connId)
respSetup = b''
respParameters = b''
respData = b''
findFirst2Parameters = smb.SMBFindFirst2_Parameters(recvPacket['Flags2'], data=parameters)
if recvPacket['Tid'] in connData['ConnectedShares']:
path = connData['ConnectedShares'][recvPacket['Tid']]['path']
searchResult, searchCount, errorCode = findFirst2(path,
decodeSMBString(recvPacket['Flags2'],
findFirst2Parameters['FileName']),
findFirst2Parameters['InformationLevel'],
findFirst2Parameters['SearchAttributes'],
pktFlags=recvPacket['Flags2'])
if searchCount > 0:
respParameters = smb.SMBFindFirst2Response_Parameters()
endOfSearch = 1
sid = 0x80 # default SID
searchCount = 0
totalData = 0
for i in enumerate(searchResult):
# i[1].dump()
data = i[1].getData()
lenData = len(data)
if (totalData + lenData) >= maxDataCount or (i[0] + 1) > findFirst2Parameters['SearchCount']:
# We gotta stop here and continue on a find_next2
endOfSearch = 0