Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

# 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: 

# 

# Wrapper class for SMB1/2/3 so it's transparent for the client. 

# You can still play with the low level methods (version dependent) 

# by calling getSMBServer() 

# 

import ntpath 

import socket 

 

from impacket import smb, smb3, nmb, nt_errors, LOG 

from impacket.ntlm import compute_lmhash, compute_nthash 

from impacket.smb3structs import SMB2Packet, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, GENERIC_ALL, FILE_SHARE_READ, \ 

FILE_SHARE_WRITE, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE, FILE_OVERWRITE_IF, FILE_ATTRIBUTE_NORMAL, \ 

SMB2_IL_IMPERSONATION, SMB2_OPLOCK_LEVEL_NONE, FILE_READ_DATA , FILE_WRITE_DATA, FILE_OPEN, GENERIC_READ, GENERIC_WRITE, \ 

FILE_OPEN_REPARSE_POINT, MOUNT_POINT_REPARSE_DATA_STRUCTURE, FSCTL_SET_REPARSE_POINT, SMB2_0_IOCTL_IS_FSCTL, \ 

MOUNT_POINT_REPARSE_GUID_DATA_STRUCTURE, FSCTL_DELETE_REPARSE_POINT 

 

 

# So the user doesn't need to import smb, the smb3 are already in here 

SMB_DIALECT = smb.SMB_DIALECT 

 

class SMBConnection: 

""" 

SMBConnection class 

 

:param string remoteName: name of the remote host, can be its NETBIOS name, IP or *\*SMBSERVER*. If the later, 

and port is 139, the library will try to get the target's server name. 

:param string remoteHost: target server's remote address (IPv4, IPv6) or FQDN 

:param string/optional myName: client's NETBIOS name 

:param integer/optional sess_port: target port to connect 

:param integer/optional timeout: timeout in seconds when receiving packets 

:param optional preferredDialect: the dialect desired to talk with the target server. If not specified the highest 

one available will be used 

:param optional boolean manualNegotiate: the user manually performs SMB_COM_NEGOTIATE 

 

:return: a SMBConnection instance, if not raises a SessionError exception 

""" 

 

def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None, 

existingConnection=None, manualNegotiate=False): 

 

self._SMBConnection = 0 

self._dialect = '' 

self._nmbSession = 0 

self._sess_port = sess_port 

self._myName = myName 

self._remoteHost = remoteHost 

self._remoteName = remoteName 

self._timeout = timeout 

self._preferredDialect = preferredDialect 

self._existingConnection = existingConnection 

self._manualNegotiate = manualNegotiate 

self._doKerberos = False 

self._kdcHost = None 

self._useCache = True 

self._ntlmFallback = True 

 

66 ↛ 68line 66 didn't jump to line 68, because the condition on line 66 was never true if existingConnection is not None: 

# Existing Connection must be a smb or smb3 instance 

assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3)) 

self._SMBConnection = existingConnection 

self._preferredDialect = self._SMBConnection.getDialect() 

self._doKerberos = self._SMBConnection.getKerberos() 

return 

 

##preferredDialect = smb.SMB_DIALECT 

 

if manualNegotiate is False: 

self.negotiateSession(preferredDialect) 

 

def negotiateSession(self, preferredDialect=None, 

flags1=smb.SMB.FLAGS1_PATHCASELESS | smb.SMB.FLAGS1_CANONICALIZED_PATHS, 

flags2=smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES, 

negoData='\x02NT LM 0.12\x00\x02SMB 2.002\x00\x02SMB 2.???\x00'): 

""" 

Perform protocol negotiation 

 

:param string preferredDialect: the dialect desired to talk with the target server. If None is specified the highest one available will be used 

:param string flags1: the SMB FLAGS capabilities 

:param string flags2: the SMB FLAGS2 capabilities 

:param string negoData: data to be sent as part of the nego handshake 

 

:return: True, raises a Session Error if error. 

""" 

 

# If port 445 and the name sent is *SMBSERVER we're setting the name to the IP. This is to help some old 

# applications still believing 

# *SMSBSERVER will work against modern OSes. If port is NETBIOS_SESSION_PORT the user better know about i 

# *SMBSERVER's limitations 

if self._sess_port == nmb.SMB_SESSION_PORT and self._remoteName == '*SMBSERVER': 

self._remoteName = self._remoteHost 

elif self._sess_port == nmb.NETBIOS_SESSION_PORT and self._remoteName == '*SMBSERVER': 

# If remote name is *SMBSERVER let's try to query its name.. if can't be guessed, continue and hope for the best 

nb = nmb.NetBIOS() 

try: 

res = nb.getnetbiosname(self._remoteHost) 

except: 

pass 

else: 

self._remoteName = res 

 

hostType = nmb.TYPE_SERVER 

if preferredDialect is None: 

# If no preferredDialect sent, we try the highest available one. 

packet = self.negotiateSessionWildcard(self._myName, self._remoteName, self._remoteHost, self._sess_port, 

self._timeout, True, flags1=flags1, flags2=flags2, data=negoData) 

115 ↛ 122line 115 didn't jump to line 122, because the condition on line 115 was never false if packet[0:1] == b'\xfe': 

# Answer is SMB2 packet 

self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType, 

self._sess_port, self._timeout, session=self._nmbSession, 

negSessionResponse=SMB2Packet(packet)) 

else: 

# Answer is SMB packet, sticking to SMBv1 

self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType, 

self._sess_port, self._timeout, session=self._nmbSession, 

negPacket=packet) 

else: 

if preferredDialect == smb.SMB_DIALECT: 

self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType, 

self._sess_port, self._timeout) 

129 ↛ 133line 129 didn't jump to line 133, because the condition on line 129 was never false elif preferredDialect in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]: 

self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType, 

self._sess_port, self._timeout, preferredDialect=preferredDialect) 

else: 

raise Exception("Unknown dialect %s") 

 

# propagate flags to the smb sub-object, except for Unicode (if server supports) 

# does not affect smb3 objects 

if isinstance(self._SMBConnection, smb.SMB): 

138 ↛ 139line 138 didn't jump to line 139, because the condition on line 138 was never true if self._SMBConnection.get_flags()[1] & smb.SMB.FLAGS2_UNICODE: 

flags2 |= smb.SMB.FLAGS2_UNICODE 

self._SMBConnection.set_flags(flags1=flags1, flags2=flags2) 

 

return True 

 

def negotiateSessionWildcard(self, myName, remoteName, remoteHost, sess_port, timeout, extended_security=True, flags1=0, 

flags2=0, data=None): 

# Here we follow [MS-SMB2] negotiation handshake trying to understand what dialects 

# (including SMB1) is supported on the other end. 

 

149 ↛ 155line 149 didn't jump to line 155, because the condition on line 149 was never false if not myName: 

myName = socket.gethostname() 

i = myName.find('.') 

152 ↛ 155line 152 didn't jump to line 155, because the condition on line 152 was never false if i > -1: 

myName = myName[:i] 

 

tries = 0 

smbp = smb.NewSMBPacket() 

smbp['Flags1'] = flags1 

# FLAGS2_UNICODE is required by some stacks to continue, regardless of subsequent support 

smbp['Flags2'] = flags2 | smb.SMB.FLAGS2_UNICODE 

resp = None 

161 ↛ 182line 161 didn't jump to line 182, because the condition on line 161 was never false while tries < 2: 

self._nmbSession = nmb.NetBIOSTCPSession(myName, remoteName, remoteHost, nmb.TYPE_SERVER, sess_port, 

timeout) 

 

negSession = smb.SMBCommand(smb.SMB.SMB_COM_NEGOTIATE) 

166 ↛ 168line 166 didn't jump to line 168, because the condition on line 166 was never false if extended_security is True: 

smbp['Flags2'] |= smb.SMB.FLAGS2_EXTENDED_SECURITY 

negSession['Data'] = data 

smbp.addCommand(negSession) 

self._nmbSession.send_packet(smbp.getData()) 

 

try: 

resp = self._nmbSession.recv_packet(timeout) 

break 

except nmb.NetBIOSError: 

# OSX Yosemite asks for more Flags. Let's give it a try and see what happens 

smbp['Flags2'] |= smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | smb.SMB.FLAGS2_UNICODE 

smbp['Data'] = [] 

 

tries += 1 

 

182 ↛ 184line 182 didn't jump to line 184, because the condition on line 182 was never true if resp is None: 

# No luck, quitting 

raise Exception('No answer!') 

 

return resp.get_trailer() 

 

 

def getNMBServer(self): 

return self._nmbSession 

 

def getSMBServer(self): 

""" 

returns the SMB/SMB3 instance being used. Useful for calling low level methods 

""" 

return self._SMBConnection 

 

def getDialect(self): 

return self._SMBConnection.getDialect() 

 

def getServerName(self): 

return self._SMBConnection.get_server_name() 

 

def getClientName(self): 

return self._SMBConnection.get_client_name() 

 

def getRemoteHost(self): 

return self._SMBConnection.get_remote_host() 

 

def getRemoteName(self): 

return self._SMBConnection.get_remote_name() 

 

def setRemoteName(self, name): 

return self._SMBConnection.set_remote_name(name) 

 

def getServerDomain(self): 

return self._SMBConnection.get_server_domain() 

 

def getServerDNSDomainName(self): 

return self._SMBConnection.get_server_dns_domain_name() 

 

def getServerOS(self): 

return self._SMBConnection.get_server_os() 

 

def getServerOSMajor(self): 

return self._SMBConnection.get_server_os_major() 

 

def getServerOSMinor(self): 

return self._SMBConnection.get_server_os_minor() 

 

def getServerOSBuild(self): 

return self._SMBConnection.get_server_os_build() 

 

def doesSupportNTLMv2(self): 

return self._SMBConnection.doesSupportNTLMv2() 

 

def isLoginRequired(self): 

return self._SMBConnection.is_login_required() 

 

def isSigningRequired(self): 

return self._SMBConnection.is_signing_required() 

 

def getCredentials(self): 

return self._SMBConnection.getCredentials() 

 

def getIOCapabilities(self): 

return self._SMBConnection.getIOCapabilities() 

 

def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True): 

""" 

logins into the target system 

 

:param string user: username 

:param string password: password for the user 

:param string domain: domain where the account is valid for 

:param string lmhash: LMHASH used to authenticate using hashes (password is not used) 

:param string nthash: NTHASH used to authenticate using hashes (password is not used) 

:param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1 

 

:return: None, raises a Session Error if error. 

""" 

self._ntlmFallback = ntlmFallback 

try: 

if self.getDialect() == smb.SMB_DIALECT: 

return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback) 

else: 

return self._SMBConnection.login(user, password, domain, lmhash, nthash) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def kerberosLogin(self, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None, 

TGS=None, useCache=True): 

""" 

logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported. 

 

:param string user: username 

:param string password: password for the user 

:param string domain: domain where the account is valid for (required) 

:param string lmhash: LMHASH used to authenticate using hashes (password is not used) 

:param string nthash: NTHASH used to authenticate using hashes (password is not used) 

:param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication 

:param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho) 

:param struct TGT: If there's a TGT available, send the structure here and it will be used 

:param struct TGS: same for TGS. See smb3.py for the format 

:param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False 

 

:return: None, raises a Session Error if error. 

""" 

import os 

from impacket.krb5.ccache import CCache 

from impacket.krb5.kerberosv5 import KerberosError 

from impacket.krb5 import constants 

 

self._kdcHost = kdcHost 

self._useCache = useCache 

 

297 ↛ 298line 297 didn't jump to line 298, because the condition on line 297 was never true if TGT is not None or TGS is not None: 

useCache = False 

 

300 ↛ 336line 300 didn't jump to line 336, because the condition on line 300 was never false if useCache is True: 

try: 

ccache = CCache.loadFile(os.getenv('KRB5CCNAME')) 

except: 

# No cache present 

pass 

else: 

LOG.debug("Using Kerberos Cache: %s" % os.getenv('KRB5CCNAME')) 

# retrieve domain information from CCache file if needed 

if domain == '': 

domain = ccache.principal.realm['data'].decode('utf-8') 

LOG.debug('Domain retrieved from CCache: %s' % domain) 

 

principal = 'cifs/%s@%s' % (self.getRemoteName().upper(), domain.upper()) 

creds = ccache.getCredential(principal) 

if creds is None: 

# Let's try for the TGT and go from there 

principal = 'krbtgt/%s@%s' % (domain.upper(),domain.upper()) 

creds = ccache.getCredential(principal) 

if creds is not None: 

TGT = creds.toTGT() 

LOG.debug('Using TGT from cache') 

else: 

LOG.debug("No valid credentials found in cache. ") 

else: 

TGS = creds.toTGS(principal) 

LOG.debug('Using TGS from cache') 

 

# retrieve user information from CCache file if needed 

if user == '' and creds is not None: 

user = creds['client'].prettyPrint().split(b'@')[0] 

LOG.debug('Username retrieved from CCache: %s' % user) 

elif user == '' and len(ccache.principal.components) > 0: 

user = ccache.principal.components[0]['data'] 

LOG.debug('Username retrieved from CCache: %s' % user) 

 

while True: 

try: 

if self.getDialect() == smb.SMB_DIALECT: 

return self._SMBConnection.kerberos_login(user, password, domain, lmhash, nthash, aesKey, kdcHost, 

TGT, TGS) 

return self._SMBConnection.kerberosLogin(user, password, domain, lmhash, nthash, aesKey, kdcHost, TGT, 

TGS) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

except KerberosError as e: 

if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value: 

# We might face this if the target does not support AES 

# So, if that's the case we'll force using RC4 by converting 

# the password to lm/nt hashes and hope for the best. If that's already 

# done, byebye. 

if lmhash is '' and nthash is '' and (aesKey is '' or aesKey is None) and TGT is None and TGS is None: 

lmhash = compute_lmhash(password) 

nthash = compute_nthash(password) 

else: 

raise e 

else: 

raise e 

 

def isGuestSession(self): 

try: 

return self._SMBConnection.isGuestSession() 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def logoff(self): 

try: 

return self._SMBConnection.logoff() 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def connectTree(self,share): 

if self.getDialect() == smb.SMB_DIALECT: 

# If we already have a UNC we do nothing. 

if ntpath.ismount(share) is False: 

# Else we build it 

share = ntpath.basename(share) 

share = '\\\\' + self.getRemoteHost() + '\\' + share 

try: 

return self._SMBConnection.connect_tree(share) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def disconnectTree(self, treeId): 

try: 

return self._SMBConnection.disconnect_tree(treeId) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def listShares(self): 

""" 

get a list of available shares at the connected target 

 

:return: a list containing dict entries for each share, raises exception if error 

""" 

# Get the shares through RPC 

from impacket.dcerpc.v5 import transport, srvs 

rpctransport = transport.SMBTransport(self.getRemoteName(), self.getRemoteHost(), filename=r'\srvsvc', 

smb_connection=self) 

dce = rpctransport.get_dce_rpc() 

dce.connect() 

dce.bind(srvs.MSRPC_UUID_SRVS) 

resp = srvs.hNetrShareEnum(dce, 1) 

return resp['InfoStruct']['ShareInfo']['Level1']['Buffer'] 

 

def listPath(self, shareName, path, password = None): 

""" 

list the files/directories under shareName/path 

 

:param string shareName: a valid name for the share where the files/directories are going to be searched 

:param string path: a base path relative to shareName 

:param string password: the password for the share 

 

:return: a list containing smb.SharedFile items, raises a SessionError exception if error. 

""" 

 

try: 

return self._SMBConnection.list_path(shareName, path, password) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def createFile(self, treeId, pathName, desiredAccess=GENERIC_ALL, 

shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 

creationOption=FILE_NON_DIRECTORY_FILE, creationDisposition=FILE_OVERWRITE_IF, 

fileAttributes=FILE_ATTRIBUTE_NORMAL, impersonationLevel=SMB2_IL_IMPERSONATION, securityFlags=0, 

oplockLevel=SMB2_OPLOCK_LEVEL_NONE, createContexts=None): 

""" 

creates a remote file 

 

 

:param HANDLE treeId: a valid handle for the share where the file is to be created 

:param string pathName: the path name of the file to create 

:param int desiredAccess: The level of access that is required, as specified in https://msdn.microsoft.com/en-us/library/cc246503.aspx 

:param int shareMode: Specifies the sharing mode for the open. 

:param int creationOption: Specifies the options to be applied when creating or opening the file. 

:param int creationDisposition: Defines the action the server MUST take if the file that is specified in the name 

field already exists. 

:param int fileAttributes: This field MUST be a combination of the values specified in [MS-FSCC] section 2.6, and MUST NOT include any values other than those specified in that section. 

:param int impersonationLevel: This field specifies the impersonation level requested by the application that is issuing the create request. 

:param int securityFlags: This field MUST NOT be used and MUST be reserved. The client MUST set this to 0, and the server MUST ignore it. 

:param int oplockLevel: The requested oplock level 

:param createContexts: A variable-length attribute that is sent with an SMB2 CREATE Request or SMB2 CREATE Response that either gives extra information about how the create will be processed, or returns extra information about how the create was processed. 

 

:return: a valid file descriptor, if not raises a SessionError exception. 

""" 

 

if self.getDialect() == smb.SMB_DIALECT: 

_, flags2 = self._SMBConnection.get_flags() 

 

pathName = pathName.replace('/', '\\') 

packetPathName = pathName.encode('utf-16le') if flags2 & smb.SMB.FLAGS2_UNICODE else pathName 

 

ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX) 

ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters() 

ntCreate['Data'] = smb.SMBNtCreateAndX_Data(flags=flags2) 

ntCreate['Parameters']['FileNameLength']= len(packetPathName) 

ntCreate['Parameters']['AccessMask'] = desiredAccess 

ntCreate['Parameters']['FileAttributes']= fileAttributes 

ntCreate['Parameters']['ShareAccess'] = shareMode 

ntCreate['Parameters']['Disposition'] = creationDisposition 

ntCreate['Parameters']['CreateOptions'] = creationOption 

ntCreate['Parameters']['Impersonation'] = impersonationLevel 

ntCreate['Parameters']['SecurityFlags'] = securityFlags 

ntCreate['Parameters']['CreateFlags'] = 0x16 

ntCreate['Data']['FileName'] = packetPathName 

 

if flags2 & smb.SMB.FLAGS2_UNICODE: 

ntCreate['Data']['Pad'] = 0x0 

 

472 ↛ 473line 472 didn't jump to line 473, because the condition on line 472 was never true if createContexts is not None: 

LOG.error("CreateContexts not supported in SMB1") 

 

try: 

return self._SMBConnection.nt_create_andx(treeId, pathName, cmd = ntCreate) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

else: 

try: 

return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption, 

creationDisposition, fileAttributes, impersonationLevel, 

securityFlags, oplockLevel, createContexts) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def openFile(self, treeId, pathName, desiredAccess=FILE_READ_DATA | FILE_WRITE_DATA, shareMode=FILE_SHARE_READ, 

creationOption=FILE_NON_DIRECTORY_FILE, creationDisposition=FILE_OPEN, 

fileAttributes=FILE_ATTRIBUTE_NORMAL, impersonationLevel=SMB2_IL_IMPERSONATION, securityFlags=0, 

oplockLevel=SMB2_OPLOCK_LEVEL_NONE, createContexts=None): 

""" 

opens a remote file 

 

:param HANDLE treeId: a valid handle for the share where the file is to be opened 

:param string pathName: the path name to open 

:param int desiredAccess: The level of access that is required, as specified in https://msdn.microsoft.com/en-us/library/cc246503.aspx 

:param int shareMode: Specifies the sharing mode for the open. 

:param int creationOption: Specifies the options to be applied when creating or opening the file. 

:param int creationDisposition: Defines the action the server MUST take if the file that is specified in the name 

field already exists. 

:param int fileAttributes: This field MUST be a combination of the values specified in [MS-FSCC] section 2.6, and MUST NOT include any values other than those specified in that section. 

:param int impersonationLevel: This field specifies the impersonation level requested by the application that is issuing the create request. 

:param int securityFlags: This field MUST NOT be used and MUST be reserved. The client MUST set this to 0, and the server MUST ignore it. 

:param int oplockLevel: The requested oplock level 

:param createContexts: A variable-length attribute that is sent with an SMB2 CREATE Request or SMB2 CREATE Response that either gives extra information about how the create will be processed, or returns extra information about how the create was processed. 

 

 

:return: a valid file descriptor, if not raises a SessionError exception. 

""" 

 

if self.getDialect() == smb.SMB_DIALECT: 

_, flags2 = self._SMBConnection.get_flags() 

 

pathName = pathName.replace('/', '\\') 

packetPathName = pathName.encode('utf-16le') if flags2 & smb.SMB.FLAGS2_UNICODE else pathName 

 

ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX) 

ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters() 

ntCreate['Data'] = smb.SMBNtCreateAndX_Data(flags=flags2) 

ntCreate['Parameters']['FileNameLength']= len(packetPathName) 

ntCreate['Parameters']['AccessMask'] = desiredAccess 

ntCreate['Parameters']['FileAttributes']= fileAttributes 

ntCreate['Parameters']['ShareAccess'] = shareMode 

ntCreate['Parameters']['Disposition'] = creationDisposition 

ntCreate['Parameters']['CreateOptions'] = creationOption 

ntCreate['Parameters']['Impersonation'] = impersonationLevel 

ntCreate['Parameters']['SecurityFlags'] = securityFlags 

ntCreate['Parameters']['CreateFlags'] = 0x16 

ntCreate['Data']['FileName'] = packetPathName 

 

if flags2 & smb.SMB.FLAGS2_UNICODE: 

ntCreate['Data']['Pad'] = 0x0 

 

534 ↛ 535line 534 didn't jump to line 535, because the condition on line 534 was never true if createContexts is not None: 

LOG.error("CreateContexts not supported in SMB1") 

 

try: 

return self._SMBConnection.nt_create_andx(treeId, pathName, cmd = ntCreate) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

else: 

try: 

return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption, 

creationDisposition, fileAttributes, impersonationLevel, 

securityFlags, oplockLevel, createContexts) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def writeFile(self, treeId, fileId, data, offset=0): 

""" 

writes data to a file 

 

:param HANDLE treeId: a valid handle for the share where the file is to be written 

:param HANDLE fileId: a valid handle for the file 

:param string data: buffer with the data to write 

:param integer offset: offset where to start writing the data 

 

:return: amount of bytes written, if not raises a SessionError exception. 

""" 

try: 

return self._SMBConnection.writeFile(treeId, fileId, data, offset) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def readFile(self, treeId, fileId, offset = 0, bytesToRead = None, singleCall = True): 

""" 

reads data from a file 

 

:param HANDLE treeId: a valid handle for the share where the file is to be read 

:param HANDLE fileId: a valid handle for the file to be read 

:param integer offset: offset where to start reading the data 

:param integer bytesToRead: amount of bytes to attempt reading. If None, it will attempt to read Dialect['MaxBufferSize'] bytes. 

:param boolean singleCall: If True it won't attempt to read all bytesToRead. It will only make a single read call 

 

:return: the data read, if not raises a SessionError exception. Length of data read is not always bytesToRead 

""" 

finished = False 

data = b'' 

maxReadSize = self._SMBConnection.getIOCapabilities()['MaxReadSize'] 

if bytesToRead is None: 

bytesToRead = maxReadSize 

remainingBytesToRead = bytesToRead 

while not finished: 

if remainingBytesToRead > maxReadSize: 

toRead = maxReadSize 

else: 

toRead = remainingBytesToRead 

try: 

bytesRead = self._SMBConnection.read_andx(treeId, fileId, offset, toRead) 

except (smb.SessionError, smb3.SessionError) as e: 

592 ↛ 593line 592 didn't jump to line 593, because the condition on line 592 was never true if e.get_error_code() == nt_errors.STATUS_END_OF_FILE: 

toRead = b'' 

break 

else: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

data += bytesRead 

if len(data) >= bytesToRead: 

finished = True 

601 ↛ 603line 601 didn't jump to line 603, because the condition on line 601 was never true elif len(bytesRead) == 0: 

# End of the file achieved. 

finished = True 

604 ↛ 607line 604 didn't jump to line 607, because the condition on line 604 was never false elif singleCall is True: 

finished = True 

else: 

offset += len(bytesRead) 

remainingBytesToRead -= len(bytesRead) 

 

return data 

 

def closeFile(self, treeId, fileId): 

""" 

closes a file handle 

 

:param HANDLE treeId: a valid handle for the share where the file is to be opened 

:param HANDLE fileId: a valid handle for the file/directory to be closed 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.close(treeId, fileId) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def deleteFile(self, shareName, pathName): 

""" 

removes a file 

 

:param string shareName: a valid name for the share where the file is to be deleted  

:param string pathName: the path name to remove 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.remove(shareName, pathName) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def queryInfo(self, treeId, fileId): 

""" 

queries basic information about an opened file/directory 

 

:param HANDLE treeId: a valid handle for the share where the file is to be opened 

:param HANDLE fileId: a valid handle for the file/directory to be closed 

 

:return: a smb.SMBQueryFileBasicInfo structure. raises a SessionError exception if error. 

 

""" 

try: 

if self.getDialect() == smb.SMB_DIALECT: 

res = self._SMBConnection.query_file_info(treeId, fileId) 

else: 

res = self._SMBConnection.queryInfo(treeId, fileId) 

return smb.SMBQueryFileStandardInfo(res) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def createDirectory(self, shareName, pathName ): 

""" 

creates a directory 

 

:param string shareName: a valid name for the share where the directory is to be created 

:param string pathName: the path name or the directory to create 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.mkdir(shareName, pathName) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def deleteDirectory(self, shareName, pathName): 

""" 

deletes a directory 

 

:param string shareName: a valid name for the share where directory is to be deleted 

:param string pathName: the path name or the directory to delete 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.rmdir(shareName, pathName) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def waitNamedPipe(self, treeId, pipeName, timeout = 5): 

""" 

waits for a named pipe 

 

:param HANDLE treeId: a valid handle for the share where the pipe is 

:param string pipeName: the pipe name to check 

:param integer timeout: time to wait for an answer 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.waitNamedPipe(treeId, pipeName, timeout = timeout) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def transactNamedPipe(self, treeId, fileId, data, waitAnswer = True): 

""" 

writes to a named pipe using a transaction command 

 

:param HANDLE treeId: a valid handle for the share where the pipe is 

:param HANDLE fileId: a valid handle for the pipe 

:param string data: buffer with the data to write 

:param boolean waitAnswer: whether or not to wait for an answer 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.TransactNamedPipe(treeId, fileId, data, waitAnswer = waitAnswer) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def transactNamedPipeRecv(self): 

""" 

reads from a named pipe using a transaction command 

 

:return: data read, raises a SessionError exception if error. 

 

""" 

try: 

return self._SMBConnection.TransactNamedPipeRecv() 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def writeNamedPipe(self, treeId, fileId, data, waitAnswer = True): 

""" 

writes to a named pipe 

 

:param HANDLE treeId: a valid handle for the share where the pipe is 

:param HANDLE fileId: a valid handle for the pipe 

:param string data: buffer with the data to write 

:param boolean waitAnswer: whether or not to wait for an answer 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

if self.getDialect() == smb.SMB_DIALECT: 

return self._SMBConnection.write_andx(treeId, fileId, data, wait_answer = waitAnswer, write_pipe_mode = True) 

else: 

return self.writeFile(treeId, fileId, data, 0) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def readNamedPipe(self,treeId, fileId, bytesToRead = None ): 

""" 

read from a named pipe 

 

:param HANDLE treeId: a valid handle for the share where the pipe resides 

:param HANDLE fileId: a valid handle for the pipe 

:param integer bytesToRead: amount of data to read 

 

:return: None, raises a SessionError exception if error. 

 

""" 

 

try: 

return self.readFile(treeId, fileId, bytesToRead = bytesToRead, singleCall = True) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

 

def getFile(self, shareName, pathName, callback, shareAccessMode = None): 

""" 

downloads a file 

 

:param string shareName: name for the share where the file is to be retrieved 

:param string pathName: the path name to retrieve 

:param callback callback: function called to write the contents read. 

:param int shareAccessMode: 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

789 ↛ 793line 789 didn't jump to line 793, because the condition on line 789 was never false if shareAccessMode is None: 

# if share access mode is none, let's the underlying API deals with it 

return self._SMBConnection.retr_file(shareName, pathName, callback) 

else: 

return self._SMBConnection.retr_file(shareName, pathName, callback, shareAccessMode=shareAccessMode) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def putFile(self, shareName, pathName, callback, shareAccessMode = None): 

""" 

uploads a file 

 

:param string shareName: name for the share where the file is to be uploaded 

:param string pathName: the path name to upload 

:param callback callback: function called to read the contents to be written. 

:param int shareAccessMode: 

 

:return: None, raises a SessionError exception if error. 

 

""" 

try: 

810 ↛ 814line 810 didn't jump to line 814, because the condition on line 810 was never false if shareAccessMode is None: 

# if share access mode is none, let's the underlying API deals with it 

return self._SMBConnection.stor_file(shareName, pathName, callback) 

else: 

return self._SMBConnection.stor_file(shareName, pathName, callback, shareAccessMode) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def createMountPoint(self, tid, path, target): 

""" 

creates a mount point at an existing directory 

 

:param int tid: tree id of current connection 

:param string path: directory at which to create mount point (must already exist) 

:param string target: target address of mount point 

""" 

 

# Verify we're under SMB2+ session 

if self.getDialect() not in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]: 

raise SessionError(error = nt_errors.STATUS_NOT_SUPPORTED) 

 

fid = self.openFile(tid, path, GENERIC_READ | GENERIC_WRITE, 

creationOption=FILE_OPEN_REPARSE_POINT) 

 

if target.startswith("\\"): 

fixed_name = target.encode('utf-16le') 

else: 

fixed_name = ("\\??\\" + target).encode('utf-16le') 

 

name = target.encode('utf-16le') 

 

reparseData = MOUNT_POINT_REPARSE_DATA_STRUCTURE() 

 

reparseData['PathBuffer'] = fixed_name + b"\x00\x00" + name + b"\x00\x00" 

reparseData['SubstituteNameLength'] = len(fixed_name) 

reparseData['PrintNameOffset'] = len(fixed_name) + 2 

reparseData['PrintNameLength'] = len(name) 

 

self._SMBConnection.ioctl(tid, fid, FSCTL_SET_REPARSE_POINT, flags=SMB2_0_IOCTL_IS_FSCTL, 

inputBlob=reparseData) 

 

self.closeFile(tid, fid) 

 

def removeMountPoint(self, tid, path): 

""" 

removes a mount point without deleting the underlying directory 

 

:param int tid: tree id of current connection 

:param string path: path to mount point to remove 

""" 

 

# Verify we're under SMB2+ session 

if self.getDialect() not in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]: 

raise SessionError(error = nt_errors.STATUS_NOT_SUPPORTED) 

 

fid = self.openFile(tid, path, GENERIC_READ | GENERIC_WRITE, 

creationOption=FILE_OPEN_REPARSE_POINT) 

 

reparseData = MOUNT_POINT_REPARSE_GUID_DATA_STRUCTURE() 

 

reparseData['DataBuffer'] = b"" 

 

try: 

self._SMBConnection.ioctl(tid, fid, FSCTL_DELETE_REPARSE_POINT, flags=SMB2_0_IOCTL_IS_FSCTL, 

inputBlob=reparseData) 

except (smb.SessionError, smb3.SessionError) as e: 

self.closeFile(tid, fid) 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

self.closeFile(tid, fid) 

 

def rename(self, shareName, oldPath, newPath): 

""" 

renames a file/directory 

 

:param string shareName: name for the share where the files/directories are 

:param string oldPath: the old path name or the directory/file to rename 

:param string newPath: the new path name or the directory/file to rename 

 

:return: True, raises a SessionError exception if error. 

 

""" 

 

try: 

return self._SMBConnection.rename(shareName, oldPath, newPath) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def reconnect(self): 

""" 

reconnects the SMB object based on the original options and credentials used. Only exception is that 

manualNegotiate will not be honored. 

Not only the connection will be created but also a login attempt using the original credentials and 

method (Kerberos, PtH, etc) 

 

:return: True, raises a SessionError exception if error 

""" 

userName, password, domain, lmhash, nthash, aesKey, TGT, TGS = self.getCredentials() 

self.negotiateSession(self._preferredDialect) 

909 ↛ 910line 909 didn't jump to line 910, because the condition on line 909 was never true if self._doKerberos is True: 

self.kerberosLogin(userName, password, domain, lmhash, nthash, aesKey, self._kdcHost, TGT, TGS, self._useCache) 

else: 

self.login(userName, password, domain, lmhash, nthash, self._ntlmFallback) 

 

return True 

 

def setTimeout(self, timeout): 

try: 

return self._SMBConnection.set_timeout(timeout) 

except (smb.SessionError, smb3.SessionError) as e: 

raise SessionError(e.get_error_code(), e.get_error_packet()) 

 

def getSessionKey(self): 

if self.getDialect() == smb.SMB_DIALECT: 

return self._SMBConnection.get_session_key() 

else: 

return self._SMBConnection.getSessionKey() 

 

def setSessionKey(self, key): 

if self.getDialect() == smb.SMB_DIALECT: 

return self._SMBConnection.set_session_key(key) 

else: 

return self._SMBConnection.setSessionKey(key) 

 

def close(self): 

""" 

logs off and closes the underlying _NetBIOSSession() 

 

:return: None 

""" 

try: 

self.logoff() 

except: 

pass 

self._SMBConnection.close_session() 

 

class SessionError(Exception): 

""" 

This is the exception every client should catch regardless of the underlying 

SMB version used. We'll take care of that. NETBIOS exceptions are NOT included, 

since all SMB versions share the same NETBIOS instances. 

""" 

def __init__( self, error = 0, packet=0): 

Exception.__init__(self) 

self.error = error 

self.packet = packet 

 

def getErrorCode( self ): 

return self.error 

 

def getErrorPacket( self ): 

return self.packet 

 

def getErrorString( self ): 

return nt_errors.ERROR_MESSAGES[self.error] 

 

def __str__( self ): 

967 ↛ 970line 967 didn't jump to line 970, because the condition on line 967 was never false if self.error in nt_errors.ERROR_MESSAGES: 

return 'SMB SessionError: %s(%s)' % (nt_errors.ERROR_MESSAGES[self.error]) 

else: 

return 'SMB SessionError: 0x%x' % self.error