| 1 |
from __future__ import print_function |
| 2 |
# Copyright (c) 2003-2016 CORE Security Technologies |
| 3 |
# |
| 4 |
# This software is provided under under a slightly modified version |
| 5 |
# of the Apache Software License. See the accompanying LICENSE file |
| 6 |
# for more information. |
| 7 |
# |
| 8 |
# Author: Alberto Solino (@agsolino) |
| 9 |
# |
| 10 |
# Description: |
| 11 |
# [MS-SMB2] Protocol Implementation (SMB2 and SMB3) |
| 12 |
# As you might see in the code, it's implemented strictly following |
| 13 |
# the structures defined in the protocol specification. This may |
| 14 |
# not be the most efficient way (e.g. self._Connection is the |
| 15 |
# same to self._Session in the context of this library ) but |
| 16 |
# it certainly helps following the document way easier. |
| 17 |
# |
| 18 |
# ToDo: |
| 19 |
# [X] Implement SMB2_CHANGE_NOTIFY |
| 20 |
# [X] Implement SMB2_QUERY_INFO |
| 21 |
# [X] Implement SMB2_SET_INFO |
| 22 |
# [ ] Implement SMB2_OPLOCK_BREAK |
| 23 |
# [X] Implement SMB3 signing |
| 24 |
# [ ] Implement SMB3 encryption |
| 25 |
# [ ] Add more backward compatible commands from the smb.py code |
| 26 |
# [ ] Fix up all the 'ToDo' comments inside the code |
| 27 |
# |
| 28 |
|
| 29 |
import socket |
| 30 |
import ntpath |
| 31 |
import random |
| 32 |
import string |
| 33 |
import struct |
| 34 |
from binascii import a2b_hex |
| 35 |
from contextlib import contextmanager |
| 36 |
|
| 37 |
from impacket import nmb, ntlm, uuid, crypto, LOG |
| 38 |
from impacket.smb3structs import * |
| 39 |
from impacket.nt_errors import STATUS_SUCCESS, STATUS_MORE_PROCESSING_REQUIRED, STATUS_INVALID_PARAMETER, \ |
| 40 |
STATUS_NO_MORE_FILES, STATUS_PENDING, STATUS_NOT_IMPLEMENTED, ERROR_MESSAGES |
| 41 |
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp |
| 42 |
|
| 43 |
|
| 44 |
# For signing |
| 45 |
import hashlib, hmac, copy |
| 46 |
|
| 47 |
# Structs to be used |
| 48 |
TREE_CONNECT = { |
| 49 |
'ShareName' : '', |
| 50 |
'TreeConnectId' : 0, |
| 51 |
'Session' : 0, |
| 52 |
'IsDfsShare' : False, |
| 53 |
# If the client implements the SMB 3.0 dialect, |
| 54 |
# the client MUST also implement the following |
| 55 |
'IsCAShare' : False, |
| 56 |
'EncryptData' : False, |
| 57 |
'IsScaleoutShare' : False, |
| 58 |
# Outside the protocol |
| 59 |
'NumberOfUses' : 0, |
| 60 |
} |
| 61 |
|
| 62 |
FILE = { |
| 63 |
'OpenTable' : [], |
| 64 |
'LeaseKey' : '', |
| 65 |
'LeaseState' : 0, |
| 66 |
'LeaseEpoch' : 0, |
| 67 |
} |
| 68 |
|
| 69 |
OPEN = { |
| 70 |
'FileID' : '', |
| 71 |
'TreeConnect' : 0, |
| 72 |
'Connection' : 0, # Not Used |
| 73 |
'Oplocklevel' : 0, |
| 74 |
'Durable' : False, |
| 75 |
'FileName' : '', |
| 76 |
'ResilientHandle' : False, |
| 77 |
'LastDisconnectTime' : 0, |
| 78 |
'ResilientTimeout' : 0, |
| 79 |
'OperationBuckets' : [], |
| 80 |
# If the client implements the SMB 3.0 dialect, |
| 81 |
# the client MUST implement the following |
| 82 |
'CreateGuid' : '', |
| 83 |
'IsPersistent' : False, |
| 84 |
'DesiredAccess' : '', |
| 85 |
'ShareMode' : 0, |
| 86 |
'CreateOption' : '', |
| 87 |
'FileAttributes' : '', |
| 88 |
'CreateDisposition' : '', |
| 89 |
} |
| 90 |
|
| 91 |
REQUEST = { |
| 92 |
'CancelID' : '', |
| 93 |
'Message' : '', |
| 94 |
'Timestamp' : 0, |
| 95 |
} |
| 96 |
|
| 97 |
CHANNEL = { |
| 98 |
'SigningKey' : '', |
| 99 |
'Connection' : 0, |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
class SessionError(Exception): |
| 104 |
def __init__( self, error = 0, packet=0): |
| 105 |
Exception.__init__(self) |
| 106 |
self.error = error |
| 107 |
self.packet = packet |
| 108 |
|
| 109 |
def get_error_code( self ): |
| 110 |
return self.error |
| 111 |
|
| 112 |
def get_error_packet( self ): |
| 113 |
return self.packet |
| 114 |
|
| 115 |
def __str__( self ): |
| 116 |
return 'SMB SessionError: %s(%s)' % (ERROR_MESSAGES[self.error]) |
| 117 |
|
| 118 |
|
| 119 |
class SMB3: |
| 120 |
def __init__(self, remote_name, remote_host, my_name = None, host_type = nmb.TYPE_SERVER, sess_port = 445, timeout=60, UDP = 0, preferredDialect = None, session = None): |
| 121 |
|
| 122 |
# [MS-SMB2] Section 3 |
| 123 |
self.RequireMessageSigning = False # |
| 124 |
self.ConnectionTable = {} |
| 125 |
self.GlobalFileTable = {} |
| 126 |
self.ClientGuid = ''.join([random.choice(string.letters) for i in range(16)]) |
| 127 |
# Only for SMB 3.0 |
| 128 |
self.EncryptionAlgorithmList = ['AES-CCM'] |
| 129 |
self.MaxDialect = [] |
| 130 |
self.RequireSecureNegotiate = False |
| 131 |
|
| 132 |
# Per Transport Connection Data |
| 133 |
self._Connection = { |
| 134 |
# Indexed by SessionID |
| 135 |
#'SessionTable' : {}, |
| 136 |
# Indexed by MessageID |
| 137 |
'OutstandingRequests' : {}, |
| 138 |
'OutstandingResponses' : {}, # |
| 139 |
'SequenceWindow' : 0, # |
| 140 |
'GSSNegotiateToken' : '', # |
| 141 |
'MaxTransactSize' : 0, # |
| 142 |
'MaxReadSize' : 0, # |
| 143 |
'MaxWriteSize' : 0, # |
| 144 |
'ServerGuid' : '', # |
| 145 |
'RequireSigning' : False, # |
| 146 |
'ServerName' : '', # |
| 147 |
# If the client implements the SMB 2.1 or SMB 3.0 dialects, it MUST |
| 148 |
# also implement the following |
| 149 |
'Dialect' : '', # |
| 150 |
'SupportsFileLeasing' : False, # |
| 151 |
'SupportsMultiCredit' : False, # |
| 152 |
# If the client implements the SMB 3.0 dialect, |
| 153 |
# it MUST also implement the following |
| 154 |
'SupportsDirectoryLeasing' : False, # |
| 155 |
'SupportsMultiChannel' : False, # |
| 156 |
'SupportsPersistentHandles': False, # |
| 157 |
'SupportsEncryption' : False, # |
| 158 |
'ClientCapabilities' : 0, |
| 159 |
'ServerCapabilities' : 0, # |
| 160 |
'ClientSecurityMode' : 0, # |
| 161 |
'ServerSecurityMode' : 0, # |
| 162 |
# Outside the protocol |
| 163 |
'ServerIP' : '', # |
| 164 |
} |
| 165 |
|
| 166 |
self._Session = { |
| 167 |
'SessionID' : 0, # |
| 168 |
'TreeConnectTable' : {}, # |
| 169 |
'SessionKey' : '', # |
| 170 |
'SigningRequired' : False, # |
| 171 |
'Connection' : 0, # |
| 172 |
'UserCredentials' : '', # |
| 173 |
'OpenTable' : {}, # |
| 174 |
# If the client implements the SMB 3.0 dialect, |
| 175 |
# it MUST also implement the following |
| 176 |
'ChannelList' : [], |
| 177 |
'ChannelSequence' : 0, |
| 178 |
#'EncryptData' : False, |
| 179 |
'EncryptData' : True, |
| 180 |
'EncryptionKey' : '', |
| 181 |
'DecryptionKey' : '', |
| 182 |
'SigningKey' : '', |
| 183 |
'ApplicationKey' : '', |
| 184 |
# Outside the protocol |
| 185 |
'SessionFlags' : 0, # |
| 186 |
'ServerName' : '', # |
| 187 |
'ServerDomain' : '', # |
| 188 |
'ServerDNSDomainName' : '', # |
| 189 |
'ServerOS' : '', # |
| 190 |
'SigningActivated' : False, # |
| 191 |
} |
| 192 |
|
| 193 |
self.SMB_PACKET = SMB2Packet |
| 194 |
|
| 195 |
self._timeout = timeout |
| 196 |
self._Connection['ServerIP'] = remote_host |
| 197 |
self._NetBIOSSession = None |
| 198 |
|
| 199 |
self.__userName = '' |
| 200 |
self.__password = '' |
| 201 |
self.__domain = '' |
| 202 |
self.__lmhash = '' |
| 203 |
self.__nthash = '' |
| 204 |
self.__kdc = '' |
| 205 |
self.__aesKey = '' |
| 206 |
self.__TGT = None |
| 207 |
self.__TGS = None |
| 208 |
|
| 209 |
if sess_port == 445 and remote_name == '*SMBSERVER': |
| 210 |
self._Connection['ServerName'] = remote_host |
| 211 |
else: |
| 212 |
self._Connection['ServerName'] = remote_name |
| 213 |
|
| 214 |
if session is None: |
| 215 |
if not my_name: |
| 216 |
my_name = socket.gethostname() |
| 217 |
i = string.find(my_name, '.') |
| 218 |
if i > -1: |
| 219 |
my_name = my_name[:i] |
| 220 |
|
| 221 |
if UDP: |
| 222 |
self._NetBIOSSession = nmb.NetBIOSUDPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout) |
| 223 |
else: |
| 224 |
self._NetBIOSSession = nmb.NetBIOSTCPSession(my_name, self._Connection['ServerName'], remote_host, host_type, sess_port, self._timeout) |
| 225 |
|
| 226 |
self.negotiateSession(preferredDialect) |
| 227 |
else: |
| 228 |
self._NetBIOSSession = session |
| 229 |
# We should increase the SequenceWindow since a packet was already received. |
| 230 |
self._Connection['SequenceWindow'] += 1 |
| 231 |
# Let's negotiate again using the same connection |
| 232 |
self.negotiateSession(preferredDialect) |
| 233 |
|
| 234 |
def printStatus(self): |
| 235 |
print("CONNECTION") |
| 236 |
for i in self._Connection.items(): |
| 237 |
print("%-40s : %s" % i) |
| 238 |
print() |
| 239 |
print("SESSION") |
| 240 |
for i in self._Session.items(): |
| 241 |
print("%-40s : %s" % i) |
| 242 |
|
| 243 |
def getServerName(self): |
| 244 |
return self._Session['ServerName'] |
| 245 |
|
| 246 |
def getServerIP(self): |
| 247 |
return self._Connection['ServerIP'] |
| 248 |
|
| 249 |
def getServerDomain(self): |
| 250 |
return self._Session['ServerDomain'] |
| 251 |
|
| 252 |
def getServerDNSDomainName(self): |
| 253 |
return self._Session['ServerDNSDomainName'] |
| 254 |
|
| 255 |
def getServerOS(self): |
| 256 |
return self._Session['ServerOS'] |
| 257 |
|
| 258 |
def getServerOSMajor(self): |
| 259 |
return self._Session['ServerOSMajor'] |
| 260 |
|
| 261 |
def getServerOSMinor(self): |
| 262 |
return self._Session['ServerOSMinor'] |
| 263 |
|
| 264 |
def getServerOSBuild(self): |
| 265 |
return self._Session['ServerOSBuild'] |
| 266 |
|
| 267 |
def isGuestSession(self): |
| 268 |
return self._Session['SessionFlags'] & SMB2_SESSION_FLAG_IS_GUEST |
| 269 |
|
| 270 |
def setTimeout(self, timeout): |
| 271 |
self._timeout = timeout |
| 272 |
|
| 273 |
@contextmanager |
| 274 |
def useTimeout(self, timeout): |
| 275 |
prev_timeout = self.getTimeout(timeout) |
| 276 |
try: |
| 277 |
yield |
| 278 |
finally: |
| 279 |
self.setTimeout(prev_timeout) |
| 280 |
|
| 281 |
def getDialect(self): |
| 282 |
return self._Connection['Dialect'] |
| 283 |
|
| 284 |
|
| 285 |
def signSMB(self, packet): |
| 286 |
packet['Signature'] = '\x00'*16 |
| 287 |
if self._Connection['Dialect'] == SMB2_DIALECT_21 or self._Connection['Dialect'] == SMB2_DIALECT_002: |
| 288 |
if len(self._Session['SessionKey']) > 0: |
| 289 |
signature = hmac.new(self._Session['SessionKey'], str(packet), hashlib.sha256).digest() |
| 290 |
packet['Signature'] = signature[:16] |
| 291 |
else: |
| 292 |
if len(self._Session['SessionKey']) > 0: |
| 293 |
p = str(packet) |
| 294 |
signature = crypto.AES_CMAC(self._Session['SigningKey'], p, len(p)) |
| 295 |
packet['Signature'] = signature |
| 296 |
|
| 297 |
def sendSMB(self, packet): |
| 298 |
# The idea here is to receive multiple/single commands and create a compound request, and send it |
| 299 |
# Should return the MessageID for later retrieval. Implement compounded related requests. |
| 300 |
|
| 301 |
# If Connection.Dialect is equal to "3.000" and if Connection.SupportsMultiChannel or |
| 302 |
# Connection.SupportsPersistentHandles is TRUE, the client MUST set ChannelSequence in the |
| 303 |
# SMB2 header to Session.ChannelSequence |
| 304 |
|
| 305 |
# Check this is not a CANCEL request. If so, don't consume sequece numbers |
| 306 |
if packet['Command'] is not SMB2_CANCEL: |
| 307 |
packet['MessageID'] = self._Connection['SequenceWindow'] |
| 308 |
self._Connection['SequenceWindow'] += 1 |
| 309 |
packet['SessionID'] = self._Session['SessionID'] |
| 310 |
|
| 311 |
# Default the credit charge to 1 unless set by the caller |
| 312 |
if ('CreditCharge' in packet.fields) is False: |
| 313 |
packet['CreditCharge'] = 1 |
| 314 |
|
| 315 |
# Standard credit request after negotiating protocol |
| 316 |
if self._Connection['SequenceWindow'] > 3: |
| 317 |
packet['CreditRequestResponse'] = 127 |
| 318 |
|
| 319 |
messageId = packet['MessageID'] |
| 320 |
|
| 321 |
if self._Session['SigningActivated'] is True and self._Connection['SequenceWindow'] > 2: |
| 322 |
if packet['TreeID'] > 0 and (packet['TreeID'] in self._Session['TreeConnectTable']) is True: |
| 323 |
if self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is False: |
| 324 |
packet['Flags'] = SMB2_FLAGS_SIGNED |
| 325 |
self.signSMB(packet) |
| 326 |
elif packet['TreeID'] == 0: |
| 327 |
packet['Flags'] = SMB2_FLAGS_SIGNED |
| 328 |
self.signSMB(packet) |
| 329 |
|
| 330 |
if (self._Session['SessionFlags'] & SMB2_SESSION_FLAG_ENCRYPT_DATA) or ( packet['TreeID'] != 0 and self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is True): |
| 331 |
plainText = str(packet) |
| 332 |
transformHeader = SMB2_TRANSFORM_HEADER() |
| 333 |
transformHeader['Nonce'] = ''.join([random.choice(string.letters) for i in range(11)]) |
| 334 |
transformHeader['OriginalMessageSize'] = len(plainText) |
| 335 |
transformHeader['EncryptionAlgorithm'] = SMB2_ENCRYPTION_AES128_CCM |
| 336 |
transformHeader['SessionID'] = self._Session['SessionID'] |
| 337 |
from Crypto.Cipher import AES |
| 338 |
try: |
| 339 |
AES.MODE_CCM |
| 340 |
except: |
| 341 |
LOG.critical("Your pycrypto doesn't support AES.MODE_CCM. Currently only pycrypto experimental supports this mode.\nDownload it from https://www.dlitz.net/software/pycrypto ") |
| 342 |
raise |
| 343 |
cipher = AES.new(self._Session['EncryptionKey'], AES.MODE_CCM, transformHeader['Nonce']) |
| 344 |
cipher.update(str(transformHeader)[20:]) |
| 345 |
cipherText = cipher.encrypt(plainText) |
| 346 |
transformHeader['Signature'] = cipher.digest() |
| 347 |
packet = str(transformHeader) + cipherText |
| 348 |
|
| 349 |
self._NetBIOSSession.send_packet(str(packet)) |
| 350 |
return messageId |
| 351 |
|
| 352 |
def recvSMB(self, packetID = None): |
| 353 |
# First, verify we don't have the packet already |
| 354 |
if packetID in self._Connection['OutstandingResponses']: |
| 355 |
return self._Connection['OutstandingResponses'].pop(packetID) |
| 356 |
|
| 357 |
data = self._NetBIOSSession.recv_packet(self._timeout) |
| 358 |
|
| 359 |
if data.get_trailer().startswith('\xfdSMB'): |
| 360 |
# Packet is encrypted |
| 361 |
transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer()) |
| 362 |
from Crypto.Cipher import AES |
| 363 |
try: |
| 364 |
AES.MODE_CCM |
| 365 |
except: |
| 366 |
LOG.critical("Your pycrypto doesn't support AES.MODE_CCM. Currently only pycrypto experimental supports this mode.\nDownload it from https://www.dlitz.net/software/pycrypto ") |
| 367 |
raise |
| 368 |
cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM, transformHeader['Nonce'][:11]) |
| 369 |
cipher.update(str(transformHeader)[20:]) |
| 370 |
plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):]) |
| 371 |
#cipher.verify(transformHeader['Signature']) |
| 372 |
packet = SMB2Packet(plainText) |
| 373 |
else: |
| 374 |
# In all SMB dialects for a response this field is interpreted as the Status field. |
| 375 |
# This field can be set to any value. For a list of valid status codes, |
| 376 |
# see [MS-ERREF] section 2.3. |
| 377 |
packet = SMB2Packet(data.get_trailer()) |
| 378 |
|
| 379 |
# Loop while we receive pending requests |
| 380 |
if packet['Status'] == STATUS_PENDING: |
| 381 |
status = STATUS_PENDING |
| 382 |
while status == STATUS_PENDING: |
| 383 |
data = self._NetBIOSSession.recv_packet(self._timeout) |
| 384 |
if data.get_trailer().startswith('\xfeSMB'): |
| 385 |
packet = SMB2Packet(data.get_trailer()) |
| 386 |
else: |
| 387 |
# Packet is encrypted |
| 388 |
transformHeader = SMB2_TRANSFORM_HEADER(data.get_trailer()) |
| 389 |
from Crypto.Cipher import AES |
| 390 |
try: |
| 391 |
AES.MODE_CCM |
| 392 |
except: |
| 393 |
LOG.critical("Your pycrypto doesn't support AES.MODE_CCM. Currently only pycrypto experimental supports this mode.\nDownload it from https://www.dlitz.net/software/pycrypto ") |
| 394 |
raise |
| 395 |
cipher = AES.new(self._Session['DecryptionKey'], AES.MODE_CCM, transformHeader['Nonce'][:11]) |
| 396 |
cipher.update(str(transformHeader)[20:]) |
| 397 |
plainText = cipher.decrypt(data.get_trailer()[len(SMB2_TRANSFORM_HEADER()):]) |
| 398 |
#cipher.verify(transformHeader['Signature']) |
| 399 |
packet = SMB2Packet(plainText) |
| 400 |
status = packet['Status'] |
| 401 |
|
| 402 |
if packet['MessageID'] == packetID or packetID is None: |
| 403 |
# if self._Session['SigningRequired'] is True: |
| 404 |
# self.signSMB(packet) |
| 405 |
# Let's update the sequenceWindow based on the CreditsCharged |
| 406 |
self._Connection['SequenceWindow'] += (packet['CreditCharge'] - 1) |
| 407 |
return packet |
| 408 |
else: |
| 409 |
self._Connection['OutstandingResponses'][packet['MessageID']] = packet |
| 410 |
return self.recvSMB(packetID) |
| 411 |
|
| 412 |
def negotiateSession(self, preferredDialect = None): |
| 413 |
packet = self.SMB_PACKET() |
| 414 |
packet['Command'] = SMB2_NEGOTIATE |
| 415 |
negSession = SMB2Negotiate() |
| 416 |
|
| 417 |
negSession['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED |
| 418 |
if self.RequireMessageSigning is True: |
| 419 |
negSession['SecurityMode'] |= SMB2_NEGOTIATE_SIGNING_REQUIRED |
| 420 |
negSession['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION |
| 421 |
negSession['ClientGuid'] = self.ClientGuid |
| 422 |
if preferredDialect is not None: |
| 423 |
negSession['Dialects'] = [preferredDialect] |
| 424 |
else: |
| 425 |
negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30] |
| 426 |
negSession['DialectCount'] = len(negSession['Dialects']) |
| 427 |
packet['Data'] = negSession |
| 428 |
|
| 429 |
# Storing this data for later use |
| 430 |
self._Connection['ClientSecurityMode'] = negSession['SecurityMode'] |
| 431 |
self._Connection['Capabilities'] = negSession['Capabilities'] |
| 432 |
|
| 433 |
packetID = self.sendSMB(packet) |
| 434 |
ans = self.recvSMB(packetID) |
| 435 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 436 |
# ToDo this: |
| 437 |
# If the DialectRevision in the SMB2 NEGOTIATE Response is 0x02FF, the client MUST issue a new |
| 438 |
# SMB2 NEGOTIATE request as described in section 3.2.4.2.2.2 with the only exception |
| 439 |
# that the client MUST allocate sequence number 1 from Connection.SequenceWindow, and MUST set |
| 440 |
# MessageId field of the SMB2 header to 1. Otherwise, the client MUST proceed as follows. |
| 441 |
negResp = SMB2Negotiate_Response(ans['Data']) |
| 442 |
self._Connection['MaxTransactSize'] = min(0x100000,negResp['MaxTransactSize']) |
| 443 |
self._Connection['MaxReadSize'] = min(0x100000,negResp['MaxReadSize']) |
| 444 |
self._Connection['MaxWriteSize'] = min(0x100000,negResp['MaxWriteSize']) |
| 445 |
self._Connection['ServerGuid'] = negResp['ServerGuid'] |
| 446 |
self._Connection['GSSNegotiateToken'] = negResp['Buffer'] |
| 447 |
self._Connection['Dialect'] = negResp['DialectRevision'] |
| 448 |
if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED: |
| 449 |
self._Connection['RequireSigning'] = True |
| 450 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING: |
| 451 |
self._Connection['SupportsFileLeasing'] = True |
| 452 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LARGE_MTU) == SMB2_GLOBAL_CAP_LARGE_MTU: |
| 453 |
self._Connection['SupportsMultiCredit'] = True |
| 454 |
|
| 455 |
if self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 456 |
# Switching to the right packet format |
| 457 |
self.SMB_PACKET = SMB3Packet |
| 458 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) == SMB2_GLOBAL_CAP_DIRECTORY_LEASING: |
| 459 |
self._Connection['SupportsDirectoryLeasing'] = True |
| 460 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_MULTI_CHANNEL) == SMB2_GLOBAL_CAP_MULTI_CHANNEL: |
| 461 |
self._Connection['SupportsMultiChannel'] = True |
| 462 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == SMB2_GLOBAL_CAP_PERSISTENT_HANDLES: |
| 463 |
self._Connection['SupportsPersistentHandles'] = True |
| 464 |
if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION: |
| 465 |
self._Connection['SupportsEncryption'] = True |
| 466 |
|
| 467 |
self._Connection['ServerCapabilities'] = negResp['Capabilities'] |
| 468 |
self._Connection['ServerSecurityMode'] = negResp['SecurityMode'] |
| 469 |
|
| 470 |
def getCredentials(self): |
| 471 |
return ( |
| 472 |
self.__userName, |
| 473 |
self.__password, |
| 474 |
self.__domain, |
| 475 |
self.__lmhash, |
| 476 |
self.__nthash, |
| 477 |
self.__aesKey, |
| 478 |
self.__TGT, |
| 479 |
self.__TGS) |
| 480 |
|
| 481 |
def kerberosLogin(self, user, password, domain = '', lmhash = '', nthash = '', aesKey='', kdcHost = '', TGT=None, TGS=None): |
| 482 |
# If TGT or TGS are specified, they are in the form of: |
| 483 |
# TGS['KDC_REP'] = the response from the server |
| 484 |
# TGS['cipher'] = the cipher used |
| 485 |
# TGS['sessionKey'] = the sessionKey |
| 486 |
# If we have hashes, normalize them |
| 487 |
if lmhash != '' or nthash != '': |
| 488 |
if len(lmhash) % 2: lmhash = '0%s' % lmhash |
| 489 |
if len(nthash) % 2: nthash = '0%s' % nthash |
| 490 |
try: # just in case they were converted already |
| 491 |
lmhash = a2b_hex(lmhash) |
| 492 |
nthash = a2b_hex(nthash) |
| 493 |
except: |
| 494 |
pass |
| 495 |
|
| 496 |
self.__userName = user |
| 497 |
self.__password = password |
| 498 |
self.__domain = domain |
| 499 |
self.__lmhash = lmhash |
| 500 |
self.__nthash = nthash |
| 501 |
self.__kdc = kdcHost |
| 502 |
self.__aesKey = aesKey |
| 503 |
self.__TGT = TGT |
| 504 |
self.__TGS = TGS |
| 505 |
|
| 506 |
sessionSetup = SMB2SessionSetup() |
| 507 |
if self.RequireMessageSigning is True: |
| 508 |
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED |
| 509 |
else: |
| 510 |
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED |
| 511 |
|
| 512 |
sessionSetup['Flags'] = 0 |
| 513 |
#sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS |
| 514 |
|
| 515 |
# Importing down here so pyasn1 is not required if kerberos is not used. |
| 516 |
from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set |
| 517 |
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS |
| 518 |
from impacket.krb5 import constants |
| 519 |
from impacket.krb5.types import Principal, KerberosTime, Ticket |
| 520 |
from pyasn1.codec.der import decoder, encoder |
| 521 |
import datetime |
| 522 |
|
| 523 |
# First of all, we need to get a TGT for the user |
| 524 |
userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value) |
| 525 |
if TGT is None: |
| 526 |
if TGS is None: |
| 527 |
tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost) |
| 528 |
else: |
| 529 |
tgt = TGT['KDC_REP'] |
| 530 |
cipher = TGT['cipher'] |
| 531 |
sessionKey = TGT['sessionKey'] |
| 532 |
|
| 533 |
# Save the ticket |
| 534 |
# If you want, for debugging purposes |
| 535 |
# from impacket.krb5.ccache import CCache |
| 536 |
# ccache = CCache() |
| 537 |
# try: |
| 538 |
# if TGS is None: |
| 539 |
# ccache.fromTGT(tgt, oldSessionKey, sessionKey) |
| 540 |
# else: |
| 541 |
# ccache.fromTGS(TGS['KDC_REP'], TGS['oldSessionKey'], TGS['sessionKey'] ) |
| 542 |
# ccache.saveFile('/tmp/ticket.bin') |
| 543 |
# except Exception, e: |
| 544 |
# print e |
| 545 |
# pass |
| 546 |
|
| 547 |
# Now that we have the TGT, we should ask for a TGS for cifs |
| 548 |
|
| 549 |
if TGS is None: |
| 550 |
serverName = Principal('cifs/%s' % (self._Connection['ServerName']), type=constants.PrincipalNameType.NT_SRV_INST.value) |
| 551 |
tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey) |
| 552 |
else: |
| 553 |
tgs = TGS['KDC_REP'] |
| 554 |
cipher = TGS['cipher'] |
| 555 |
sessionKey = TGS['sessionKey'] |
| 556 |
|
| 557 |
# Let's build a NegTokenInit with a Kerberos REQ_AP |
| 558 |
|
| 559 |
blob = SPNEGO_NegTokenInit() |
| 560 |
|
| 561 |
# Kerberos |
| 562 |
blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']] |
| 563 |
|
| 564 |
# Let's extract the ticket from the TGS |
| 565 |
tgs = decoder.decode(tgs, asn1Spec = TGS_REP())[0] |
| 566 |
ticket = Ticket() |
| 567 |
ticket.from_asn1(tgs['ticket']) |
| 568 |
|
| 569 |
# Now let's build the AP_REQ |
| 570 |
apReq = AP_REQ() |
| 571 |
apReq['pvno'] = 5 |
| 572 |
apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value) |
| 573 |
|
| 574 |
opts = list() |
| 575 |
apReq['ap-options'] = constants.encodeFlags(opts) |
| 576 |
seq_set(apReq,'ticket', ticket.to_asn1) |
| 577 |
|
| 578 |
authenticator = Authenticator() |
| 579 |
authenticator['authenticator-vno'] = 5 |
| 580 |
authenticator['crealm'] = domain |
| 581 |
seq_set(authenticator, 'cname', userName.components_to_asn1) |
| 582 |
now = datetime.datetime.utcnow() |
| 583 |
|
| 584 |
authenticator['cusec'] = now.microsecond |
| 585 |
authenticator['ctime'] = KerberosTime.to_asn1(now) |
| 586 |
|
| 587 |
encodedAuthenticator = encoder.encode(authenticator) |
| 588 |
|
| 589 |
# Key Usage 11 |
| 590 |
# AP-REQ Authenticator (includes application authenticator |
| 591 |
# subkey), encrypted with the application session key |
| 592 |
# (Section 5.5.1) |
| 593 |
encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None) |
| 594 |
|
| 595 |
apReq['authenticator'] = None |
| 596 |
apReq['authenticator']['etype'] = cipher.enctype |
| 597 |
apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator |
| 598 |
|
| 599 |
blob['MechToken'] = encoder.encode(apReq) |
| 600 |
|
| 601 |
sessionSetup['SecurityBufferLength'] = len(blob) |
| 602 |
sessionSetup['Buffer'] = blob.getData() |
| 603 |
|
| 604 |
packet = self.SMB_PACKET() |
| 605 |
packet['Command'] = SMB2_SESSION_SETUP |
| 606 |
packet['Data'] = sessionSetup |
| 607 |
|
| 608 |
packetID = self.sendSMB(packet) |
| 609 |
ans = self.recvSMB(packetID) |
| 610 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 611 |
self._Session['SessionID'] = ans['SessionID'] |
| 612 |
self._Session['SigningRequired'] = self._Connection['RequireSigning'] |
| 613 |
self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash) |
| 614 |
self._Session['Connection'] = self._NetBIOSSession.get_socket() |
| 615 |
|
| 616 |
self._Session['SessionKey'] = sessionKey.contents[:16] |
| 617 |
if self._Session['SigningRequired'] is True and self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 618 |
self._Session['SigningKey'] = crypto.KDF_CounterMode(self._Session['SessionKey'], "SMB2AESCMAC\x00", "SmbSign\x00", 128) |
| 619 |
|
| 620 |
# Calculate the key derivations for dialect 3.0 |
| 621 |
if self._Session['SigningRequired'] is True: |
| 622 |
self._Session['SigningActivated'] = True |
| 623 |
if self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 624 |
self._Session['ApplicationKey'] = crypto.KDF_CounterMode(self._Session['SessionKey'], "SMB2APP\x00", "SmbRpc\x00", 128) |
| 625 |
self._Session['EncryptionKey'] = crypto.KDF_CounterMode(self._Session['SessionKey'], "SMB2AESCCM\x00", "ServerIn \x00", 128) |
| 626 |
self._Session['DecryptionKey'] = crypto.KDF_CounterMode(self._Session['SessionKey'], "SMB2AESCCM\x00", "ServerOut\x00", 128) |
| 627 |
|
| 628 |
return True |
| 629 |
else: |
| 630 |
# We clean the stuff we used in case we want to authenticate again |
| 631 |
# within the same connection |
| 632 |
self._Session['UserCredentials'] = '' |
| 633 |
self._Session['Connection'] = 0 |
| 634 |
self._Session['SessionID'] = 0 |
| 635 |
self._Session['SigningRequired'] = False |
| 636 |
self._Session['SigningKey'] = '' |
| 637 |
self._Session['SessionKey'] = '' |
| 638 |
self._Session['SigningActivated'] = False |
| 639 |
raise |
| 640 |
|
| 641 |
|
| 642 |
def login(self, user, password, domain = '', lmhash = '', nthash = ''): |
| 643 |
# If we have hashes, normalize them |
| 644 |
if lmhash != '' or nthash != '': |
| 645 |
if len(lmhash) % 2: lmhash = '0%s' % lmhash |
| 646 |
if len(nthash) % 2: nthash = '0%s' % nthash |
| 647 |
try: # just in case they were converted already |
| 648 |
lmhash = a2b_hex(lmhash) |
| 649 |
nthash = a2b_hex(nthash) |
| 650 |
except: |
| 651 |
pass |
| 652 |
|
| 653 |
self.__userName = user |
| 654 |
self.__password = password |
| 655 |
self.__domain = domain |
| 656 |
self.__lmhash = lmhash |
| 657 |
self.__nthash = nthash |
| 658 |
self.__aesKey = '' |
| 659 |
self.__TGT = None |
| 660 |
self.__TGS = None |
| 661 |
|
| 662 |
sessionSetup = SMB2SessionSetup() |
| 663 |
if self.RequireMessageSigning is True: |
| 664 |
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_REQUIRED |
| 665 |
else: |
| 666 |
sessionSetup['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED |
| 667 |
|
| 668 |
sessionSetup['Flags'] = 0 |
| 669 |
#sessionSetup['Capabilities'] = SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_DFS |
| 670 |
|
| 671 |
# Let's build a NegTokenInit with the NTLMSSP |
| 672 |
# TODO: In the future we should be able to choose different providers |
| 673 |
|
| 674 |
blob = SPNEGO_NegTokenInit() |
| 675 |
|
| 676 |
# NTLMSSP |
| 677 |
blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] |
| 678 |
auth = ntlm.getNTLMSSPType1('','', self._Connection['RequireSigning']) |
| 679 |
blob['MechToken'] = str(auth) |
| 680 |
|
| 681 |
sessionSetup['SecurityBufferLength'] = len(blob) |
| 682 |
sessionSetup['Buffer'] = blob.getData() |
| 683 |
|
| 684 |
# ToDo: |
| 685 |
# If this authentication is for establishing an alternative channel for an existing Session, as specified |
| 686 |
# in section 3.2.4.1.7, the client MUST also set the following values: |
| 687 |
# The SessionId field in the SMB2 header MUST be set to the Session.SessionId for the new |
| 688 |
# channel being established. |
| 689 |
# The SMB2_SESSION_FLAG_BINDING bit MUST be set in the Flags field. |
| 690 |
# The PreviousSessionId field MUST be set to zero. |
| 691 |
|
| 692 |
packet = self.SMB_PACKET() |
| 693 |
packet['Command'] = SMB2_SESSION_SETUP |
| 694 |
packet['Data'] = sessionSetup |
| 695 |
|
| 696 |
packetID = self.sendSMB(packet) |
| 697 |
ans = self.recvSMB(packetID) |
| 698 |
if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED): |
| 699 |
self._Session['SessionID'] = ans['SessionID'] |
| 700 |
self._Session['SigningRequired'] = self._Connection['RequireSigning'] |
| 701 |
self._Session['UserCredentials'] = (user, password, domain, lmhash, nthash) |
| 702 |
self._Session['Connection'] = self._NetBIOSSession.get_socket() |
| 703 |
sessionSetupResponse = SMB2SessionSetup_Response(ans['Data']) |
| 704 |
respToken = SPNEGO_NegTokenResp(sessionSetupResponse['Buffer']) |
| 705 |
|
| 706 |
# Let's parse some data and keep it to ourselves in case it is asked |
| 707 |
ntlmChallenge = ntlm.NTLMAuthChallenge(respToken['ResponseToken']) |
| 708 |
if ntlmChallenge['TargetInfoFields_len'] > 0: |
| 709 |
av_pairs = ntlm.AV_PAIRS(ntlmChallenge['TargetInfoFields'][:ntlmChallenge['TargetInfoFields_len']]) |
| 710 |
if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None: |
| 711 |
try: |
| 712 |
self._Session['ServerName'] = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le') |
| 713 |
except: |
| 714 |
# For some reason, we couldn't decode Unicode here.. silently discard the operation |
| 715 |
pass |
| 716 |
if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None: |
| 717 |
try: |
| 718 |
if self._Session['ServerName'] != av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le'): |
| 719 |
self._Session['ServerDomain'] = av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le') |
| 720 |
except: |
| 721 |
# For some reason, we couldn't decode Unicode here.. silently discard the operation |
| 722 |
pass |
| 723 |
if av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] is not None: |
| 724 |
try: |
| 725 |
self._Session['ServerDNSDomainName'] = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME][1].decode('utf-16le') |
| 726 |
except: |
| 727 |
# For some reason, we couldn't decode Unicode here.. silently discard the operation |
| 728 |
pass |
| 729 |
|
| 730 |
# Parse Version to know the target Operating system name. Not provided elsewhere anymore |
| 731 |
if 'Version' in ntlmChallenge.fields: |
| 732 |
version = ntlmChallenge['Version'] |
| 733 |
|
| 734 |
if len(version) >= 4: |
| 735 |
self._Session['ServerOS'] = "Windows %d.%d Build %d" % (ord(version[0]), ord(version[1]), struct.unpack('<H',version[2:4])[0]) |
| 736 |
self._Session["ServerOSMajor"] = ord(version[0]) |
| 737 |
self._Session["ServerOSMinor"] = ord(version[1]) |
| 738 |
self._Session["ServerOSBuild"] = struct.unpack('<H',version[2:4])[0] |
| 739 |
|
| 740 |
type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, respToken['ResponseToken'], user, password, domain, lmhash, nthash) |
| 741 |
|
| 742 |
if exportedSessionKey is not None: |
| 743 |
self._Session['SessionKey'] = exportedSessionKey |
| 744 |
if self._Session['SigningRequired'] is True and self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 745 |
self._Session['SigningKey'] = crypto.KDF_CounterMode(exportedSessionKey, "SMB2AESCMAC\x00", "SmbSign\x00", 128) |
| 746 |
|
| 747 |
respToken2 = SPNEGO_NegTokenResp() |
| 748 |
respToken2['ResponseToken'] = str(type3) |
| 749 |
|
| 750 |
# Reusing the previous structure |
| 751 |
sessionSetup['SecurityBufferLength'] = len(respToken2) |
| 752 |
sessionSetup['Buffer'] = respToken2.getData() |
| 753 |
|
| 754 |
packetID = self.sendSMB(packet) |
| 755 |
packet = self.recvSMB(packetID) |
| 756 |
try: |
| 757 |
if packet.isValidAnswer(STATUS_SUCCESS): |
| 758 |
sessionSetupResponse = SMB2SessionSetup_Response(packet['Data']) |
| 759 |
self._Session['SessionFlags'] = sessionSetupResponse['SessionFlags'] |
| 760 |
|
| 761 |
# Calculate the key derivations for dialect 3.0 |
| 762 |
if self._Session['SigningRequired'] is True: |
| 763 |
self._Session['SigningActivated'] = True |
| 764 |
if self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 765 |
self._Session['ApplicationKey'] = crypto.KDF_CounterMode(exportedSessionKey, "SMB2APP\x00", "SmbRpc\x00", 128) |
| 766 |
self._Session['EncryptionKey'] = crypto.KDF_CounterMode(exportedSessionKey, "SMB2AESCCM\x00", "ServerIn \x00", 128) |
| 767 |
self._Session['DecryptionKey'] = crypto.KDF_CounterMode(exportedSessionKey, "SMB2AESCCM\x00", "ServerOut\x00", 128) |
| 768 |
|
| 769 |
return True |
| 770 |
except: |
| 771 |
# We clean the stuff we used in case we want to authenticate again |
| 772 |
# within the same connection |
| 773 |
self._Session['UserCredentials'] = '' |
| 774 |
self._Session['Connection'] = 0 |
| 775 |
self._Session['SessionID'] = 0 |
| 776 |
self._Session['SigningRequired'] = False |
| 777 |
self._Session['SigningKey'] = '' |
| 778 |
self._Session['SessionKey'] = '' |
| 779 |
self._Session['SigningActivated'] = False |
| 780 |
raise |
| 781 |
|
| 782 |
def connectTree(self, share): |
| 783 |
|
| 784 |
# Just in case this came with the full path (maybe an SMB1 client), let's just leave |
| 785 |
# the sharename, we'll take care of the rest |
| 786 |
|
| 787 |
#print self._Session['TreeConnectTable'] |
| 788 |
share = share.split('\\')[-1] |
| 789 |
if share in self._Session['TreeConnectTable']: |
| 790 |
# Already connected, no need to reconnect |
| 791 |
treeEntry = self._Session['TreeConnectTable'][share] |
| 792 |
treeEntry['NumberOfUses'] += 1 |
| 793 |
self._Session['TreeConnectTable'][treeEntry['TreeConnectId']]['NumberOfUses'] += 1 |
| 794 |
return treeEntry['TreeConnectId'] |
| 795 |
|
| 796 |
#path = share |
| 797 |
try: |
| 798 |
_, _, _, _, sockaddr = socket.getaddrinfo(self._Connection['ServerIP'], 80, 0, 0, socket.IPPROTO_TCP)[0] |
| 799 |
remoteHost = sockaddr[0] |
| 800 |
except: |
| 801 |
remoteHost = self._Connection['ServerIP'] |
| 802 |
path = '\\\\' + remoteHost + '\\' +share |
| 803 |
|
| 804 |
treeConnect = SMB2TreeConnect() |
| 805 |
treeConnect['Buffer'] = path.encode('utf-16le') |
| 806 |
treeConnect['PathLength'] = len(path)*2 |
| 807 |
|
| 808 |
packet = self.SMB_PACKET() |
| 809 |
packet['Command'] = SMB2_TREE_CONNECT |
| 810 |
packet['Data'] = treeConnect |
| 811 |
packetID = self.sendSMB(packet) |
| 812 |
packet = self.recvSMB(packetID) |
| 813 |
if packet.isValidAnswer(STATUS_SUCCESS): |
| 814 |
treeConnectResponse = SMB2TreeConnect_Response(packet['Data']) |
| 815 |
treeEntry = copy.deepcopy(TREE_CONNECT) |
| 816 |
treeEntry['ShareName'] = share |
| 817 |
treeEntry['TreeConnectId'] = packet['TreeID'] |
| 818 |
treeEntry['Session'] = packet['SessionID'] |
| 819 |
treeEntry['NumberOfUses'] += 1 |
| 820 |
if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_DFS) == SMB2_SHARE_CAP_DFS: |
| 821 |
treeEntry['IsDfsShare'] = True |
| 822 |
if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY) == SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY: |
| 823 |
treeEntry['IsCAShare'] = True |
| 824 |
|
| 825 |
if self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 826 |
if (self._Connection['SupportsEncryption'] is True) and ((treeConnectResponse['ShareFlags'] & SMB2_SHAREFLAG_ENCRYPT_DATA) == SMB2_SHAREFLAG_ENCRYPT_DATA): |
| 827 |
treeEntry['EncryptData'] = True |
| 828 |
# ToDo: This and what follows |
| 829 |
# If Session.EncryptData is FALSE, the client MUST then generate an encryption key, a |
| 830 |
# decryption key as specified in section 3.1.4.2, by providing the following inputs and store |
| 831 |
# them in Session.EncryptionKey and Session.DecryptionKey: |
| 832 |
if (treeConnectResponse['Capabilities'] & SMB2_SHARE_CAP_SCALEOUT) == SMB2_SHARE_CAP_SCALEOUT: |
| 833 |
treeEntry['IsScaleoutShare'] = True |
| 834 |
|
| 835 |
self._Session['TreeConnectTable'][packet['TreeID']] = treeEntry |
| 836 |
self._Session['TreeConnectTable'][share] = treeEntry |
| 837 |
|
| 838 |
return packet['TreeID'] |
| 839 |
|
| 840 |
def disconnectTree(self, treeId): |
| 841 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 842 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 843 |
|
| 844 |
if treeId in self._Session['TreeConnectTable']: |
| 845 |
# More than 1 use? descrease it and return, if not, send the packet |
| 846 |
if self._Session['TreeConnectTable'][treeId]['NumberOfUses'] > 1: |
| 847 |
treeEntry = self._Session['TreeConnectTable'][treeId] |
| 848 |
treeEntry['NumberOfUses'] -= 1 |
| 849 |
self._Session['TreeConnectTable'][treeEntry['ShareName']]['NumberOfUses'] -= 1 |
| 850 |
return True |
| 851 |
|
| 852 |
packet = self.SMB_PACKET() |
| 853 |
packet['Command'] = SMB2_TREE_DISCONNECT |
| 854 |
packet['TreeID'] = treeId |
| 855 |
treeDisconnect = SMB2TreeDisconnect() |
| 856 |
packet['Data'] = treeDisconnect |
| 857 |
packetID = self.sendSMB(packet) |
| 858 |
packet = self.recvSMB(packetID) |
| 859 |
if packet.isValidAnswer(STATUS_SUCCESS): |
| 860 |
shareName = self._Session['TreeConnectTable'][treeId]['ShareName'] |
| 861 |
del(self._Session['TreeConnectTable'][shareName]) |
| 862 |
del(self._Session['TreeConnectTable'][treeId]) |
| 863 |
return True |
| 864 |
|
| 865 |
def create(self, treeId, fileName, desiredAccess, shareMode, creationOptions, creationDisposition, fileAttributes, impersonationLevel = SMB2_IL_IMPERSONATION, securityFlags = 0, oplockLevel = SMB2_OPLOCK_LEVEL_NONE, createContexts = None): |
| 866 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 867 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 868 |
|
| 869 |
fileName = string.replace(fileName, '/', '\\') |
| 870 |
if len(fileName) > 0: |
| 871 |
fileName = ntpath.normpath(fileName) |
| 872 |
if fileName[0] == '\\': |
| 873 |
fileName = fileName[1:] |
| 874 |
|
| 875 |
if self._Session['TreeConnectTable'][treeId]['IsDfsShare'] is True: |
| 876 |
pathName = fileName |
| 877 |
else: |
| 878 |
pathName = '\\\\' + self._Connection['ServerName'] + '\\' + fileName |
| 879 |
|
| 880 |
fileEntry = copy.deepcopy(FILE) |
| 881 |
fileEntry['LeaseKey'] = uuid.generate() |
| 882 |
fileEntry['LeaseState'] = SMB2_LEASE_NONE |
| 883 |
self.GlobalFileTable[pathName] = fileEntry |
| 884 |
|
| 885 |
if self._Connection['Dialect'] == SMB2_DIALECT_30 and self._Connection['SupportsDirectoryLeasing'] is True: |
| 886 |
# Is this file NOT on the root directory? |
| 887 |
if len(fileName.split('\\')) > 2: |
| 888 |
parentDir = ntpath.dirname(pathName) |
| 889 |
if parentDir in self.GlobalFileTable: |
| 890 |
LOG.critical("Don't know what to do now! :-o") |
| 891 |
raise |
| 892 |
else: |
| 893 |
parentEntry = copy.deepcopy(FILE) |
| 894 |
parentEntry['LeaseKey'] = uuid.generate() |
| 895 |
parentEntry['LeaseState'] = SMB2_LEASE_NONE |
| 896 |
self.GlobalFileTable[parentDir] = parentEntry |
| 897 |
|
| 898 |
packet = self.SMB_PACKET() |
| 899 |
packet['Command'] = SMB2_CREATE |
| 900 |
packet['TreeID'] = treeId |
| 901 |
if self._Session['TreeConnectTable'][treeId]['IsDfsShare'] is True: |
| 902 |
packet['Flags'] = SMB2_FLAGS_DFS_OPERATIONS |
| 903 |
|
| 904 |
smb2Create = SMB2Create() |
| 905 |
smb2Create['SecurityFlags'] = 0 |
| 906 |
smb2Create['RequestedOplockLevel'] = oplockLevel |
| 907 |
smb2Create['ImpersonationLevel'] = impersonationLevel |
| 908 |
smb2Create['DesiredAccess'] = desiredAccess |
| 909 |
smb2Create['FileAttributes'] = fileAttributes |
| 910 |
smb2Create['ShareAccess'] = shareMode |
| 911 |
smb2Create['CreateDisposition'] = creationDisposition |
| 912 |
smb2Create['CreateOptions'] = creationOptions |
| 913 |
|
| 914 |
smb2Create['NameLength'] = len(fileName)*2 |
| 915 |
if fileName != '': |
| 916 |
smb2Create['Buffer'] = fileName.encode('utf-16le') |
| 917 |
else: |
| 918 |
smb2Create['Buffer'] = '\x00' |
| 919 |
|
| 920 |
if createContexts is not None: |
| 921 |
smb2Create['Buffer'] += createContexts |
| 922 |
smb2Create['CreateContextsOffset'] = len(SMB2Packet()) + SMB2Create.SIZE + smb2Create['NameLength'] |
| 923 |
smb2Create['CreateContextsLength'] = len(createContexts) |
| 924 |
else: |
| 925 |
smb2Create['CreateContextsOffset'] = 0 |
| 926 |
smb2Create['CreateContextsLength'] = 0 |
| 927 |
|
| 928 |
packet['Data'] = smb2Create |
| 929 |
|
| 930 |
packetID = self.sendSMB(packet) |
| 931 |
ans = self.recvSMB(packetID) |
| 932 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 933 |
createResponse = SMB2Create_Response(ans['Data']) |
| 934 |
|
| 935 |
openFile = copy.deepcopy(OPEN) |
| 936 |
openFile['FileID'] = createResponse['FileID'] |
| 937 |
openFile['TreeConnect'] = treeId |
| 938 |
openFile['Oplocklevel'] = oplockLevel |
| 939 |
openFile['Durable'] = False |
| 940 |
openFile['ResilientHandle'] = False |
| 941 |
openFile['LastDisconnectTime'] = 0 |
| 942 |
openFile['FileName'] = pathName |
| 943 |
|
| 944 |
# ToDo: Complete the OperationBuckets |
| 945 |
if self._Connection['Dialect'] == SMB2_DIALECT_30: |
| 946 |
openFile['DesiredAccess'] = oplockLevel |
| 947 |
openFile['ShareMode'] = oplockLevel |
| 948 |
openFile['CreateOptions'] = oplockLevel |
| 949 |
openFile['FileAttributes'] = oplockLevel |
| 950 |
openFile['CreateDisposition'] = oplockLevel |
| 951 |
|
| 952 |
# ToDo: Process the contexts |
| 953 |
self._Session['OpenTable'][str(createResponse['FileID'])] = openFile |
| 954 |
|
| 955 |
# The client MUST generate a handle for the Open, and it MUST |
| 956 |
# return success and the generated handle to the calling application. |
| 957 |
# In our case, str(FileID) |
| 958 |
return str(createResponse['FileID']) |
| 959 |
|
| 960 |
def close(self, treeId, fileId): |
| 961 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 962 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 963 |
if (fileId in self._Session['OpenTable']) is False: |
| 964 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 965 |
|
| 966 |
packet = self.SMB_PACKET() |
| 967 |
packet['Command'] = SMB2_CLOSE |
| 968 |
packet['TreeID'] = treeId |
| 969 |
|
| 970 |
smbClose = SMB2Close() |
| 971 |
smbClose['Flags'] = 0 |
| 972 |
smbClose['FileID'] = fileId |
| 973 |
|
| 974 |
packet['Data'] = smbClose |
| 975 |
|
| 976 |
packetID = self.sendSMB(packet) |
| 977 |
ans = self.recvSMB(packetID) |
| 978 |
|
| 979 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 980 |
del(self.GlobalFileTable[self._Session['OpenTable'][fileId]['FileName']]) |
| 981 |
del(self._Session['OpenTable'][fileId]) |
| 982 |
|
| 983 |
# ToDo Remove stuff from GlobalFileTable |
| 984 |
return True |
| 985 |
|
| 986 |
def read(self, treeId, fileId, offset = 0, bytesToRead = 0, waitAnswer = True): |
| 987 |
# IMPORTANT NOTE: As you can see, this was coded as a recursive function |
| 988 |
# Hence, you can exhaust the memory pretty easy ( large bytesToRead ) |
| 989 |
# This function should NOT be used for reading files directly, but another higher |
| 990 |
# level function should be used that will break the read into smaller pieces |
| 991 |
|
| 992 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 993 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 994 |
if (fileId in self._Session['OpenTable']) is False: |
| 995 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 996 |
|
| 997 |
packet = self.SMB_PACKET() |
| 998 |
packet['Command'] = SMB2_READ |
| 999 |
packet['TreeID'] = treeId |
| 1000 |
|
| 1001 |
if self._Connection['MaxReadSize'] < bytesToRead: |
| 1002 |
maxBytesToRead = self._Connection['MaxReadSize'] |
| 1003 |
else: |
| 1004 |
maxBytesToRead = bytesToRead |
| 1005 |
|
| 1006 |
if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True: |
| 1007 |
packet['CreditCharge'] = ( 1 + (maxBytesToRead - 1) / 65536) |
| 1008 |
else: |
| 1009 |
maxBytesToRead = min(65536,bytesToRead) |
| 1010 |
|
| 1011 |
smbRead = SMB2Read() |
| 1012 |
smbRead['Padding'] = 0x50 |
| 1013 |
smbRead['FileID'] = fileId |
| 1014 |
smbRead['Length'] = maxBytesToRead |
| 1015 |
smbRead['Offset'] = offset |
| 1016 |
packet['Data'] = smbRead |
| 1017 |
|
| 1018 |
packetID = self.sendSMB(packet) |
| 1019 |
ans = self.recvSMB(packetID) |
| 1020 |
|
| 1021 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1022 |
readResponse = SMB2Read_Response(ans['Data']) |
| 1023 |
retData = readResponse['Buffer'] |
| 1024 |
if readResponse['DataRemaining'] > 0: |
| 1025 |
retData += self.read(treeId, fileId, offset+len(retData), readResponse['DataRemaining'], waitAnswer) |
| 1026 |
return retData |
| 1027 |
|
| 1028 |
def write(self, treeId, fileId, data, offset = 0, bytesToWrite = 0, waitAnswer = True): |
| 1029 |
# IMPORTANT NOTE: As you can see, this was coded as a recursive function |
| 1030 |
# Hence, you can exhaust the memory pretty easy ( large bytesToWrite ) |
| 1031 |
# This function should NOT be used for writing directly to files, but another higher |
| 1032 |
# level function should be used that will break the writes into smaller pieces |
| 1033 |
|
| 1034 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1035 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1036 |
if (fileId in self._Session['OpenTable']) is False: |
| 1037 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1038 |
|
| 1039 |
packet = self.SMB_PACKET() |
| 1040 |
packet['Command'] = SMB2_WRITE |
| 1041 |
packet['TreeID'] = treeId |
| 1042 |
|
| 1043 |
if self._Connection['MaxWriteSize'] < bytesToWrite: |
| 1044 |
maxBytesToWrite = self._Connection['MaxWriteSize'] |
| 1045 |
else: |
| 1046 |
maxBytesToWrite = bytesToWrite |
| 1047 |
|
| 1048 |
if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True: |
| 1049 |
packet['CreditCharge'] = ( 1 + (maxBytesToWrite - 1) / 65536) |
| 1050 |
else: |
| 1051 |
maxBytesToWrite = min(65536,bytesToWrite) |
| 1052 |
|
| 1053 |
smbWrite = SMB2Write() |
| 1054 |
smbWrite['FileID'] = fileId |
| 1055 |
smbWrite['Length'] = maxBytesToWrite |
| 1056 |
smbWrite['Offset'] = offset |
| 1057 |
smbWrite['WriteChannelInfoOffset'] = 0 |
| 1058 |
smbWrite['Buffer'] = data[:maxBytesToWrite] |
| 1059 |
packet['Data'] = smbWrite |
| 1060 |
|
| 1061 |
packetID = self.sendSMB(packet) |
| 1062 |
if waitAnswer is True: |
| 1063 |
ans = self.recvSMB(packetID) |
| 1064 |
else: |
| 1065 |
return maxBytesToWrite |
| 1066 |
|
| 1067 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1068 |
writeResponse = SMB2Write_Response(ans['Data']) |
| 1069 |
bytesWritten = writeResponse['Count'] |
| 1070 |
if bytesWritten < bytesToWrite: |
| 1071 |
bytesWritten += self.write(treeId, fileId, data[bytesWritten:], offset+bytesWritten, bytesToWrite-bytesWritten, waitAnswer) |
| 1072 |
return bytesWritten |
| 1073 |
|
| 1074 |
def queryDirectory(self, treeId, fileId, searchString = '*', resumeIndex = 0, informationClass = FILENAMES_INFORMATION, maxBufferSize = None, enumRestart = False, singleEntry = False): |
| 1075 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1076 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1077 |
if (fileId in self._Session['OpenTable']) is False: |
| 1078 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1079 |
|
| 1080 |
packet = self.SMB_PACKET() |
| 1081 |
packet['Command'] = SMB2_QUERY_DIRECTORY |
| 1082 |
packet['TreeID'] = treeId |
| 1083 |
|
| 1084 |
queryDirectory = SMB2QueryDirectory() |
| 1085 |
queryDirectory['FileInformationClass'] = informationClass |
| 1086 |
if resumeIndex != 0 : |
| 1087 |
queryDirectory['Flags'] = SMB2_INDEX_SPECIFIED |
| 1088 |
queryDirectory['FileIndex'] = resumeIndex |
| 1089 |
queryDirectory['FileID'] = fileId |
| 1090 |
if maxBufferSize is None: |
| 1091 |
maxBufferSize = self._Connection['MaxReadSize'] |
| 1092 |
queryDirectory['OutputBufferLength'] = maxBufferSize |
| 1093 |
queryDirectory['FileNameLength'] = len(searchString)*2 |
| 1094 |
queryDirectory['Buffer'] = searchString.encode('utf-16le') |
| 1095 |
|
| 1096 |
packet['Data'] = queryDirectory |
| 1097 |
|
| 1098 |
if self._Connection['Dialect'] != SMB2_DIALECT_002 and self._Connection['SupportsMultiCredit'] is True: |
| 1099 |
packet['CreditCharge'] = ( 1 + (maxBufferSize - 1) / 65536) |
| 1100 |
|
| 1101 |
packetID = self.sendSMB(packet) |
| 1102 |
ans = self.recvSMB(packetID) |
| 1103 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1104 |
queryDirectoryResponse = SMB2QueryDirectory_Response(ans['Data']) |
| 1105 |
return queryDirectoryResponse['Buffer'] |
| 1106 |
|
| 1107 |
def echo(self): |
| 1108 |
packet = self.SMB_PACKET() |
| 1109 |
packet['Command'] = SMB2_ECHO |
| 1110 |
smbEcho = SMB2Echo() |
| 1111 |
packet['Data'] = smbEcho |
| 1112 |
packetID = self.sendSMB(packet) |
| 1113 |
ans = self.recvSMB(packetID) |
| 1114 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1115 |
return True |
| 1116 |
|
| 1117 |
def cancel(self, packetID): |
| 1118 |
packet = self.SMB_PACKET() |
| 1119 |
packet['Command'] = SMB2_CANCEL |
| 1120 |
packet['MessageID'] = packetID |
| 1121 |
|
| 1122 |
smbCancel = SMB2Cancel() |
| 1123 |
|
| 1124 |
packet['Data'] = smbCancel |
| 1125 |
self.sendSMB(packet) |
| 1126 |
|
| 1127 |
def ioctl(self, treeId, fileId = None, ctlCode = -1, flags = 0, inputBlob = '', maxInputResponse = None, maxOutputResponse = None, waitAnswer = 1): |
| 1128 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1129 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1130 |
if fileId is None: |
| 1131 |
fileId = '\xff'*16 |
| 1132 |
else: |
| 1133 |
if (fileId in self._Session['OpenTable']) is False: |
| 1134 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1135 |
|
| 1136 |
packet = self.SMB_PACKET() |
| 1137 |
packet['Command'] = SMB2_IOCTL |
| 1138 |
packet['TreeID'] = treeId |
| 1139 |
|
| 1140 |
smbIoctl = SMB2Ioctl() |
| 1141 |
smbIoctl['FileID'] = fileId |
| 1142 |
smbIoctl['CtlCode'] = ctlCode |
| 1143 |
smbIoctl['MaxInputResponse'] = maxInputResponse |
| 1144 |
smbIoctl['MaxOutputResponse'] = maxOutputResponse |
| 1145 |
smbIoctl['InputCount'] = len(inputBlob) |
| 1146 |
if len(inputBlob) == 0: |
| 1147 |
smbIoctl['InputOffset'] = 0 |
| 1148 |
smbIoctl['Buffer'] = '\x00' |
| 1149 |
else: |
| 1150 |
smbIoctl['Buffer'] = inputBlob |
| 1151 |
smbIoctl['OutputOffset'] = 0 |
| 1152 |
smbIoctl['MaxOutputResponse'] = maxOutputResponse |
| 1153 |
smbIoctl['Flags'] = flags |
| 1154 |
|
| 1155 |
packet['Data'] = smbIoctl |
| 1156 |
|
| 1157 |
packetID = self.sendSMB(packet) |
| 1158 |
|
| 1159 |
if waitAnswer == 0: |
| 1160 |
return True |
| 1161 |
|
| 1162 |
ans = self.recvSMB(packetID) |
| 1163 |
|
| 1164 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1165 |
smbIoctlResponse = SMB2Ioctl_Response(ans['Data']) |
| 1166 |
return smbIoctlResponse['Buffer'] |
| 1167 |
|
| 1168 |
def flush(self,treeId, fileId): |
| 1169 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1170 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1171 |
if (fileId in self._Session['OpenTable']) is False: |
| 1172 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1173 |
|
| 1174 |
packet = self.SMB_PACKET() |
| 1175 |
packet['Command'] = SMB2_FLUSH |
| 1176 |
packet['TreeID'] = treeId |
| 1177 |
|
| 1178 |
smbFlush = SMB2Flush() |
| 1179 |
smbFlush['FileID'] = fileId |
| 1180 |
|
| 1181 |
packet['Data'] = smbFlush |
| 1182 |
|
| 1183 |
packetID = self.sendSMB(packet) |
| 1184 |
ans = self.recvSMB(packetID) |
| 1185 |
|
| 1186 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1187 |
return True |
| 1188 |
|
| 1189 |
def lock(self, treeId, fileId, locks, lockSequence = 0): |
| 1190 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1191 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1192 |
if (fileId in self._Session['OpenTable']) is False: |
| 1193 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1194 |
|
| 1195 |
packet = self.SMB_PACKET() |
| 1196 |
packet['Command'] = SMB2_LOCK |
| 1197 |
packet['TreeID'] = treeId |
| 1198 |
|
| 1199 |
smbLock = SMB2Lock() |
| 1200 |
smbLock['FileID'] = fileId |
| 1201 |
smbLock['LockCount'] = len(locks) |
| 1202 |
smbLock['LockSequence'] = lockSequence |
| 1203 |
smbLock['Locks'] = ''.join(str(x) for x in locks) |
| 1204 |
|
| 1205 |
packet['Data'] = smbLock |
| 1206 |
|
| 1207 |
packetID = self.sendSMB(packet) |
| 1208 |
ans = self.recvSMB(packetID) |
| 1209 |
|
| 1210 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1211 |
smbFlushResponse = SMB2Lock_Response(ans['Data']) |
| 1212 |
return True |
| 1213 |
|
| 1214 |
# ToDo: |
| 1215 |
# If Open.ResilientHandle is TRUE or Connection.SupportsMultiChannel is TRUE, the client MUST |
| 1216 |
# do the following: |
| 1217 |
# The client MUST scan through Open.OperationBuckets and find an element with its Free field |
| 1218 |
# set to TRUE. If no such element could be found, an implementation-specific error MUST be |
| 1219 |
# returned to the application. |
| 1220 |
# Let the zero-based array index of the element chosen above be referred to as BucketIndex, and |
| 1221 |
# let BucketNumber = BucketIndex +1. |
| 1222 |
# Set Open.OperationBuckets[BucketIndex].Free = FALSE |
| 1223 |
# Let the SequenceNumber of the element chosen above be referred to as BucketSequence. |
| 1224 |
# The LockSequence field of the SMB2 lock request MUST be set to (BucketNumber<< 4) + |
| 1225 |
# BucketSequence. |
| 1226 |
# Increment the SequenceNumber of the element chosen above using MOD 16 arithmetic. |
| 1227 |
|
| 1228 |
def logoff(self): |
| 1229 |
packet = self.SMB_PACKET() |
| 1230 |
packet['Command'] = SMB2_LOGOFF |
| 1231 |
|
| 1232 |
smbLogoff = SMB2Logoff() |
| 1233 |
|
| 1234 |
packet['Data'] = smbLogoff |
| 1235 |
|
| 1236 |
packetID = self.sendSMB(packet) |
| 1237 |
ans = self.recvSMB(packetID) |
| 1238 |
|
| 1239 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1240 |
# We clean the stuff we used in case we want to authenticate again |
| 1241 |
# within the same connection |
| 1242 |
self._Session['UserCredentials'] = '' |
| 1243 |
self._Session['Connection'] = 0 |
| 1244 |
self._Session['SessionID'] = 0 |
| 1245 |
self._Session['SigningRequired'] = False |
| 1246 |
self._Session['SigningKey'] = '' |
| 1247 |
self._Session['SessionKey'] = '' |
| 1248 |
self._Session['SigningActivated'] = False |
| 1249 |
return True |
| 1250 |
|
| 1251 |
def queryInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0, flags = 0 ): |
| 1252 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1253 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1254 |
if (fileId in self._Session['OpenTable']) is False: |
| 1255 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1256 |
|
| 1257 |
packet = self.SMB_PACKET() |
| 1258 |
packet['Command'] = SMB2_QUERY_INFO |
| 1259 |
packet['TreeID'] = treeId |
| 1260 |
|
| 1261 |
queryInfo = SMB2QueryInfo() |
| 1262 |
queryInfo['FileID'] = fileId |
| 1263 |
queryInfo['InfoType'] = SMB2_0_INFO_FILE |
| 1264 |
queryInfo['FileInfoClass'] = fileInfoClass |
| 1265 |
queryInfo['OutputBufferLength'] = 65535 |
| 1266 |
queryInfo['AdditionalInformation'] = additionalInformation |
| 1267 |
if len(inputBlob) == 0: |
| 1268 |
queryInfo['InputBufferOffset'] = 0 |
| 1269 |
queryInfo['Buffer'] = '\x00' |
| 1270 |
else: |
| 1271 |
queryInfo['InputBufferLength'] = len(inputBlob) |
| 1272 |
queryInfo['Buffer'] = inputBlob |
| 1273 |
queryInfo['Flags'] = flags |
| 1274 |
|
| 1275 |
packet['Data'] = queryInfo |
| 1276 |
packetID = self.sendSMB(packet) |
| 1277 |
ans = self.recvSMB(packetID) |
| 1278 |
|
| 1279 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1280 |
queryResponse = SMB2QueryInfo_Response(ans['Data']) |
| 1281 |
return queryResponse['Buffer'] |
| 1282 |
|
| 1283 |
def setInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0 ): |
| 1284 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1285 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1286 |
if (fileId in self._Session['OpenTable']) is False: |
| 1287 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1288 |
|
| 1289 |
packet = self.SMB_PACKET() |
| 1290 |
packet['Command'] = SMB2_SET_INFO |
| 1291 |
packet['TreeID'] = treeId |
| 1292 |
|
| 1293 |
setInfo = SMB2SetInfo() |
| 1294 |
setInfo['InfoType'] = SMB2_0_INFO_FILE |
| 1295 |
setInfo['FileInfoClass'] = fileInfoClass |
| 1296 |
setInfo['BufferLength'] = len(inputBlob) |
| 1297 |
setInfo['AdditionalInformation'] = additionalInformation |
| 1298 |
setInfo['FileID'] = fileId |
| 1299 |
setInfo['Buffer'] = inputBlob |
| 1300 |
|
| 1301 |
packet['Data'] = setInfo |
| 1302 |
packetID = self.sendSMB(packet) |
| 1303 |
ans = self.recvSMB(packetID) |
| 1304 |
|
| 1305 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1306 |
return True |
| 1307 |
|
| 1308 |
def getSessionKey(self): |
| 1309 |
if self.getDialect() == SMB2_DIALECT_30: |
| 1310 |
return self._Session['ApplicationKey'] |
| 1311 |
else: |
| 1312 |
return self._Session['SessionKey'] |
| 1313 |
|
| 1314 |
def setSessionKey(self, key): |
| 1315 |
if self.getDialect() == SMB2_DIALECT_30: |
| 1316 |
self._Session['ApplicationKey'] = key |
| 1317 |
else: |
| 1318 |
self._Session['SessionKey'] = key |
| 1319 |
|
| 1320 |
###################################################################### |
| 1321 |
# Higher level functions |
| 1322 |
|
| 1323 |
def rename(self, shareName, oldPath, newPath): |
| 1324 |
oldPath = string.replace(oldPath,'/', '\\') |
| 1325 |
oldPath = ntpath.normpath(oldPath) |
| 1326 |
if len(oldPath) > 0 and oldPath[0] == '\\': |
| 1327 |
oldPath = oldPath[1:] |
| 1328 |
|
| 1329 |
newPath = string.replace(newPath,'/', '\\') |
| 1330 |
newPath = ntpath.normpath(newPath) |
| 1331 |
if len(newPath) > 0 and newPath[0] == '\\': |
| 1332 |
newPath = newPath[1:] |
| 1333 |
|
| 1334 |
treeId = self.connectTree(shareName) |
| 1335 |
fileId = None |
| 1336 |
try: |
| 1337 |
fileId = self.create(treeId, oldPath, MAXIMUM_ALLOWED ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, 0x200020, FILE_OPEN, 0) |
| 1338 |
renameReq = FILE_RENAME_INFORMATION_TYPE_2() |
| 1339 |
renameReq['ReplaceIfExists'] = 1 |
| 1340 |
renameReq['RootDirectory'] = '\x00'*8 |
| 1341 |
renameReq['FileNameLength'] = len(newPath)*2 |
| 1342 |
renameReq['FileName'] = newPath.encode('utf-16le') |
| 1343 |
self.setInfo(treeId, fileId, renameReq, infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_RENAME_INFO) |
| 1344 |
finally: |
| 1345 |
if fileId is not None: |
| 1346 |
self.close(treeId, fileId) |
| 1347 |
self.disconnectTree(treeId) |
| 1348 |
|
| 1349 |
return True |
| 1350 |
|
| 1351 |
def writeFile(self, treeId, fileId, data, offset = 0): |
| 1352 |
finished = False |
| 1353 |
writeOffset = offset |
| 1354 |
while not finished: |
| 1355 |
if len(data) == 0: |
| 1356 |
break |
| 1357 |
writeData = data[:self._Connection['MaxWriteSize']] |
| 1358 |
data = data[self._Connection['MaxWriteSize']:] |
| 1359 |
written = self.write(treeId, fileId, writeData, writeOffset, len(writeData)) |
| 1360 |
writeOffset += written |
| 1361 |
return writeOffset - offset |
| 1362 |
|
| 1363 |
def listPath(self, shareName, path, password = None): |
| 1364 |
# ToDo: Handle situations where share is password protected |
| 1365 |
path = string.replace(path,'/', '\\') |
| 1366 |
path = ntpath.normpath(path) |
| 1367 |
if len(path) > 0 and path[0] == '\\': |
| 1368 |
path = path[1:] |
| 1369 |
|
| 1370 |
treeId = self.connectTree(shareName) |
| 1371 |
|
| 1372 |
fileId = None |
| 1373 |
try: |
| 1374 |
# ToDo, we're assuming it's a directory, we should check what the file type is |
| 1375 |
fileId = self.create(treeId, ntpath.dirname(path), FILE_READ_ATTRIBUTES | FILE_READ_DATA ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN, 0) |
| 1376 |
res = '' |
| 1377 |
files = [] |
| 1378 |
from impacket import smb |
| 1379 |
while True: |
| 1380 |
try: |
| 1381 |
res = self.queryDirectory( treeId, fileId, ntpath.basename(path), maxBufferSize = 65535, informationClass = FILE_FULL_DIRECTORY_INFORMATION ) |
| 1382 |
nextOffset = 1 |
| 1383 |
while nextOffset != 0: |
| 1384 |
fileInfo = smb.SMBFindFileFullDirectoryInfo(smb.SMB.FLAGS2_UNICODE) |
| 1385 |
fileInfo.fromString(res) |
| 1386 |
files.append(smb.SharedFile(fileInfo['CreationTime'],fileInfo['LastAccessTime'],fileInfo['LastChangeTime'],fileInfo['EndOfFile'],fileInfo['AllocationSize'],fileInfo['ExtFileAttributes'],fileInfo['FileName'].decode('utf-16le'), fileInfo['FileName'].decode('utf-16le'))) |
| 1387 |
nextOffset = fileInfo['NextEntryOffset'] |
| 1388 |
res = res[nextOffset:] |
| 1389 |
except SessionError as e: |
| 1390 |
if (e.get_error_code()) != STATUS_NO_MORE_FILES: |
| 1391 |
raise |
| 1392 |
break |
| 1393 |
finally: |
| 1394 |
if fileId is not None: |
| 1395 |
self.close(treeId, fileId) |
| 1396 |
self.disconnectTree(treeId) |
| 1397 |
|
| 1398 |
return files |
| 1399 |
|
| 1400 |
def mkdir(self, shareName, pathName, password = None): |
| 1401 |
# ToDo: Handle situations where share is password protected |
| 1402 |
pathName = string.replace(pathName,'/', '\\') |
| 1403 |
pathName = ntpath.normpath(pathName) |
| 1404 |
if len(pathName) > 0 and pathName[0] == '\\': |
| 1405 |
pathName = pathName[1:] |
| 1406 |
|
| 1407 |
treeId = self.connectTree(shareName) |
| 1408 |
|
| 1409 |
fileId = None |
| 1410 |
try: |
| 1411 |
fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0) |
| 1412 |
finally: |
| 1413 |
if fileId is not None: |
| 1414 |
self.close(treeId, fileId) |
| 1415 |
self.disconnectTree(treeId) |
| 1416 |
|
| 1417 |
return True |
| 1418 |
|
| 1419 |
def rmdir(self, shareName, pathName, password = None): |
| 1420 |
# ToDo: Handle situations where share is password protected |
| 1421 |
pathName = string.replace(pathName,'/', '\\') |
| 1422 |
pathName = ntpath.normpath(pathName) |
| 1423 |
if len(pathName) > 0 and pathName[0] == '\\': |
| 1424 |
pathName = pathName[1:] |
| 1425 |
|
| 1426 |
treeId = self.connectTree(shareName) |
| 1427 |
|
| 1428 |
fileId = None |
| 1429 |
try: |
| 1430 |
fileId = self.create(treeId, pathName, DELETE, FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0) |
| 1431 |
finally: |
| 1432 |
if fileId is not None: |
| 1433 |
self.close(treeId, fileId) |
| 1434 |
self.disconnectTree(treeId) |
| 1435 |
|
| 1436 |
return True |
| 1437 |
|
| 1438 |
def remove(self, shareName, pathName, password = None): |
| 1439 |
# ToDo: Handle situations where share is password protected |
| 1440 |
pathName = string.replace(pathName,'/', '\\') |
| 1441 |
pathName = ntpath.normpath(pathName) |
| 1442 |
if len(pathName) > 0 and pathName[0] == '\\': |
| 1443 |
pathName = pathName[1:] |
| 1444 |
|
| 1445 |
treeId = self.connectTree(shareName) |
| 1446 |
|
| 1447 |
fileId = None |
| 1448 |
try: |
| 1449 |
fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0) |
| 1450 |
finally: |
| 1451 |
if fileId is not None: |
| 1452 |
self.close(treeId, fileId) |
| 1453 |
self.disconnectTree(treeId) |
| 1454 |
|
| 1455 |
return True |
| 1456 |
|
| 1457 |
def retrieveFile(self, shareName, path, callback, mode = FILE_OPEN, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ): |
| 1458 |
# ToDo: Handle situations where share is password protected |
| 1459 |
path = string.replace(path,'/', '\\') |
| 1460 |
path = ntpath.normpath(path) |
| 1461 |
if len(path) > 0 and path[0] == '\\': |
| 1462 |
path = path[1:] |
| 1463 |
|
| 1464 |
treeId = self.connectTree(shareName) |
| 1465 |
fileId = None |
| 1466 |
from impacket import smb |
| 1467 |
try: |
| 1468 |
fileId = self.create(treeId, path, FILE_READ_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0) |
| 1469 |
res = self.queryInfo(treeId, fileId) |
| 1470 |
fileInfo = smb.SMBQueryFileStandardInfo(res) |
| 1471 |
fileSize = fileInfo['EndOfFile'] |
| 1472 |
if (fileSize-offset) < self._Connection['MaxReadSize']: |
| 1473 |
# Skip reading 0 bytes files. |
| 1474 |
if (fileSize-offset) > 0: |
| 1475 |
data = self.read(treeId, fileId, offset, fileSize-offset) |
| 1476 |
callback(data) |
| 1477 |
else: |
| 1478 |
written = 0 |
| 1479 |
toBeRead = fileSize-offset |
| 1480 |
while written < toBeRead: |
| 1481 |
data = self.read(treeId, fileId, offset, self._Connection['MaxReadSize']) |
| 1482 |
written += len(data) |
| 1483 |
offset += len(data) |
| 1484 |
callback(data) |
| 1485 |
finally: |
| 1486 |
if fileId is not None: |
| 1487 |
self.close(treeId, fileId) |
| 1488 |
self.disconnectTree(treeId) |
| 1489 |
|
| 1490 |
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE): |
| 1491 |
# ToDo: Handle situations where share is password protected |
| 1492 |
path = string.replace(path,'/', '\\') |
| 1493 |
path = ntpath.normpath(path) |
| 1494 |
if len(path) > 0 and path[0] == '\\': |
| 1495 |
path = path[1:] |
| 1496 |
|
| 1497 |
treeId = self.connectTree(shareName) |
| 1498 |
fileId = None |
| 1499 |
try: |
| 1500 |
fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0) |
| 1501 |
finished = False |
| 1502 |
writeOffset = offset |
| 1503 |
while not finished: |
| 1504 |
data = callback(self._Connection['MaxWriteSize']) |
| 1505 |
if len(data) == 0: |
| 1506 |
break |
| 1507 |
written = self.write(treeId, fileId, data, writeOffset, len(data)) |
| 1508 |
writeOffset += written |
| 1509 |
finally: |
| 1510 |
if fileId is not None: |
| 1511 |
self.close(treeId, fileId) |
| 1512 |
self.disconnectTree(treeId) |
| 1513 |
|
| 1514 |
def waitNamedPipe(self, treeId, pipename, timeout = 5): |
| 1515 |
pipename = ntpath.basename(pipename) |
| 1516 |
if (treeId in self._Session['TreeConnectTable']) is False: |
| 1517 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1518 |
if len(pipename) > 0xffff: |
| 1519 |
raise SessionError(STATUS_INVALID_PARAMETER) |
| 1520 |
|
| 1521 |
pipeWait = FSCTL_PIPE_WAIT_STRUCTURE() |
| 1522 |
pipeWait['Timeout'] = timeout*100000 |
| 1523 |
pipeWait['NameLength'] = len(pipename)*2 |
| 1524 |
pipeWait['TimeoutSpecified'] = 1 |
| 1525 |
pipeWait['Name'] = pipename.encode('utf-16le') |
| 1526 |
|
| 1527 |
return self.ioctl(treeId, None, FSCTL_PIPE_WAIT,flags=SMB2_0_IOCTL_IS_FSCTL, inputBlob=pipeWait, maxInputResponse = 0, maxOutputResponse=0) |
| 1528 |
|
| 1529 |
def getIOCapabilities(self): |
| 1530 |
res = dict() |
| 1531 |
|
| 1532 |
res['MaxReadSize'] = self._Connection['MaxReadSize'] |
| 1533 |
res['MaxWriteSize'] = self._Connection['MaxWriteSize'] |
| 1534 |
return res |
| 1535 |
|
| 1536 |
|
| 1537 |
###################################################################### |
| 1538 |
# Backward compatibility functions and alias for SMB1 and DCE Transports |
| 1539 |
# NOTE: It is strongly recommended not to use these commands |
| 1540 |
# when implementing new client calls. |
| 1541 |
get_server_name = getServerName |
| 1542 |
get_server_domain = getServerDomain |
| 1543 |
get_server_dns_domain_name = getServerDNSDomainName |
| 1544 |
get_remote_name = getServerName |
| 1545 |
get_remote_host = getServerIP |
| 1546 |
get_server_os = getServerOS |
| 1547 |
get_server_os_major = getServerOSMajor |
| 1548 |
get_server_os_minor = getServerOSMinor |
| 1549 |
get_server_os_build = getServerOSBuild |
| 1550 |
tree_connect_andx = connectTree |
| 1551 |
tree_connect = connectTree |
| 1552 |
connect_tree = connectTree |
| 1553 |
disconnect_tree = disconnectTree |
| 1554 |
set_timeout = setTimeout |
| 1555 |
use_timeout = useTimeout |
| 1556 |
stor_file = storeFile |
| 1557 |
retr_file = retrieveFile |
| 1558 |
list_path = listPath |
| 1559 |
|
| 1560 |
def __del__(self): |
| 1561 |
if self._NetBIOSSession: |
| 1562 |
self._NetBIOSSession.close() |
| 1563 |
|
| 1564 |
|
| 1565 |
def doesSupportNTLMv2(self): |
| 1566 |
# Always true :P |
| 1567 |
return True |
| 1568 |
|
| 1569 |
def is_login_required(self): |
| 1570 |
# Always true :P |
| 1571 |
return True |
| 1572 |
|
| 1573 |
def is_signing_required(self): |
| 1574 |
return self._Session["SigningRequired"] |
| 1575 |
|
| 1576 |
def nt_create_andx(self, treeId, fileName, smb_packet=None, cmd = None): |
| 1577 |
if len(fileName) > 0 and fileName[0] == '\\': |
| 1578 |
fileName = fileName[1:] |
| 1579 |
|
| 1580 |
if cmd is not None: |
| 1581 |
from impacket import smb |
| 1582 |
ntCreate = smb.SMBCommand(data = str(cmd)) |
| 1583 |
params = smb.SMBNtCreateAndX_Parameters(ntCreate['Parameters']) |
| 1584 |
return self.create(treeId, fileName, params['AccessMask'], params['ShareAccess'], |
| 1585 |
params['CreateOptions'], params['Disposition'], params['FileAttributes'], |
| 1586 |
params['Impersonation'], params['SecurityFlags']) |
| 1587 |
|
| 1588 |
else: |
| 1589 |
return self.create(treeId, fileName, |
| 1590 |
FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA | |
| 1591 |
FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | READ_CONTROL, |
| 1592 |
FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_NON_DIRECTORY_FILE, FILE_OPEN, 0 ) |
| 1593 |
|
| 1594 |
def get_socket(self): |
| 1595 |
return self._NetBIOSSession.get_socket() |
| 1596 |
|
| 1597 |
|
| 1598 |
def write_andx(self,tid,fid,data, offset = 0, wait_answer=1, write_pipe_mode = False, smb_packet=None): |
| 1599 |
# ToDo: Handle the custom smb_packet situation |
| 1600 |
return self.write(tid, fid, data, offset, len(data)) |
| 1601 |
|
| 1602 |
def TransactNamedPipe(self, tid, fid, data, noAnswer = 0, waitAnswer = 1, offset = 0): |
| 1603 |
return self.ioctl(tid, fid, FSCTL_PIPE_TRANSCEIVE, SMB2_0_IOCTL_IS_FSCTL, data, maxOutputResponse = 65535, waitAnswer = noAnswer | waitAnswer) |
| 1604 |
|
| 1605 |
def TransactNamedPipeRecv(self): |
| 1606 |
ans = self.recvSMB() |
| 1607 |
|
| 1608 |
if ans.isValidAnswer(STATUS_SUCCESS): |
| 1609 |
smbIoctlResponse = SMB2Ioctl_Response(ans['Data']) |
| 1610 |
return smbIoctlResponse['Buffer'] |
| 1611 |
|
| 1612 |
|
| 1613 |
def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1, smb_packet=None): |
| 1614 |
# ToDo: Handle the custom smb_packet situation |
| 1615 |
if max_size is None: |
| 1616 |
max_size = self._Connection['MaxReadSize'] |
| 1617 |
return self.read(tid, fid, offset, max_size, wait_answer) |
| 1618 |
|
| 1619 |
def list_shared(self): |
| 1620 |
# In the context of SMB2/3, forget about the old LANMAN, throw NOT IMPLEMENTED |
| 1621 |
raise SessionError(STATUS_NOT_IMPLEMENTED) |
| 1622 |
|
| 1623 |
def open_andx(self, tid, fileName, open_mode, desired_access): |
| 1624 |
# ToDo Return all the attributes of the file |
| 1625 |
if len(fileName) > 0 and fileName[0] == '\\': |
| 1626 |
fileName = fileName[1:] |
| 1627 |
|
| 1628 |
fileId = self.create(tid,fileName,desired_access, open_mode, FILE_NON_DIRECTORY_FILE, open_mode, 0) |
| 1629 |
return fileId, 0, 0, 0, 0, 0, 0, 0, 0 |
| 1630 |
|