-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmbclient.py
More file actions
1005 lines (874 loc) · 35.9 KB
/
smbclient.py
File metadata and controls
1005 lines (874 loc) · 35.9 KB
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.
#
# Copyright Fortra, LLC and its affiliated companies
#
# 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.
#
# Description:
# Mini shell using some of the SMB funcionality of the library but cooler.
#
# Author:
# Alberto Solino (@agsolino)
#
# Reference for:
# SMB DCE/RPC
#
from __future__ import division
from __future__ import print_function
from io import BytesIO
import sys
import time
import cmd
import os
import ntpath
import string
import random
from six import PY2
from impacket.dcerpc.v5 import samr, transport, srvs
from impacket.dcerpc.v5.dtypes import NULL
from impacket import LOG
from impacket.smbconnection import SMBConnection, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB_DIALECT, SessionError, \
FILE_READ_DATA, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE
from impacket.smb3structs import FILE_DIRECTORY_FILE, FILE_LIST_DIRECTORY
from impacket.acl import SMBFileACL
import charset_normalizer as chardet
from impacket import version
import logging
import argparse
from impacket.examples import logger
from impacket.examples.utils import parse_target
class MiniImpacketShell(cmd.Cmd):
def __init__(self, smbClient, tcpShell=None, outputfile=None, debug=False):
# If the tcpShell parameter is passed (used in ntlmrelayx),
# all input and output is redirected to a tcp socket
# instead of to stdin / stdout
if tcpShell is not None:
cmd.Cmd.__init__(self, stdin=tcpShell.stdin, stdout=tcpShell.stdout)
sys.stdout = tcpShell.stdout
sys.stdin = tcpShell.stdin
sys.stderr = tcpShell.stdout
self.use_rawinput = False
self.shell = tcpShell
else:
cmd.Cmd.__init__(self)
self.shell = None
self.smb = smbClient
self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey, self.TGT, self.TGS = smbClient.getCredentials()
self.tid = None
self.intro = 'Type help for list of commands'
self.pwd = ''
self.share = None
self.loggedIn = True
self.last_output = None
self.completion = []
self.outputfile = outputfile
self.debug = debug
self.remoteIP = self.smb.getRemoteHost()
self.prompt = f'{self.remoteIP}: # '
def emptyline(self):
pass
def precmd(self, line):
# switch to unicode
if self.outputfile is not None:
f = open(self.outputfile, 'a')
f.write('> ' + line + "\n")
f.close()
if PY2:
return line.decode('utf-8')
return line
def onecmd(self, s):
retVal = False
try:
retVal = cmd.Cmd.onecmd(self, s)
except Exception as e:
LOG.error(e)
LOG.debug('Exception info', exc_info=True)
return retVal
def do_exit(self, line):
if self.shell is not None:
self.shell.close()
return True
def do_shell(self, line):
output = os.popen(line).read()
print(output)
self.last_output = output
def do_help(self, line):
print("""
open {host,port=445} - opens a SMB connection against the target host/port
reconnect - reconnect connection, useful for broken pipes & interrupted sessions
login {domain/username,passwd} - logs into the current SMB connection, no parameters for NULL connection. If no password specified, it'll be prompted
kerberos_login {domain/username,passwd} - logs into the current SMB connection using Kerberos. If no password specified, it'll be prompted. Use the DNS resolvable domain name
login_hash {domain/username,lmhash:nthash} - logs into the current SMB connection using the password hashes
logoff - logs off
shares - list available shares
use {sharename} - connect to an specific share
cd {path} - changes the current directory to {path}
lcd {path} - changes the current local directory to {path}
pwd - shows current remote directory
password - changes the user password, the new password will be prompted for input
ls {wildcard} - lists all the files in the current directory
lls {dirname} - lists all the files on the local filesystem.
tree {filepath} - recursively lists all files in folder and sub folders
rm {file} - removes the selected file
mkdir {dirname} - creates the directory under the current path
rmdir {dirname} - removes the directory under the current path
put {filename} - uploads the filename into the current path
get {filename} - downloads the filename from the current path
mget {mask} - downloads all files from the current directory matching the provided mask
rget {mask} - recursively downloads all files from the current directory and subdirectories matching the provided mask
cat {filename} - reads the filename from the current path
mount {target,path} - creates a mount point from {path} to {target} (admin required)
umount {path} - removes the mount point at {path} without deleting the directory (admin required)
list_snapshots {path} - lists the vss snapshots for the specified path
info - returns NetrServerInfo main results
who - returns the sessions currently connected at the target host (admin required)
acl {filename,action,permissions,user/group} - displays or modifies file ACLs
close - closes the current SMB Session
exit - terminates the server process (and this session)
""")
def do_password(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
from getpass import getpass
newPassword = getpass("New Password:")
rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename=r'\samr', smb_connection=self.smb)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(samr.MSRPC_UUID_SAMR)
samr.hSamrUnicodeChangePasswordUser2(dce, '\x00', self.username, self.password, newPassword, self.lmhash,
self.nthash)
self.password = newPassword
self.lmhash = None
self.nthash = None
def do_open(self, line):
l = line.split(' ')
port = 445
if len(l) > 0:
host = l[0]
if len(l) > 1:
port = int(l[1])
if port == 139:
self.smb = SMBConnection('*SMBSERVER', host, sess_port=port)
else:
self.smb = SMBConnection(host, host, sess_port=port)
dialect = self.smb.getDialect()
if dialect == SMB_DIALECT:
LOG.info("SMBv1 dialect used")
elif dialect == SMB2_DIALECT_002:
LOG.info("SMBv2.0 dialect used")
elif dialect == SMB2_DIALECT_21:
LOG.info("SMBv2.1 dialect used")
else:
LOG.info("SMBv3.0 dialect used")
self.share = None
self.tid = None
self.pwd = ''
self.loggedIn = False
self.password = None
self.lmhash = None
self.nthash = None
self.username = None
def do_reconnect(self, line):
if self.smb:
self.smb.reconnect()
else:
LOG.warning("Not reconnecting a closed connection.")
def do_login(self, line):
if self.smb is None:
LOG.error("No connection open")
return
l = line.split(' ')
username = ''
password = ''
domain = ''
if len(l) > 0:
username = l[0]
if len(l) > 1:
password = l[1]
if username.find('/') > 0:
domain, username = username.split('/')
if password == '' and username != '':
from getpass import getpass
password = getpass("Password:")
self.smb.login(username, password, domain=domain)
self.password = password
self.username = username
if self.smb.isGuestSession() > 0:
LOG.info("GUEST Session Granted")
else:
LOG.info("USER Session Granted")
self.loggedIn = True
def do_kerberos_login(self, line):
if self.smb is None:
LOG.error("No connection open")
return
l = line.split(' ')
username = ''
password = ''
domain = ''
if len(l) > 0:
username = l[0]
if len(l) > 1:
password = l[1]
if username.find('/') > 0:
domain, username = username.split('/')
if domain == '':
LOG.error("Domain must be specified for Kerberos login")
return
if password == '' and username != '':
from getpass import getpass
password = getpass("Password:")
self.smb.kerberosLogin(username, password, domain=domain)
self.password = password
self.username = username
if self.smb.isGuestSession() > 0:
LOG.info("GUEST Session Granted")
else:
LOG.info("USER Session Granted")
self.loggedIn = True
def do_login_hash(self, line):
if self.smb is None:
LOG.error("No connection open")
return
l = line.split(' ')
domain = ''
if len(l) > 0:
username = l[0]
if len(l) > 1:
hashes = l[1]
else:
LOG.error("Hashes needed. Format is lmhash:nthash")
return
if username.find('/') > 0:
domain, username = username.split('/')
lmhash, nthash = hashes.split(':')
self.smb.login(username, '', domain, lmhash=lmhash, nthash=nthash)
self.username = username
self.lmhash = lmhash
self.nthash = nthash
if self.smb.isGuestSession() > 0:
LOG.info("GUEST Session Granted")
else:
LOG.info("USER Session Granted")
self.loggedIn = True
def do_logoff(self, line):
if self.smb is None:
LOG.error("No connection open")
return
self.smb.logoff()
del self.smb
self.share = None
self.smb = None
self.tid = None
self.pwd = ''
self.loggedIn = False
self.password = None
self.lmhash = None
self.nthash = None
self.username = None
def do_info(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename=r'\srvsvc', smb_connection=self.smb)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(srvs.MSRPC_UUID_SRVS)
resp = srvs.hNetrServerGetInfo(dce, 102)
print("Version Major: %d" % resp['InfoStruct']['ServerInfo102']['sv102_version_major'])
print("Version Minor: %d" % resp['InfoStruct']['ServerInfo102']['sv102_version_minor'])
print("Server Name: %s" % resp['InfoStruct']['ServerInfo102']['sv102_name'])
print("Server Comment: %s" % resp['InfoStruct']['ServerInfo102']['sv102_comment'])
print("Server UserPath: %s" % resp['InfoStruct']['ServerInfo102']['sv102_userpath'])
print("Simultaneous Users: %d" % resp['InfoStruct']['ServerInfo102']['sv102_users'])
def do_who(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename=r'\srvsvc', smb_connection=self.smb)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(srvs.MSRPC_UUID_SRVS)
resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10)
for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']:
print("host: %15s, user: %5s, active: %5d, idle: %5d" % (
session['sesi10_cname'][:-1], session['sesi10_username'][:-1], session['sesi10_time'],
session['sesi10_idle_time']))
def _resolve_share_type(self, type_int):
attributes = []
if type_int & srvs.STYPE_SPECIAL:
attributes.append("SPECIAL")
type_int ^= srvs.STYPE_SPECIAL
if type_int & srvs.STYPE_TEMPORARY:
attributes.append("TEMP")
type_int ^= srvs.STYPE_TEMPORARY
type_str = "UNKNOWN"
if type_int == srvs.STYPE_DISKTREE:
type_str = "DISK"
elif type_int == srvs.STYPE_PRINTQ:
type_str = "PRINT"
elif type_int == srvs.STYPE_DEVICE:
type_str = "DEVICE"
elif type_int == srvs.STYPE_IPC:
type_str = "IPC"
if attributes:
return f"{type_str} ({','.join(attributes)})"
return type_str
def gen_random_string(self, length):
# Choose from lowercase, uppercase, and digits
return ''.join(random.choices(string.ascii_letters, k=length))
def get_share_access(self, share_name):
read = False
write_dir = False
write_file = False
write_check = True
try:
self.smb.listPath(share_name, "*")
read = True
except SessionError as e:
error = str(e)
if self.debug:
print(f"Error checking READ access on share {share_name}: {error}")
except (NetBIOSError, UnicodeEncodeError) as e:
write_check = False
share_info["access"].append("UNKNOWN (try '--no-smbv1')")
error = str(e)
if self.debug:
print(f"Error checking READ access on share {share_name}: {error}. This exception always caused by special character in share name with SMBv1")
print(f"Skipping WRITE permission check on share {share_name}")
if write_check:
temp_dir = ntpath.normpath("\\" + self.gen_random_string(10))
temp_file = ntpath.normpath("\\" + self.gen_random_string(10) + ".txt")
try:
self.smb.createDirectory(share_name, temp_dir)
write_dir = True
try:
self.smb.deleteDirectory(share_name, temp_dir)
except SessionError as e:
error = str(e)
if error == "STATUS_OBJECT_NAME_NOT_FOUND":
pass
else:
if self.debug:
print(f"Error DELETING created temp dir {temp_dir} on share {share_name}: {error}")
except SessionError as e:
error = str(e)
if self.debug:
print(f"Error checking WRITE access with DIR creation on share {share_name}: {error}")
try:
tid = self.smb.connectTree(share_name)
fid = self.smb.createFile(tid, temp_file, desiredAccess=FILE_SHARE_WRITE, shareMode=FILE_SHARE_DELETE)
self.smb.closeFile(tid, fid)
write_file = True
try:
self.smb.deleteFile(share_name, temp_file)
except SessionError as e:
error = str(e)
if error == "STATUS_OBJECT_NAME_NOT_FOUND":
pass
else:
if self.debug:
print(f"Error DELETING created temp file {temp_file} on share {share_name}")
except SessionError as e:
error = str(e)
if self.debug:
print(f"Error checking WRITE access with FILE creation on share {share_name}: {error}")
respon = ''
if read:
respon = 'READ'
if write_dir or write_file:
respon += ',WRITE'
return respon
def do_shares(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
resp = self.smb.listShares()
fmt = "{:<25} {:<15} {:<11} {}"
print(fmt.format("Share Name", "Type", "Access", "Comment"))
print("-" * 70)
if self.outputfile is not None:
f = open(self.outputfile, 'a')
for i in range(len(resp)):
share_name = resp[i]['shi1_netname'][:-1]
share_remark = resp[i]['shi1_remark'][:-1]
share_type_int = resp[i]['shi1_type']
share_type = self._resolve_share_type(share_type_int)
share_access = self.get_share_access(share_name)
if self.outputfile:
f.write(f"{share_name}|{share_type}|{share_access}|{share_remark}\n")
print(fmt.format(share_name, share_type, share_access, share_remark))
if self.outputfile:
f.close()
def do_use(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
self.share = line
self.tid = self.smb.connectTree(line)
self.pwd = '\\'
self.do_ls('', False)
self.prompt = f'{self.remoteIP}:{self.share} # '
def complete_cd(self, text, line, begidx, endidx):
return self.complete_get(text, line, begidx, endidx, include=2)
def do_cd(self, line):
if self.tid is None:
LOG.error("No share selected")
return
p = line.replace('/', '\\')
oldpwd = self.pwd
if p[0] == '\\':
self.pwd = line
else:
self.pwd = ntpath.join(self.pwd, line)
self.pwd = ntpath.normpath(self.pwd)
# Let's try to open the directory to see if it's valid
try:
fid = self.smb.openFile(self.tid, self.pwd, creationOption=FILE_DIRECTORY_FILE,
desiredAccess=FILE_READ_DATA |
FILE_LIST_DIRECTORY, shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE)
self.smb.closeFile(self.tid, fid)
except SessionError:
self.pwd = oldpwd
raise
self.prompt = f'{self.remoteIP}:{self.share}{self.pwd.replace('/','\\')} # '
def do_lcd(self, s):
print(s)
if s == '':
print(os.getcwd())
else:
os.chdir(s)
def do_pwd(self, line):
if self.loggedIn is False:
LOG.error("Not logged in")
return
print(self.pwd.replace("\\", "/"))
if self.outputfile is not None:
f = open(self.outputfile, 'a')
f.write(self.pwd.replace("\\", "/"))
f.close()
def do_ls(self, wildcard, display=True):
if self.loggedIn is False:
LOG.error("Not logged in")
return
if self.tid is None:
LOG.error("No share selected")
return
if wildcard == '':
pwd = ntpath.join(self.pwd, '*')
else:
pwd = ntpath.join(self.pwd, wildcard)
self.completion = []
pwd = pwd.replace('/', '\\')
pwd = ntpath.normpath(pwd)
if self.outputfile is not None:
of = open(self.outputfile, 'a')
for f in self.smb.listPath(self.share, pwd):
if display is True:
if self.outputfile:
of.write("%crw-rw-rw- %10d %s %s" % (
'd' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())),
f.get_longname()) + "\n")
print("%crw-rw-rw- %10d %s %s" % (
'd' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())),
f.get_longname()))
self.completion.append((f.get_longname(), f.is_directory()))
if self.outputfile:
of.close()
def do_lls(self, currentDir):
if currentDir == "":
currentDir = "./"
else:
pass
for LINE in os.listdir(currentDir):
print(LINE)
def do_listFiles(self, share, ip):
retList = []
retFiles = []
retInt = 0
try:
for LINE in self.smb.listPath(self.share, ip):
if (LINE.get_longname() == "." or LINE.get_longname() == ".."):
pass
else:
retInt = retInt + 1
print(ip.strip("*").replace("//", "/") + LINE.get_longname())
if (LINE.is_directory()):
retval = ip.strip("*").replace("//", "/") + LINE.get_longname()
retList.append(retval)
else:
retval = ip.strip("*").replace("//", "/") + LINE.get_longname()
retFiles.append(retval)
except:
pass
return retList, retFiles, retInt
def do_tree(self, filepath):
folderList = []
retList = []
totalFilesRead = 0
if self.loggedIn is False:
LOG.error("Not logged in")
return
if self.tid is None:
LOG.error("No share selected")
return
filepath = filepath.replace("\\", "/")
if not filepath.startswith("/"):
filepath = self.pwd.replace("\\", "/") + "/" + filepath
if (not filepath.endswith("/*")):
filepath = filepath + "/*"
filepath = os.path.abspath(filepath).replace("//", "/")
for LINE in self.smb.listPath(self.share, filepath):
if (LINE.is_directory()):
if (LINE.get_longname() == "." or LINE.get_longname() == ".."):
pass
else:
totalFilesRead = totalFilesRead + 1
folderList.append(filepath.strip("*") + LINE.get_longname())
else:
print(filepath.strip("*") + LINE.get_longname())
for ITEM in folderList:
ITEM = ITEM + "/*"
try:
retList, retFiles, retInt = self.do_listFiles(self.share, ITEM)
for q in retList:
folderList.append(q)
totalFilesRead = totalFilesRead + retInt
except:
pass
print("Finished - " + str(totalFilesRead) + " files and folders")
def do_rm(self, filename):
if self.tid is None:
LOG.error("No share selected")
return
f = ntpath.join(self.pwd, filename)
file = f.replace('/', '\\')
self.smb.deleteFile(self.share, file)
def do_mkdir(self, path):
if self.tid is None:
LOG.error("No share selected")
return
p = ntpath.join(self.pwd, path)
pathname = p.replace('/', '\\')
self.smb.createDirectory(self.share, pathname)
def do_rmdir(self, path):
if self.tid is None:
LOG.error("No share selected")
return
p = ntpath.join(self.pwd, path)
pathname = p.replace('/', '\\')
self.smb.deleteDirectory(self.share, pathname)
def do_put(self, pathname):
if self.tid is None:
LOG.error("No share selected")
return
src_path = pathname
dst_name = os.path.basename(src_path)
fh = open(pathname, 'rb')
f = ntpath.join(self.pwd, dst_name)
finalpath = f.replace('/', '\\')
self.smb.putFile(self.share, finalpath, fh.read)
fh.close()
def complete_get(self, text, line, begidx, endidx, include=1):
# include means
# 1 just files
# 2 just directories
p = line.replace('/', '\\')
if p.find('\\') < 0:
items = []
if include == 1:
mask = 0
else:
mask = 0x010
for i in self.completion:
if i[1] == mask:
items.append(i[0])
if text:
return [
item for item in items
if item.upper().startswith(text.upper())
]
else:
return items
def do_mget(self, mask):
if mask == '':
LOG.error("A mask must be provided")
return
if self.tid is None:
LOG.error("No share selected")
return
self.do_ls(mask, display=False)
if len(self.completion) == 0:
LOG.error("No files found matching the provided mask")
return
for file_tuple in self.completion:
if file_tuple[1] == 0:
filename = file_tuple[0]
filename = filename.replace('/', '\\')
fh = open(ntpath.basename(filename), 'wb')
pathname = ntpath.join(self.pwd, filename)
try:
LOG.info("Downloading %s" % (filename))
self.smb.getFileEx(self.share, pathname, fh.write)
except:
fh.close()
os.remove(filename)
raise
fh.close()
def do_rget(self, mask):
if mask == '':
mask = '*'
if self.tid is None:
LOG.error("No share selected")
return
if self.loggedIn is False:
LOG.error("Not logged in")
return
root_pwd = self.pwd
folderList = [root_pwd]
for ITEM in folderList:
self.pwd = ITEM
try:
self.do_ls('*', display=False)
for file_tuple in self.completion:
filename = file_tuple[0]
is_directory = file_tuple[1]
if filename in ['.', '..']:
continue
if is_directory:
folderList.append(ntpath.join(ITEM, filename))
self.do_ls(mask, display=False)
for file_tuple in self.completion:
filename = file_tuple[0]
is_directory = file_tuple[1]
if filename in ['.', '..'] or is_directory:
continue
filename = filename.replace('/', '\\')
local_path = ntpath.relpath(ITEM, root_pwd)
if local_path == '.':
local_path = ''
local_path = local_path.replace('\\', os.sep)
local_file = os.path.join(local_path, ntpath.basename(filename)) if local_path else ntpath.basename(
filename)
local_dir = os.path.dirname(local_file)
if local_dir and not os.path.exists(local_dir):
os.makedirs(local_dir)
fh = open(local_file, 'wb')
pathname = ntpath.join(ITEM, filename)
try:
LOG.info("Downloading %s" % local_file)
self.smb.getFileEx(self.share, pathname, fh.write)
except:
fh.close()
os.remove(local_file)
raise
fh.close()
finally:
self.pwd = root_pwd
def do_get(self, filename):
if self.tid is None:
LOG.error("No share selected")
return
filename = filename.replace('/', '\\')
fh = open(ntpath.basename(filename), 'wb')
pathname = ntpath.join(self.pwd, filename)
try:
self.smb.getFileEx(self.share, pathname, fh.write)
except:
fh.close()
os.remove(filename)
raise
fh.close()
def complete_cat(self, text, line, begidx, endidx):
return self.complete_get(text, line, begidx, endidx, include=1)
def do_cat(self, filename):
if self.tid is None:
LOG.error("No share selected")
return
filename = filename.replace('/', '\\')
fh = BytesIO()
pathname = ntpath.join(self.pwd, filename)
try:
self.smb.getFileEx(self.share, pathname, fh.write)
except:
raise
output = fh.getvalue()
encoding = chardet.detect(output)["encoding"]
error_msg = "[-] Output cannot be correctly decoded, are you sure the text is readable ?"
if self.outputfile is not None:
f = open(self.outputfile, 'a')
if encoding:
try:
if self.outputfile:
f.write(output.decode(encoding) + '\n')
f.close()
print(output.decode(encoding))
except:
if self.outputfile:
f.write(error_msg + '\n')
f.close()
print(error_msg)
finally:
fh.close()
else:
if self.outputfile:
f.write(error_msg + '\n')
f.close()
print(error_msg)
fh.close()
def do_close(self, line):
self.do_logoff(line)
def do_list_snapshots(self, line):
l = line.split(' ')
if len(l) > 0:
pathName = l[0].replace('/', '\\')
# Relative or absolute path?
if pathName.startswith('\\') is not True:
pathName = ntpath.join(self.pwd, pathName)
snapshotList = self.smb.listSnapshots(self.tid, pathName)
if not snapshotList:
print("No snapshots found")
return
for timestamp in snapshotList:
print(timestamp)
def do_mount(self, line):
l = line.split(' ')
if len(l) > 1:
target = l[0].replace('/', '\\')
pathName = l[1].replace('/', '\\')
# Relative or absolute path?
if pathName.startswith('\\') is not True:
pathName = ntpath.join(self.pwd, pathName)
self.smb.createMountPoint(self.tid, pathName, target)
def do_umount(self, mountpoint):
mountpoint = mountpoint.replace('/', '\\')
# Relative or absolute path?
if mountpoint.startswith('\\') is not True:
mountpoint = ntpath.join(self.pwd, mountpoint)
mountPath = ntpath.join(self.pwd, mountpoint)
self.smb.removeMountPoint(self.tid, mountPath)
def do_acl(self, line):
if self.tid is None:
LOG.error("No share selected")
return
parts = line.split()
if len(parts) == 0:
LOG.error("Usage: acl {filename,action,permissions,user/group} actions: grant/revoke, "
"supported permissions : R/W/D/X/F")
return
filename = parts[0].replace('/', '\\')
# Relative or absolute path?
if filename.startswith('\\') is not True:
filename = ntpath.join(self.pwd, filename)
smb_file_acl = None
try:
if len(parts) == 1:
smb_file_acl = SMBFileACL(smb_connection=self.smb)
resp = smb_file_acl.get_permissions(self.share, filename)
print(resp)
else:
action = parts[1].lower()
if action not in ['grant', 'revoke']:
LOG.error("Action must be 'grant' or 'revoke'")
return
if len(parts) < 3:
LOG.error(
"Permissions required. Supported: R (read), W (write), D (delete), X (execute), F (full control)")
return
permissions = parts[2]
if len(parts) < 4:
LOG.error("User/group name is required")
return
user = parts[3]
smb_file_acl = SMBFileACL(smb_connection=self.smb)
smb_file_acl.set_permissions(self.share, filename, user, permissions, action)
if action == 'grant':
print("Successfully granted permissions to %s" % user)
elif action == 'revoke':
print("Successfully revoked permissions from %s" % user)
finally:
if smb_file_acl:
smb_file_acl.close_connection()
def do_EOF(self, line):
print('Bye!\n')
return True
def main():
print(version.BANNER)
parser = argparse.ArgumentParser(add_help = True, description = "SMB client implementation.")
parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
parser.add_argument('-inputfile', type=argparse.FileType('r'), help='input file with commands to execute in the mini shell')
parser.add_argument('-outputfile', action='store', help='Output file to log smbclient actions in')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')
group = parser.add_argument_group('authentication')
group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
'(KRB5CCNAME) based on target parameters. If valid credentials '
'cannot be found, it will use the ones specified in the command '
'line')
group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication '
'(128 or 256 bits)')
group = parser.add_argument_group('connection')
group.add_argument('-dc-ip', action='store', metavar="ip address",
help='IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in '
'the target parameter')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
'This is useful when target is the NetBIOS name and you cannot resolve it')
group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
help='Destination port to connect to SMB Server')
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
options = parser.parse_args()
# Init the example's logger theme
logger.init(options.ts, options.debug)
domain, username, password, address = parse_target(options.target)
if options.target_ip is None:
options.target_ip = address
if domain is None:
domain = ''
if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
from getpass import getpass
password = getpass("Password:")
if options.aesKey is not None:
options.k = True
if options.hashes is not None:
lmhash, nthash = options.hashes.split(':')
else:
lmhash = ''
nthash = ''
try:
smbClient = SMBConnection(address, options.target_ip, sess_port=int(options.port))
if options.k is True:
smbClient.kerberosLogin(username, password, domain, lmhash, nthash, options.aesKey, options.dc_ip )
else:
smbClient.login(username, password, domain, lmhash, nthash)
shell = MiniImpacketShell(smbClient, None, options.outputfile, options.debug)
if options.outputfile is not None:
f = open(options.outputfile, 'a')
f.write('=' * 20 + '\n' + options.target_ip + '\n' + '=' * 20 + '\n')
f.close()
if options.inputfile is not None:
logging.info("Executing commands from %s" % options.inputfile.name)
for line in options.inputfile.readlines():
if line[0] != '#':
print("# %s" % line, end=' ')
shell.onecmd(line)
else:
print(line, end=' ')
else:
shell.cmdloop()
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback