| 1 |
# Copyright (c) 2003-2016 CORE Security Technologies |
| 2 |
# |
| 3 |
# This software is provided under under a slightly modified version |
| 4 |
# of the Apache Software License. See the accompanying LICENSE file |
| 5 |
# for more information. |
| 6 |
# |
| 7 |
# Author: Alberto Solino (@agsolino) |
| 8 |
# |
| 9 |
# TODO: |
| 10 |
# [-] Functions should return NT error codes |
| 11 |
# [-] Handling errors in all situations, right now it's just raising exceptions. |
| 12 |
# [*] Standard authentication support |
| 13 |
# [ ] Organize the connectionData stuff |
| 14 |
# [*] Add capability to send a bad user ID if the user is not authenticated, |
| 15 |
# right now you can ask for any command without actually being authenticated |
| 16 |
# [ ] PATH TRAVERSALS EVERYWHERE.. BE WARNED! |
| 17 |
# [ ] Check the credentials.. now we're just letting everybody to log in. |
| 18 |
# [ ] Check error situation (now many places assume the right data is coming) |
| 19 |
# [ ] Implement IPC to the main process so the connectionData is on a single place |
| 20 |
# [ ] Hence.. implement locking |
| 21 |
# estamos en la B |
| 22 |
|
| 23 |
from __future__ import with_statement |
| 24 |
import calendar |
| 25 |
import socket |
| 26 |
import time |
| 27 |
import datetime |
| 28 |
import struct |
| 29 |
try: # Python 3 |
| 30 |
import configparser |
| 31 |
except ImportError: # Python 2 |
| 32 |
import ConfigParser as configparser |
| 33 |
import SocketServer |
| 34 |
import threading |
| 35 |
import logging |
| 36 |
import logging.config |
| 37 |
import ntpath |
| 38 |
import os |
| 39 |
import fnmatch |
| 40 |
import errno |
| 41 |
import sys |
| 42 |
import random |
| 43 |
import shutil |
| 44 |
from binascii import hexlify |
| 45 |
|
| 46 |
# For signing |
| 47 |
from impacket import smb, nmb, ntlm, uuid, LOG |
| 48 |
from impacket import smb3structs as smb2 |
| 49 |
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, MechTypes, SPNEGO_NegTokenResp, ASN1_AID, ASN1_SUPPORTED_MECH |
| 50 |
from impacket.nt_errors import STATUS_NO_MORE_FILES, STATUS_NETWORK_NAME_DELETED, STATUS_INVALID_PARAMETER, \ |
| 51 |
STATUS_FILE_CLOSED, STATUS_MORE_PROCESSING_REQUIRED, STATUS_OBJECT_PATH_NOT_FOUND, STATUS_DIRECTORY_NOT_EMPTY, \ |
| 52 |
STATUS_FILE_IS_A_DIRECTORY, STATUS_NOT_IMPLEMENTED, STATUS_INVALID_HANDLE, STATUS_OBJECT_NAME_COLLISION, \ |
| 53 |
STATUS_NO_SUCH_FILE, STATUS_CANCELLED, STATUS_OBJECT_NAME_NOT_FOUND, STATUS_SUCCESS, STATUS_ACCESS_DENIED, \ |
| 54 |
STATUS_NOT_SUPPORTED, STATUS_INVALID_DEVICE_REQUEST, STATUS_FS_DRIVER_REQUIRED, STATUS_INVALID_INFO_CLASS |
| 55 |
|
| 56 |
# These ones not defined in nt_errors |
| 57 |
STATUS_SMB_BAD_UID = 0x005B0002 |
| 58 |
STATUS_SMB_BAD_TID = 0x00050002 |
| 59 |
|
| 60 |
try: |
| 61 |
unicode # Python 2 |
| 62 |
except NameError: |
| 63 |
unicode = str # Python 3 |
| 64 |
|
| 65 |
|
| 66 |
# Utility functions |
| 67 |
# and general functions. |
| 68 |
# There are some common functions that can be accessed from more than one SMB |
| 69 |
# command (or either TRANSACTION). That's why I'm putting them here |
| 70 |
# TODO: Return NT ERROR Codes |
| 71 |
|
| 72 |
def outputToJohnFormat(challenge, username, domain, lmresponse, ntresponse): |
| 73 |
# We don't want to add a possible failure here, since this is an |
| 74 |
# extra bonus. We try, if it fails, returns nothing |
| 75 |
ret_value = '' |
| 76 |
try: |
| 77 |
if len(ntresponse) > 24: |
| 78 |
# Extended Security - NTLMv2 |
| 79 |
ret_value = {'hash_string':'%s::%s:%s:%s:%s' % (username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(challenge), hexlify(ntresponse)[:32], hexlify(ntresponse)[32:]), 'hash_version':'ntlmv2'} |
| 80 |
else: |
| 81 |
# NTLMv1 |
| 82 |
ret_value = {'hash_string':'%s::%s:%s:%s:%s' % (username.decode('utf-16le'), domain.decode('utf-16le'), hexlify(lmresponse), hexlify(ntresponse), hexlify(challenge)), 'hash_version':'ntlm'} |
| 83 |
except: |
| 84 |
# Let's try w/o decoding Unicode |
| 85 |
try: |
| 86 |
if len(ntresponse) > 24: |
| 87 |
# Extended Security - NTLMv2 |
| 88 |
ret_value = {'hash_string':'%s::%s:%s:%s:%s' % (username, domain, hexlify(challenge), hexlify(ntresponse)[:32], hexlify(ntresponse)[32:]), 'hash_version':'ntlmv2'} |
| 89 |
else: |
| 90 |
# NTLMv1 |
| 91 |
ret_value = {'hash_string':'%s::%s:%s:%s:%s' % (username, domain, hexlify(lmresponse), hexlify(ntresponse), hexlify(challenge)), 'hash_version':'ntlm'} |
| 92 |
except Exception as e: |
| 93 |
LOG.error("outputToJohnFormat: %s" % e) |
| 94 |
pass |
| 95 |
|
| 96 |
return ret_value |
| 97 |
|
| 98 |
def writeJohnOutputToFile(hash_string, hash_version, file_name): |
| 99 |
fn_data = os.path.splitext(file_name) |
| 100 |
if hash_version == "ntlmv2": |
| 101 |
output_filename = fn_data[0] + "_ntlmv2" + fn_data[1] |
| 102 |
else: |
| 103 |
output_filename = fn_data[0] + "_ntlm" + fn_data[1] |
| 104 |
|
| 105 |
with open(output_filename,"a") as f: |
| 106 |
f.write(hash_string) |
| 107 |
f.write('\n') |
| 108 |
|
| 109 |
|
| 110 |
def decodeSMBString( flags, text ): |
| 111 |
if flags & smb.SMB.FLAGS2_UNICODE: |
| 112 |
return text.decode('utf-16le') |
| 113 |
else: |
| 114 |
return text |
| 115 |
|
| 116 |
def encodeSMBString( flags, text ): |
| 117 |
if flags & smb.SMB.FLAGS2_UNICODE: |
| 118 |
return (text).encode('utf-16le') |
| 119 |
else: |
| 120 |
return text |
| 121 |
|
| 122 |
def getFileTime(t): |
| 123 |
t *= 10000000 |
| 124 |
t += 116444736000000000 |
| 125 |
return t |
| 126 |
|
| 127 |
def getUnixTime(t): |
| 128 |
t -= 116444736000000000 |
| 129 |
t /= 10000000 |
| 130 |
return t |
| 131 |
|
| 132 |
def getSMBDate(t): |
| 133 |
# TODO: Fix this :P |
| 134 |
d = datetime.date.fromtimestamp(t) |
| 135 |
year = d.year - 1980 |
| 136 |
ret = (year << 8) + (d.month << 4) + d.day |
| 137 |
return ret |
| 138 |
|
| 139 |
def getSMBTime(t): |
| 140 |
# TODO: Fix this :P |
| 141 |
d = datetime.datetime.fromtimestamp(t) |
| 142 |
return (d.hour << 8) + (d.minute << 4) + d.second |
| 143 |
|
| 144 |
def getShares(connId, smbServer): |
| 145 |
config = smbServer.getServerConfig() |
| 146 |
sections = config.sections() |
| 147 |
# Remove the global one |
| 148 |
del(sections[sections.index('global')]) |
| 149 |
shares = {} |
| 150 |
for i in sections: |
| 151 |
shares[i] = dict(config.items(i)) |
| 152 |
return shares |
| 153 |
|
| 154 |
def searchShare(connId, share, smbServer): |
| 155 |
config = smbServer.getServerConfig() |
| 156 |
if config.has_section(share): |
| 157 |
return dict(config.items(share)) |
| 158 |
else: |
| 159 |
return None |
| 160 |
|
| 161 |
def openFile(path,fileName, accessMode, fileAttributes, openMode): |
| 162 |
fileName = os.path.normpath(fileName.replace('\\','/')) |
| 163 |
errorCode = 0 |
| 164 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 165 |
# strip leading '/' |
| 166 |
fileName = fileName[1:] |
| 167 |
pathName = os.path.join(path,fileName) |
| 168 |
mode = 0 |
| 169 |
# Check the Open Mode |
| 170 |
if openMode & 0x10: |
| 171 |
# If the file does not exist, create it. |
| 172 |
mode = os.O_CREAT |
| 173 |
else: |
| 174 |
# If file does not exist, return an error |
| 175 |
if os.path.exists(pathName) is not True: |
| 176 |
errorCode = STATUS_NO_SUCH_FILE |
| 177 |
return 0,mode, pathName, errorCode |
| 178 |
|
| 179 |
if os.path.isdir(pathName) and (fileAttributes & smb.ATTR_DIRECTORY) == 0: |
| 180 |
# Request to open a normal file and this is actually a directory |
| 181 |
errorCode = STATUS_FILE_IS_A_DIRECTORY |
| 182 |
return 0, mode, pathName, errorCode |
| 183 |
# Check the Access Mode |
| 184 |
if accessMode & 0x7 == 1: |
| 185 |
mode |= os.O_WRONLY |
| 186 |
elif accessMode & 0x7 == 2: |
| 187 |
mode |= os.O_RDWR |
| 188 |
else: |
| 189 |
mode = os.O_RDONLY |
| 190 |
|
| 191 |
try: |
| 192 |
if sys.platform == 'win32': |
| 193 |
mode |= os.O_BINARY |
| 194 |
fid = os.open(pathName, mode) |
| 195 |
except Exception as e: |
| 196 |
LOG.error("openFile: %s,%s" % (pathName, mode) ,e) |
| 197 |
fid = 0 |
| 198 |
errorCode = STATUS_ACCESS_DENIED |
| 199 |
|
| 200 |
return fid, mode, pathName, errorCode |
| 201 |
|
| 202 |
def queryFsInformation(path, filename, level=0): |
| 203 |
|
| 204 |
if isinstance(filename,unicode): |
| 205 |
encoding = 'utf-16le' |
| 206 |
flags = smb.SMB.FLAGS2_UNICODE |
| 207 |
else: |
| 208 |
encoding = 'ascii' |
| 209 |
flags = 0 |
| 210 |
|
| 211 |
fileName = os.path.normpath(filename.replace('\\','/')) |
| 212 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 213 |
# strip leading '/' |
| 214 |
fileName = fileName[1:] |
| 215 |
pathName = os.path.join(path,fileName) |
| 216 |
fileSize = os.path.getsize(pathName) |
| 217 |
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName) |
| 218 |
if level == smb.SMB_QUERY_FS_ATTRIBUTE_INFO or level == smb2.SMB2_FILESYSTEM_ATTRIBUTE_INFO: |
| 219 |
data = smb.SMBQueryFsAttributeInfo() |
| 220 |
data['FileSystemAttributes'] = smb.FILE_CASE_SENSITIVE_SEARCH | smb.FILE_CASE_PRESERVED_NAMES |
| 221 |
data['MaxFilenNameLengthInBytes'] = 255 |
| 222 |
data['LengthOfFileSystemName'] = len('XTFS')*2 |
| 223 |
data['FileSystemName'] = 'XTFS'.encode('utf-16le') |
| 224 |
return data.getData() |
| 225 |
elif level == smb.SMB_INFO_VOLUME: |
| 226 |
data = smb.SMBQueryFsInfoVolume( flags = flags ) |
| 227 |
data['VolumeLabel'] = 'SHARE'.encode(encoding) |
| 228 |
return data.getData() |
| 229 |
elif level == smb.SMB_QUERY_FS_VOLUME_INFO or level == smb2.SMB2_FILESYSTEM_VOLUME_INFO: |
| 230 |
data = smb.SMBQueryFsVolumeInfo() |
| 231 |
data['VolumeLabel'] = '' |
| 232 |
data['VolumeCreationTime'] = getFileTime(ctime) |
| 233 |
return data.getData() |
| 234 |
elif level == smb.SMB_QUERY_FS_SIZE_INFO: |
| 235 |
data = smb.SMBQueryFsSizeInfo() |
| 236 |
return data.getData() |
| 237 |
elif level == smb.FILE_FS_FULL_SIZE_INFORMATION: |
| 238 |
data = smb.SMBFileFsFullSizeInformation() |
| 239 |
return data.getData() |
| 240 |
elif level == smb.FILE_FS_SIZE_INFORMATION: |
| 241 |
data = smb.FileFsSizeInformation() |
| 242 |
return data.getData() |
| 243 |
else: |
| 244 |
lastWriteTime = mtime |
| 245 |
attribs = 0 |
| 246 |
if os.path.isdir(pathName): |
| 247 |
attribs |= smb.SMB_FILE_ATTRIBUTE_DIRECTORY |
| 248 |
if os.path.isfile(pathName): |
| 249 |
attribs |= smb.SMB_FILE_ATTRIBUTE_NORMAL |
| 250 |
fileAttributes = attribs |
| 251 |
return fileSize, lastWriteTime, fileAttributes |
| 252 |
|
| 253 |
def findFirst2(path, fileName, level, searchAttributes, isSMB2 = False): |
| 254 |
# TODO: Depending on the level, this could be done much simpler |
| 255 |
|
| 256 |
#print "FindFirs2 path:%s, filename:%s" % (path, fileName) |
| 257 |
fileName = os.path.normpath(fileName.replace('\\','/')) |
| 258 |
# Let's choose the right encoding depending on the request |
| 259 |
if isinstance(fileName,unicode): |
| 260 |
encoding = 'utf-16le' |
| 261 |
flags = smb.SMB.FLAGS2_UNICODE |
| 262 |
else: |
| 263 |
encoding = 'ascii' |
| 264 |
flags = 0 |
| 265 |
|
| 266 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 267 |
# strip leading '/' |
| 268 |
fileName = fileName[1:] |
| 269 |
|
| 270 |
pathName = os.path.join(path,fileName) |
| 271 |
files = [] |
| 272 |
|
| 273 |
if pathName.find('*') == -1 and pathName.find('?') == -1: |
| 274 |
# No search patterns |
| 275 |
pattern = '' |
| 276 |
else: |
| 277 |
pattern = os.path.basename(pathName) |
| 278 |
dirName = os.path.dirname(pathName) |
| 279 |
|
| 280 |
# Always add . and .. Not that important for Windows, but Samba whines if |
| 281 |
# not present (for * search only) |
| 282 |
if pattern == '*': |
| 283 |
files.append(os.path.join(dirName,'.')) |
| 284 |
files.append(os.path.join(dirName,'..')) |
| 285 |
|
| 286 |
if pattern != '': |
| 287 |
for file in os.listdir(dirName): |
| 288 |
if fnmatch.fnmatch(file.lower(),pattern.lower()): |
| 289 |
entry = os.path.join(dirName, file) |
| 290 |
if os.path.isdir(entry): |
| 291 |
if searchAttributes & smb.ATTR_DIRECTORY: |
| 292 |
files.append(entry) |
| 293 |
else: |
| 294 |
files.append(entry) |
| 295 |
else: |
| 296 |
if os.path.exists(pathName): |
| 297 |
files.append(pathName) |
| 298 |
|
| 299 |
searchResult = [] |
| 300 |
searchCount = len(files) |
| 301 |
errorCode = STATUS_SUCCESS |
| 302 |
|
| 303 |
for i in files: |
| 304 |
if level == smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_BOTH_DIRECTORY_INFO: |
| 305 |
item = smb.SMBFindFileBothDirectoryInfo( flags = flags ) |
| 306 |
elif level == smb.SMB_FIND_FILE_DIRECTORY_INFO or level == smb2.SMB2_FILE_DIRECTORY_INFO: |
| 307 |
item = smb.SMBFindFileDirectoryInfo( flags = flags ) |
| 308 |
elif level == smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO or level == smb2.SMB2_FULL_DIRECTORY_INFO: |
| 309 |
item = smb.SMBFindFileFullDirectoryInfo( flags = flags ) |
| 310 |
elif level == smb.SMB_FIND_INFO_STANDARD: |
| 311 |
item = smb.SMBFindInfoStandard( flags = flags ) |
| 312 |
elif level == smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_FULL_DIRECTORY_INFO: |
| 313 |
item = smb.SMBFindFileIdFullDirectoryInfo( flags = flags ) |
| 314 |
elif level == smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO: |
| 315 |
item = smb.SMBFindFileIdBothDirectoryInfo( flags = flags ) |
| 316 |
elif level == smb.SMB_FIND_FILE_NAMES_INFO or level == smb2.SMB2_FILE_NAMES_INFO: |
| 317 |
item = smb.SMBFindFileNamesInfo( flags = flags ) |
| 318 |
else: |
| 319 |
LOG.error("Wrong level %d!" % level) |
| 320 |
return searchResult, searchCount, STATUS_NOT_SUPPORTED |
| 321 |
|
| 322 |
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(i) |
| 323 |
if os.path.isdir(i): |
| 324 |
item['ExtFileAttributes'] = smb.ATTR_DIRECTORY |
| 325 |
else: |
| 326 |
item['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE |
| 327 |
|
| 328 |
item['FileName'] = os.path.basename(i).encode(encoding) |
| 329 |
|
| 330 |
if level == smb.SMB_FIND_FILE_BOTH_DIRECTORY_INFO or level == smb.SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_ID_BOTH_DIRECTORY_INFO or level == smb2.SMB2_FILE_BOTH_DIRECTORY_INFO: |
| 331 |
item['EaSize'] = 0 |
| 332 |
item['EndOfFile'] = size |
| 333 |
item['AllocationSize'] = size |
| 334 |
item['CreationTime'] = getFileTime(ctime) |
| 335 |
item['LastAccessTime'] = getFileTime(atime) |
| 336 |
item['LastWriteTime'] = getFileTime(mtime) |
| 337 |
item['LastChangeTime'] = getFileTime(mtime) |
| 338 |
item['ShortName'] = '\x00'*24 |
| 339 |
item['FileName'] = os.path.basename(i).encode(encoding) |
| 340 |
padLen = (8-(len(item) % 8)) % 8 |
| 341 |
item['NextEntryOffset'] = len(item) + padLen |
| 342 |
elif level == smb.SMB_FIND_FILE_DIRECTORY_INFO: |
| 343 |
item['EndOfFile'] = size |
| 344 |
item['AllocationSize'] = size |
| 345 |
item['CreationTime'] = getFileTime(ctime) |
| 346 |
item['LastAccessTime'] = getFileTime(atime) |
| 347 |
item['LastWriteTime'] = getFileTime(mtime) |
| 348 |
item['LastChangeTime'] = getFileTime(mtime) |
| 349 |
item['FileName'] = os.path.basename(i).encode(encoding) |
| 350 |
padLen = (8-(len(item) % 8)) % 8 |
| 351 |
item['NextEntryOffset'] = len(item) + padLen |
| 352 |
elif level == smb.SMB_FIND_FILE_FULL_DIRECTORY_INFO or level == smb.SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO or level == smb2.SMB2_FULL_DIRECTORY_INFO: |
| 353 |
item['EaSize'] = 0 |
| 354 |
item['EndOfFile'] = size |
| 355 |
item['AllocationSize'] = size |
| 356 |
item['CreationTime'] = getFileTime(ctime) |
| 357 |
item['LastAccessTime'] = getFileTime(atime) |
| 358 |
item['LastWriteTime'] = getFileTime(mtime) |
| 359 |
item['LastChangeTime'] = getFileTime(mtime) |
| 360 |
padLen = (8-(len(item) % 8)) % 8 |
| 361 |
item['NextEntryOffset'] = len(item) + padLen |
| 362 |
elif level == smb.SMB_FIND_INFO_STANDARD: |
| 363 |
item['EaSize'] = size |
| 364 |
item['CreationDate'] = getSMBDate(ctime) |
| 365 |
item['CreationTime'] = getSMBTime(ctime) |
| 366 |
item['LastAccessDate'] = getSMBDate(atime) |
| 367 |
item['LastAccessTime'] = getSMBTime(atime) |
| 368 |
item['LastWriteDate'] = getSMBDate(mtime) |
| 369 |
item['LastWriteTime'] = getSMBTime(mtime) |
| 370 |
searchResult.append(item) |
| 371 |
|
| 372 |
# No more files |
| 373 |
if (level >= smb.SMB_FIND_FILE_DIRECTORY_INFO or isSMB2 == True) and searchCount > 0: |
| 374 |
searchResult[-1]['NextEntryOffset'] = 0 |
| 375 |
|
| 376 |
return searchResult, searchCount, errorCode |
| 377 |
|
| 378 |
def queryFileInformation(path, filename, level): |
| 379 |
#print "queryFileInfo path: %s, filename: %s, level:0x%x" % (path,filename,level) |
| 380 |
return queryPathInformation(path,filename, level) |
| 381 |
|
| 382 |
def queryPathInformation(path, filename, level): |
| 383 |
# TODO: Depending on the level, this could be done much simpler |
| 384 |
#print "queryPathInfo path: %s, filename: %s, level:0x%x" % (path,filename,level) |
| 385 |
try: |
| 386 |
errorCode = 0 |
| 387 |
fileName = os.path.normpath(filename.replace('\\','/')) |
| 388 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\') and path != '': |
| 389 |
# strip leading '/' |
| 390 |
fileName = fileName[1:] |
| 391 |
pathName = os.path.join(path,fileName) |
| 392 |
if os.path.exists(pathName): |
| 393 |
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName) |
| 394 |
if level == smb.SMB_QUERY_FILE_BASIC_INFO: |
| 395 |
infoRecord = smb.SMBQueryFileBasicInfo() |
| 396 |
infoRecord['CreationTime'] = getFileTime(ctime) |
| 397 |
infoRecord['LastAccessTime'] = getFileTime(atime) |
| 398 |
infoRecord['LastWriteTime'] = getFileTime(mtime) |
| 399 |
infoRecord['LastChangeTime'] = getFileTime(mtime) |
| 400 |
if os.path.isdir(pathName): |
| 401 |
infoRecord['ExtFileAttributes'] = smb.ATTR_DIRECTORY |
| 402 |
else: |
| 403 |
infoRecord['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE |
| 404 |
elif level == smb.SMB_QUERY_FILE_STANDARD_INFO: |
| 405 |
infoRecord = smb.SMBQueryFileStandardInfo() |
| 406 |
infoRecord['AllocationSize'] = size |
| 407 |
infoRecord['EndOfFile'] = size |
| 408 |
if os.path.isdir(pathName): |
| 409 |
infoRecord['Directory'] = 1 |
| 410 |
else: |
| 411 |
infoRecord['Directory'] = 0 |
| 412 |
elif level == smb.SMB_QUERY_FILE_ALL_INFO or level == smb2.SMB2_FILE_ALL_INFO: |
| 413 |
infoRecord = smb.SMBQueryFileAllInfo() |
| 414 |
infoRecord['CreationTime'] = getFileTime(ctime) |
| 415 |
infoRecord['LastAccessTime'] = getFileTime(atime) |
| 416 |
infoRecord['LastWriteTime'] = getFileTime(mtime) |
| 417 |
infoRecord['LastChangeTime'] = getFileTime(mtime) |
| 418 |
if os.path.isdir(pathName): |
| 419 |
infoRecord['ExtFileAttributes'] = smb.ATTR_DIRECTORY |
| 420 |
else: |
| 421 |
infoRecord['ExtFileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE |
| 422 |
infoRecord['AllocationSize'] = size |
| 423 |
infoRecord['EndOfFile'] = size |
| 424 |
if os.path.isdir(pathName): |
| 425 |
infoRecord['Directory'] = 1 |
| 426 |
else: |
| 427 |
infoRecord['Directory'] = 0 |
| 428 |
infoRecord['FileName'] = filename.encode('utf-16le') |
| 429 |
elif level == smb2.SMB2_FILE_NETWORK_OPEN_INFO: |
| 430 |
infoRecord = smb.SMBFileNetworkOpenInfo() |
| 431 |
infoRecord['CreationTime'] = getFileTime(ctime) |
| 432 |
infoRecord['LastAccessTime'] = getFileTime(atime) |
| 433 |
infoRecord['LastWriteTime'] = getFileTime(mtime) |
| 434 |
infoRecord['ChangeTime'] = getFileTime(mtime) |
| 435 |
infoRecord['AllocationSize'] = size |
| 436 |
infoRecord['EndOfFile'] = size |
| 437 |
if os.path.isdir(pathName): |
| 438 |
infoRecord['FileAttributes'] = smb.ATTR_DIRECTORY |
| 439 |
else: |
| 440 |
infoRecord['FileAttributes'] = smb.ATTR_NORMAL | smb.ATTR_ARCHIVE |
| 441 |
elif level == smb.SMB_QUERY_FILE_EA_INFO or level == smb2.SMB2_FILE_EA_INFO: |
| 442 |
infoRecord = smb.SMBQueryFileEaInfo() |
| 443 |
elif level == smb2.SMB2_FILE_STREAM_INFO: |
| 444 |
infoRecord = smb.SMBFileStreamInformation() |
| 445 |
else: |
| 446 |
LOG.error('Unknown level for query path info! 0x%x' % level) |
| 447 |
# UNSUPPORTED |
| 448 |
return None, STATUS_NOT_SUPPORTED |
| 449 |
|
| 450 |
return infoRecord, errorCode |
| 451 |
else: |
| 452 |
# NOT FOUND |
| 453 |
return None, STATUS_OBJECT_NAME_NOT_FOUND |
| 454 |
except Exception as e: |
| 455 |
LOG.error('queryPathInfo: %s' % e) |
| 456 |
raise |
| 457 |
|
| 458 |
def queryDiskInformation(path): |
| 459 |
# TODO: Do something useful here :) |
| 460 |
# For now we just return fake values |
| 461 |
totalUnits = 65535 |
| 462 |
freeUnits = 65535 |
| 463 |
return totalUnits, freeUnits |
| 464 |
|
| 465 |
# Here we implement the NT transaction handlers |
| 466 |
class NTTRANSCommands: |
| 467 |
def default(self, connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 468 |
pass |
| 469 |
|
| 470 |
# Here we implement the NT transaction handlers |
| 471 |
class TRANSCommands: |
| 472 |
@staticmethod |
| 473 |
def lanMan(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 474 |
# Minimal [MS-RAP] implementation, just to return the shares |
| 475 |
connData = smbServer.getConnectionData(connId) |
| 476 |
|
| 477 |
respSetup = '' |
| 478 |
respParameters = '' |
| 479 |
respData = '' |
| 480 |
errorCode = STATUS_SUCCESS |
| 481 |
if struct.unpack('<H',parameters[:2])[0] == 0: |
| 482 |
# NetShareEnum Request |
| 483 |
netShareEnum = smb.SMBNetShareEnum(parameters) |
| 484 |
if netShareEnum['InfoLevel'] == 1: |
| 485 |
shares = getShares(connId, smbServer) |
| 486 |
respParameters = smb.SMBNetShareEnumResponse() |
| 487 |
respParameters['EntriesReturned'] = len(shares) |
| 488 |
respParameters['EntriesAvailable'] = len(shares) |
| 489 |
tailData = '' |
| 490 |
for i in shares: |
| 491 |
# NetShareInfo1 len == 20 |
| 492 |
entry = smb.NetShareInfo1() |
| 493 |
entry['NetworkName'] = i + '\x00'*(13-len(i)) |
| 494 |
entry['Type'] = int(shares[i]['share type']) |
| 495 |
# (beto) If offset == 0 it crashes explorer.exe on windows 7 |
| 496 |
entry['RemarkOffsetLow'] = 20 * len(shares) + len(tailData) |
| 497 |
respData += entry.getData() |
| 498 |
if 'comment' in shares[i]: |
| 499 |
tailData += shares[i]['comment'] + '\x00' |
| 500 |
else: |
| 501 |
tailData += '\x00' |
| 502 |
respData += tailData |
| 503 |
else: |
| 504 |
# We don't support other info levels |
| 505 |
errorCode = STATUS_NOT_SUPPORTED |
| 506 |
elif struct.unpack('<H',parameters[:2])[0] == 13: |
| 507 |
# NetrServerGetInfo Request |
| 508 |
respParameters = smb.SMBNetServerGetInfoResponse() |
| 509 |
netServerInfo = smb.SMBNetServerInfo1() |
| 510 |
netServerInfo['ServerName'] = smbServer.getServerName() |
| 511 |
respData = str(netServerInfo) |
| 512 |
respParameters['TotalBytesAvailable'] = len(respData) |
| 513 |
elif struct.unpack('<H',parameters[:2])[0] == 1: |
| 514 |
# NetrShareGetInfo Request |
| 515 |
request = smb.SMBNetShareGetInfo(parameters) |
| 516 |
respParameters = smb.SMBNetShareGetInfoResponse() |
| 517 |
shares = getShares(connId, smbServer) |
| 518 |
share = shares[request['ShareName'].upper()] |
| 519 |
shareInfo = smb.NetShareInfo1() |
| 520 |
shareInfo['NetworkName'] = request['ShareName'].upper() + '\x00' |
| 521 |
shareInfo['Type'] = int(share['share type']) |
| 522 |
respData = shareInfo.getData() |
| 523 |
if 'comment' in share: |
| 524 |
shareInfo['RemarkOffsetLow'] = len(respData) |
| 525 |
respData += share['comment'] + '\x00' |
| 526 |
respParameters['TotalBytesAvailable'] = len(respData) |
| 527 |
|
| 528 |
else: |
| 529 |
# We don't know how to handle anything else |
| 530 |
errorCode = STATUS_NOT_SUPPORTED |
| 531 |
|
| 532 |
smbServer.setConnectionData(connId, connData) |
| 533 |
|
| 534 |
return respSetup, respParameters, respData, errorCode |
| 535 |
|
| 536 |
@staticmethod |
| 537 |
def transactNamedPipe(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 538 |
connData = smbServer.getConnectionData(connId) |
| 539 |
|
| 540 |
respSetup = '' |
| 541 |
respParameters = '' |
| 542 |
respData = '' |
| 543 |
errorCode = STATUS_SUCCESS |
| 544 |
SMBCommand = smb.SMBCommand(recvPacket['Data'][0]) |
| 545 |
transParameters= smb.SMBTransaction_Parameters(SMBCommand['Parameters']) |
| 546 |
|
| 547 |
# Extract the FID |
| 548 |
fid = struct.unpack('<H', transParameters['Setup'][2:])[0] |
| 549 |
|
| 550 |
if fid in connData['OpenedFiles']: |
| 551 |
fileHandle = connData['OpenedFiles'][fid]['FileHandle'] |
| 552 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 553 |
os.write(fileHandle,data) |
| 554 |
respData = os.read(fileHandle,data) |
| 555 |
else: |
| 556 |
sock = connData['OpenedFiles'][fid]['Socket'] |
| 557 |
sock.send(data) |
| 558 |
respData = sock.recv(maxDataCount) |
| 559 |
else: |
| 560 |
errorCode = STATUS_INVALID_HANDLE |
| 561 |
|
| 562 |
smbServer.setConnectionData(connId, connData) |
| 563 |
|
| 564 |
return respSetup, respParameters, respData, errorCode |
| 565 |
|
| 566 |
# Here we implement the transaction2 handlers |
| 567 |
class TRANS2Commands: |
| 568 |
# All these commands return setup, parameters, data, errorCode |
| 569 |
@staticmethod |
| 570 |
def setPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 571 |
connData = smbServer.getConnectionData(connId) |
| 572 |
|
| 573 |
respSetup = '' |
| 574 |
respParameters = '' |
| 575 |
respData = '' |
| 576 |
errorCode = STATUS_SUCCESS |
| 577 |
setPathInfoParameters = smb.SMBSetPathInformation_Parameters(flags = recvPacket['Flags2'], data = parameters) |
| 578 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 579 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 580 |
fileName = decodeSMBString(recvPacket['Flags2'], setPathInfoParameters['FileName']) |
| 581 |
fileName = os.path.normpath(fileName.replace('\\','/')) |
| 582 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\') and path != '': |
| 583 |
# strip leading '/' |
| 584 |
fileName = fileName[1:] |
| 585 |
pathName = os.path.join(path,fileName) |
| 586 |
if os.path.exists(pathName): |
| 587 |
informationLevel = setPathInfoParameters['InformationLevel'] |
| 588 |
if informationLevel == smb.SMB_SET_FILE_BASIC_INFO: |
| 589 |
infoRecord = smb.SMBSetFileBasicInfo(data) |
| 590 |
# Creation time won't be set, the other ones we play with. |
| 591 |
atime = infoRecord['LastAccessTime'] |
| 592 |
if atime == 0: |
| 593 |
atime = -1 |
| 594 |
else: |
| 595 |
atime = getUnixTime(atime) |
| 596 |
mtime = infoRecord['LastWriteTime'] |
| 597 |
if mtime == 0: |
| 598 |
mtime = -1 |
| 599 |
else: |
| 600 |
mtime = getUnixTime(mtime) |
| 601 |
if mtime != -1 or atime != -1: |
| 602 |
os.utime(pathName,(atime,mtime)) |
| 603 |
else: |
| 604 |
smbServer.log('Unknown level for set path info! 0x%x' % setPathInfoParameters['InformationLevel'], logging.ERROR) |
| 605 |
# UNSUPPORTED |
| 606 |
errorCode = STATUS_NOT_SUPPORTED |
| 607 |
else: |
| 608 |
errorCode = STATUS_OBJECT_NAME_NOT_FOUND |
| 609 |
|
| 610 |
if errorCode == STATUS_SUCCESS: |
| 611 |
respParameters = smb.SMBSetPathInformationResponse_Parameters() |
| 612 |
|
| 613 |
else: |
| 614 |
errorCode = STATUS_SMB_BAD_TID |
| 615 |
|
| 616 |
smbServer.setConnectionData(connId, connData) |
| 617 |
|
| 618 |
return respSetup, respParameters, respData, errorCode |
| 619 |
|
| 620 |
|
| 621 |
@staticmethod |
| 622 |
def setFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 623 |
connData = smbServer.getConnectionData(connId) |
| 624 |
|
| 625 |
respSetup = '' |
| 626 |
respParameters = '' |
| 627 |
respData = '' |
| 628 |
errorCode = STATUS_SUCCESS |
| 629 |
setFileInfoParameters = smb.SMBSetFileInformation_Parameters(parameters) |
| 630 |
|
| 631 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 632 |
if setFileInfoParameters['FID'] in connData['OpenedFiles']: |
| 633 |
fileName = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileName'] |
| 634 |
informationLevel = setFileInfoParameters['InformationLevel'] |
| 635 |
if informationLevel == smb.SMB_SET_FILE_DISPOSITION_INFO: |
| 636 |
infoRecord = smb.SMBSetFileDispositionInfo(parameters) |
| 637 |
if infoRecord['DeletePending'] > 0: |
| 638 |
# Mark this file for removal after closed |
| 639 |
connData['OpenedFiles'][setFileInfoParameters['FID']]['DeleteOnClose'] = True |
| 640 |
respParameters = smb.SMBSetFileInformationResponse_Parameters() |
| 641 |
elif informationLevel == smb.SMB_SET_FILE_BASIC_INFO: |
| 642 |
infoRecord = smb.SMBSetFileBasicInfo(data) |
| 643 |
# Creation time won't be set, the other ones we play with. |
| 644 |
atime = infoRecord['LastAccessTime'] |
| 645 |
if atime == 0: |
| 646 |
atime = -1 |
| 647 |
else: |
| 648 |
atime = getUnixTime(atime) |
| 649 |
mtime = infoRecord['LastWriteTime'] |
| 650 |
if mtime == 0: |
| 651 |
mtime = -1 |
| 652 |
else: |
| 653 |
mtime = getUnixTime(mtime) |
| 654 |
os.utime(fileName,(atime,mtime)) |
| 655 |
elif informationLevel == smb.SMB_SET_FILE_END_OF_FILE_INFO: |
| 656 |
fileHandle = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileHandle'] |
| 657 |
infoRecord = smb.SMBSetFileEndOfFileInfo(data) |
| 658 |
if infoRecord['EndOfFile'] > 0: |
| 659 |
os.lseek(fileHandle, infoRecord['EndOfFile']-1, 0) |
| 660 |
os.write(fileHandle, '\x00') |
| 661 |
else: |
| 662 |
smbServer.log('Unknown level for set file info! 0x%x' % setFileInfoParameters['InformationLevel'], logging.ERROR) |
| 663 |
# UNSUPPORTED |
| 664 |
errorCode = STATUS_NOT_SUPPORTED |
| 665 |
else: |
| 666 |
errorCode = STATUS_NO_SUCH_FILE |
| 667 |
|
| 668 |
if errorCode == STATUS_SUCCESS: |
| 669 |
respParameters = smb.SMBSetFileInformationResponse_Parameters() |
| 670 |
else: |
| 671 |
errorCode = STATUS_SMB_BAD_TID |
| 672 |
|
| 673 |
smbServer.setConnectionData(connId, connData) |
| 674 |
|
| 675 |
return respSetup, respParameters, respData, errorCode |
| 676 |
|
| 677 |
@staticmethod |
| 678 |
def queryFileInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 679 |
connData = smbServer.getConnectionData(connId) |
| 680 |
|
| 681 |
respSetup = '' |
| 682 |
respParameters = '' |
| 683 |
respData = '' |
| 684 |
|
| 685 |
queryFileInfoParameters = smb.SMBQueryFileInformation_Parameters(parameters) |
| 686 |
|
| 687 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 688 |
if queryFileInfoParameters['FID'] in connData['OpenedFiles']: |
| 689 |
fileName = connData['OpenedFiles'][queryFileInfoParameters['FID']]['FileName'] |
| 690 |
|
| 691 |
infoRecord, errorCode = queryFileInformation('', fileName, queryFileInfoParameters['InformationLevel']) |
| 692 |
|
| 693 |
if infoRecord is not None: |
| 694 |
respParameters = smb.SMBQueryFileInformationResponse_Parameters() |
| 695 |
respData = infoRecord |
| 696 |
else: |
| 697 |
errorCode = STATUS_INVALID_HANDLE |
| 698 |
else: |
| 699 |
errorCode = STATUS_SMB_BAD_TID |
| 700 |
|
| 701 |
smbServer.setConnectionData(connId, connData) |
| 702 |
|
| 703 |
return respSetup, respParameters, respData, errorCode |
| 704 |
|
| 705 |
@staticmethod |
| 706 |
def queryPathInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 707 |
connData = smbServer.getConnectionData(connId) |
| 708 |
|
| 709 |
respSetup = '' |
| 710 |
respParameters = '' |
| 711 |
respData = '' |
| 712 |
errorCode = 0 |
| 713 |
|
| 714 |
queryPathInfoParameters = smb.SMBQueryPathInformation_Parameters(flags = recvPacket['Flags2'], data = parameters) |
| 715 |
|
| 716 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 717 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 718 |
try: |
| 719 |
infoRecord, errorCode = queryPathInformation(path, decodeSMBString(recvPacket['Flags2'], queryPathInfoParameters['FileName']), queryPathInfoParameters['InformationLevel']) |
| 720 |
except Exception as e: |
| 721 |
smbServer.log("queryPathInformation: %s" % e,logging.ERROR) |
| 722 |
|
| 723 |
if infoRecord is not None: |
| 724 |
respParameters = smb.SMBQueryPathInformationResponse_Parameters() |
| 725 |
respData = infoRecord |
| 726 |
else: |
| 727 |
errorCode = STATUS_SMB_BAD_TID |
| 728 |
|
| 729 |
smbServer.setConnectionData(connId, connData) |
| 730 |
|
| 731 |
return respSetup, respParameters, respData, errorCode |
| 732 |
|
| 733 |
@staticmethod |
| 734 |
def queryFsInformation(connId, smbServer, recvPacket, parameters, data, maxDataCount = 0): |
| 735 |
connData = smbServer.getConnectionData(connId) |
| 736 |
errorCode = 0 |
| 737 |
# Get the Tid associated |
| 738 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 739 |
data = queryFsInformation(connData['ConnectedShares'][recvPacket['Tid']]['path'], '', struct.unpack('<H',parameters)[0]) |
| 740 |
|
| 741 |
smbServer.setConnectionData(connId, connData) |
| 742 |
|
| 743 |
return '','', data, errorCode |
| 744 |
|
| 745 |
@staticmethod |
| 746 |
def findNext2(connId, smbServer, recvPacket, parameters, data, maxDataCount): |
| 747 |
connData = smbServer.getConnectionData(connId) |
| 748 |
|
| 749 |
respSetup = '' |
| 750 |
respParameters = '' |
| 751 |
respData = '' |
| 752 |
errorCode = STATUS_SUCCESS |
| 753 |
findNext2Parameters = smb.SMBFindNext2_Parameters(flags = recvPacket['Flags2'], data = parameters) |
| 754 |
|
| 755 |
sid = findNext2Parameters['SID'] |
| 756 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 757 |
if sid in connData['SIDs']: |
| 758 |
searchResult = connData['SIDs'][sid] |
| 759 |
respParameters = smb.SMBFindNext2Response_Parameters() |
| 760 |
endOfSearch = 1 |
| 761 |
searchCount = 1 |
| 762 |
totalData = 0 |
| 763 |
for i in enumerate(searchResult): |
| 764 |
data = i[1].getData() |
| 765 |
lenData = len(data) |
| 766 |
if (totalData+lenData) >= maxDataCount or (i[0]+1) >= findNext2Parameters['SearchCount']: |
| 767 |
# We gotta stop here and continue on a find_next2 |
| 768 |
endOfSearch = 0 |
| 769 |
connData['SIDs'][sid] = searchResult[i[0]:] |
| 770 |
respParameters['LastNameOffset'] = totalData |
| 771 |
break |
| 772 |
else: |
| 773 |
searchCount +=1 |
| 774 |
respData += data |
| 775 |
totalData += lenData |
| 776 |
|
| 777 |
# Have we reached the end of the search or still stuff to send? |
| 778 |
if endOfSearch > 0: |
| 779 |
# Let's remove the SID from our ConnData |
| 780 |
del(connData['SIDs'][sid]) |
| 781 |
|
| 782 |
respParameters['EndOfSearch'] = endOfSearch |
| 783 |
respParameters['SearchCount'] = searchCount |
| 784 |
else: |
| 785 |
errorCode = STATUS_INVALID_HANDLE |
| 786 |
else: |
| 787 |
errorCode = STATUS_SMB_BAD_TID |
| 788 |
|
| 789 |
smbServer.setConnectionData(connId, connData) |
| 790 |
|
| 791 |
return respSetup, respParameters, respData, errorCode |
| 792 |
|
| 793 |
@staticmethod |
| 794 |
def findFirst2(connId, smbServer, recvPacket, parameters, data, maxDataCount): |
| 795 |
connData = smbServer.getConnectionData(connId) |
| 796 |
|
| 797 |
respSetup = '' |
| 798 |
respParameters = '' |
| 799 |
respData = '' |
| 800 |
findFirst2Parameters = smb.SMBFindFirst2_Parameters( recvPacket['Flags2'], data = parameters) |
| 801 |
|
| 802 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 803 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 804 |
|
| 805 |
searchResult, searchCount, errorCode = findFirst2(path, |
| 806 |
decodeSMBString( recvPacket['Flags2'], findFirst2Parameters['FileName'] ), |
| 807 |
findFirst2Parameters['InformationLevel'], |
| 808 |
findFirst2Parameters['SearchAttributes'] ) |
| 809 |
|
| 810 |
respParameters = smb.SMBFindFirst2Response_Parameters() |
| 811 |
endOfSearch = 1 |
| 812 |
sid = 0x80 # default SID |
| 813 |
searchCount = 0 |
| 814 |
totalData = 0 |
| 815 |
for i in enumerate(searchResult): |
| 816 |
#i[1].dump() |
| 817 |
data = i[1].getData() |
| 818 |
lenData = len(data) |
| 819 |
if (totalData+lenData) >= maxDataCount or (i[0]+1) > findFirst2Parameters['SearchCount']: |
| 820 |
# We gotta stop here and continue on a find_next2 |
| 821 |
endOfSearch = 0 |
| 822 |
# Simple way to generate a fid |
| 823 |
if len(connData['SIDs']) == 0: |
| 824 |
sid = 1 |
| 825 |
else: |
| 826 |
sid = connData['SIDs'].keys()[-1] + 1 |
| 827 |
# Store the remaining search results in the ConnData SID |
| 828 |
connData['SIDs'][sid] = searchResult[i[0]:] |
| 829 |
respParameters['LastNameOffset'] = totalData |
| 830 |
break |
| 831 |
else: |
| 832 |
searchCount +=1 |
| 833 |
respData += data |
| 834 |
|
| 835 |
padLen = (8-(lenData % 8)) %8 |
| 836 |
respData += '\xaa'*padLen |
| 837 |
totalData += lenData + padLen |
| 838 |
|
| 839 |
respParameters['SID'] = sid |
| 840 |
respParameters['EndOfSearch'] = endOfSearch |
| 841 |
respParameters['SearchCount'] = searchCount |
| 842 |
else: |
| 843 |
errorCode = STATUS_SMB_BAD_TID |
| 844 |
|
| 845 |
smbServer.setConnectionData(connId, connData) |
| 846 |
|
| 847 |
return respSetup, respParameters, respData, errorCode |
| 848 |
|
| 849 |
# Here we implement the commands handlers |
| 850 |
class SMBCommands: |
| 851 |
|
| 852 |
@staticmethod |
| 853 |
def smbTransaction(connId, smbServer, SMBCommand, recvPacket, transCommands): |
| 854 |
connData = smbServer.getConnectionData(connId) |
| 855 |
|
| 856 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 857 |
|
| 858 |
transParameters= smb.SMBTransaction_Parameters(SMBCommand['Parameters']) |
| 859 |
|
| 860 |
# Do the stuff |
| 861 |
if transParameters['ParameterCount'] != transParameters['TotalParameterCount']: |
| 862 |
# TODO: Handle partial parameters |
| 863 |
raise Exception("Unsupported partial parameters in TRANSACT2!") |
| 864 |
else: |
| 865 |
transData = smb.SMBTransaction_SData(flags = recvPacket['Flags2']) |
| 866 |
# Standard says servers shouldn't trust Parameters and Data comes |
| 867 |
# in order, so we have to parse the offsets, ugly |
| 868 |
|
| 869 |
paramCount = transParameters['ParameterCount'] |
| 870 |
transData['Trans_ParametersLength'] = paramCount |
| 871 |
dataCount = transParameters['DataCount'] |
| 872 |
transData['Trans_DataLength'] = dataCount |
| 873 |
transData.fromString(SMBCommand['Data']) |
| 874 |
if transParameters['ParameterOffset'] > 0: |
| 875 |
paramOffset = transParameters['ParameterOffset'] - 63 - transParameters['SetupLength'] |
| 876 |
transData['Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset+paramCount] |
| 877 |
else: |
| 878 |
transData['Trans_Parameters'] = '' |
| 879 |
|
| 880 |
if transParameters['DataOffset'] > 0: |
| 881 |
dataOffset = transParameters['DataOffset'] - 63 - transParameters['SetupLength'] |
| 882 |
transData['Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount] |
| 883 |
else: |
| 884 |
transData['Trans_Data'] = '' |
| 885 |
|
| 886 |
# Call the handler for this TRANSACTION |
| 887 |
if transParameters['SetupCount'] == 0: |
| 888 |
# No subcommand, let's play with the Name |
| 889 |
command = decodeSMBString(recvPacket['Flags2'],transData['Name']) |
| 890 |
else: |
| 891 |
command = struct.unpack('<H', transParameters['Setup'][:2])[0] |
| 892 |
|
| 893 |
if command in transCommands: |
| 894 |
# Call the TRANS subcommand |
| 895 |
setup = '' |
| 896 |
parameters = '' |
| 897 |
data = '' |
| 898 |
try: |
| 899 |
setup, parameters, data, errorCode = transCommands[command](connId, |
| 900 |
smbServer, |
| 901 |
recvPacket, |
| 902 |
transData['Trans_Parameters'], |
| 903 |
transData['Trans_Data'], |
| 904 |
transParameters['MaxDataCount']) |
| 905 |
except Exception as e: |
| 906 |
#print 'Transaction: %s' % e,e |
| 907 |
smbServer.log('Transaction: (%r,%s)' % (command, e), logging.ERROR) |
| 908 |
errorCode = STATUS_ACCESS_DENIED |
| 909 |
#raise |
| 910 |
|
| 911 |
if setup == '' and parameters == '' and data == '': |
| 912 |
# Something wen't wrong |
| 913 |
respParameters = '' |
| 914 |
respData = '' |
| 915 |
else: |
| 916 |
# Build the answer |
| 917 |
data = str(data) |
| 918 |
remainingData = len(data) |
| 919 |
parameters = str(parameters) |
| 920 |
remainingParameters = len(parameters) |
| 921 |
commands = [] |
| 922 |
dataDisplacement = 0 |
| 923 |
while remainingData > 0 or remainingParameters > 0: |
| 924 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 925 |
respParameters = smb.SMBTransactionResponse_Parameters() |
| 926 |
respData = smb.SMBTransaction2Response_Data() |
| 927 |
|
| 928 |
respParameters['TotalParameterCount'] = len(parameters) |
| 929 |
respParameters['ParameterCount'] = len(parameters) |
| 930 |
respData['Trans_ParametersLength'] = len(parameters) |
| 931 |
respParameters['TotalDataCount'] = len(data) |
| 932 |
respParameters['DataDisplacement'] = dataDisplacement |
| 933 |
|
| 934 |
# TODO: Do the same for parameters |
| 935 |
if len(data) > transParameters['MaxDataCount']: |
| 936 |
# Answer doesn't fit in this packet |
| 937 |
LOG.debug("Lowering answer from %d to %d" % (len(data),transParameters['MaxDataCount']) ) |
| 938 |
respParameters['DataCount'] = transParameters['MaxDataCount'] |
| 939 |
else: |
| 940 |
respParameters['DataCount'] = len(data) |
| 941 |
|
| 942 |
respData['Trans_DataLength'] = respParameters['DataCount'] |
| 943 |
respParameters['SetupCount'] = len(setup) |
| 944 |
respParameters['Setup'] = setup |
| 945 |
# TODO: Make sure we're calculating the pad right |
| 946 |
if len(parameters) > 0: |
| 947 |
#padLen = 4 - (55 + len(setup)) % 4 |
| 948 |
padLen = (4 - (55 + len(setup)) % 4 ) % 4 |
| 949 |
padBytes = '\xFF' * padLen |
| 950 |
respData['Pad1'] = padBytes |
| 951 |
respParameters['ParameterOffset'] = 55 + len(setup) + padLen |
| 952 |
else: |
| 953 |
padLen = 0 |
| 954 |
respParameters['ParameterOffset'] = 0 |
| 955 |
respData['Pad1'] = '' |
| 956 |
|
| 957 |
if len(data) > 0: |
| 958 |
#pad2Len = 4 - (55 + len(setup) + padLen + len(parameters)) % 4 |
| 959 |
pad2Len = (4 - (55 + len(setup) + padLen + len(parameters)) % 4) % 4 |
| 960 |
respData['Pad2'] = '\xFF' * pad2Len |
| 961 |
respParameters['DataOffset'] = 55 + len(setup) + padLen + len(parameters) + pad2Len |
| 962 |
else: |
| 963 |
respParameters['DataOffset'] = 0 |
| 964 |
respData['Pad2'] = '' |
| 965 |
|
| 966 |
respData['Trans_Parameters'] = parameters[:respParameters['ParameterCount']] |
| 967 |
respData['Trans_Data'] = data[:respParameters['DataCount']] |
| 968 |
respSMBCommand['Parameters'] = respParameters |
| 969 |
respSMBCommand['Data'] = respData |
| 970 |
|
| 971 |
data = data[respParameters['DataCount']:] |
| 972 |
remainingData -= respParameters['DataCount'] |
| 973 |
dataDisplacement += respParameters['DataCount'] + 1 |
| 974 |
|
| 975 |
parameters = parameters[respParameters['ParameterCount']:] |
| 976 |
remainingParameters -= respParameters['ParameterCount'] |
| 977 |
commands.append(respSMBCommand) |
| 978 |
|
| 979 |
smbServer.setConnectionData(connId, connData) |
| 980 |
return commands, None, errorCode |
| 981 |
|
| 982 |
else: |
| 983 |
smbServer.log("Unsupported Transact command %r" % command, logging.ERROR) |
| 984 |
respParameters = '' |
| 985 |
respData = '' |
| 986 |
errorCode = STATUS_NOT_IMPLEMENTED |
| 987 |
|
| 988 |
respSMBCommand['Parameters'] = respParameters |
| 989 |
respSMBCommand['Data'] = respData |
| 990 |
smbServer.setConnectionData(connId, connData) |
| 991 |
|
| 992 |
return [respSMBCommand], None, errorCode |
| 993 |
|
| 994 |
|
| 995 |
@staticmethod |
| 996 |
def smbNTTransact(connId, smbServer, SMBCommand, recvPacket, transCommands): |
| 997 |
connData = smbServer.getConnectionData(connId) |
| 998 |
|
| 999 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 1000 |
|
| 1001 |
NTTransParameters= smb.SMBNTTransaction_Parameters(SMBCommand['Parameters']) |
| 1002 |
# Do the stuff |
| 1003 |
if NTTransParameters['ParameterCount'] != NTTransParameters['TotalParameterCount']: |
| 1004 |
# TODO: Handle partial parameters |
| 1005 |
raise Exception("Unsupported partial parameters in NTTrans!") |
| 1006 |
else: |
| 1007 |
NTTransData = smb.SMBNTTransaction_Data() |
| 1008 |
# Standard says servers shouldn't trust Parameters and Data comes |
| 1009 |
# in order, so we have to parse the offsets, ugly |
| 1010 |
|
| 1011 |
paramCount = NTTransParameters['ParameterCount'] |
| 1012 |
NTTransData['NT_Trans_ParametersLength'] = paramCount |
| 1013 |
dataCount = NTTransParameters['DataCount'] |
| 1014 |
NTTransData['NT_Trans_DataLength'] = dataCount |
| 1015 |
|
| 1016 |
if NTTransParameters['ParameterOffset'] > 0: |
| 1017 |
paramOffset = NTTransParameters['ParameterOffset'] - 73 - NTTransParameters['SetupLength'] |
| 1018 |
NTTransData['NT_Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset+paramCount] |
| 1019 |
else: |
| 1020 |
NTTransData['NT_Trans_Parameters'] = '' |
| 1021 |
|
| 1022 |
if NTTransParameters['DataOffset'] > 0: |
| 1023 |
dataOffset = NTTransParameters['DataOffset'] - 73 - NTTransParameters['SetupLength'] |
| 1024 |
NTTransData['NT_Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount] |
| 1025 |
else: |
| 1026 |
NTTransData['NT_Trans_Data'] = '' |
| 1027 |
|
| 1028 |
# Call the handler for this TRANSACTION |
| 1029 |
command = NTTransParameters['Function'] |
| 1030 |
if command in transCommands: |
| 1031 |
# Call the NT TRANS subcommand |
| 1032 |
setup = '' |
| 1033 |
parameters = '' |
| 1034 |
data = '' |
| 1035 |
try: |
| 1036 |
setup, parameters, data, errorCode = transCommands[command](connId, |
| 1037 |
smbServer, |
| 1038 |
recvPacket, |
| 1039 |
NTTransData['NT_Trans_Parameters'], |
| 1040 |
NTTransData['NT_Trans_Data'], |
| 1041 |
NTTransParameters['MaxDataCount']) |
| 1042 |
except Exception as e: |
| 1043 |
smbServer.log('NTTransaction: (0x%x,%s)' % (command, e), logging.ERROR) |
| 1044 |
errorCode = STATUS_ACCESS_DENIED |
| 1045 |
#raise |
| 1046 |
|
| 1047 |
if setup == '' and parameters == '' and data == '': |
| 1048 |
# Something wen't wrong |
| 1049 |
respParameters = '' |
| 1050 |
respData = '' |
| 1051 |
if errorCode == STATUS_SUCCESS: |
| 1052 |
errorCode = STATUS_ACCESS_DENIED |
| 1053 |
else: |
| 1054 |
# Build the answer |
| 1055 |
data = str(data) |
| 1056 |
remainingData = len(data) |
| 1057 |
parameters = str(parameters) |
| 1058 |
remainingParameters = len(parameters) |
| 1059 |
commands = [] |
| 1060 |
dataDisplacement = 0 |
| 1061 |
while remainingData > 0 or remainingParameters > 0: |
| 1062 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 1063 |
respParameters = smb.SMBNTTransactionResponse_Parameters() |
| 1064 |
respData = smb.SMBNTTransactionResponse_Data() |
| 1065 |
|
| 1066 |
respParameters['TotalParameterCount'] = len(parameters) |
| 1067 |
respParameters['ParameterCount'] = len(parameters) |
| 1068 |
respData['Trans_ParametersLength'] = len(parameters) |
| 1069 |
respParameters['TotalDataCount'] = len(data) |
| 1070 |
respParameters['DataDisplacement'] = dataDisplacement |
| 1071 |
# TODO: Do the same for parameters |
| 1072 |
if len(data) > NTTransParameters['MaxDataCount']: |
| 1073 |
# Answer doesn't fit in this packet |
| 1074 |
LOG.debug("Lowering answer from %d to %d" % (len(data),NTTransParameters['MaxDataCount']) ) |
| 1075 |
respParameters['DataCount'] = NTTransParameters['MaxDataCount'] |
| 1076 |
else: |
| 1077 |
respParameters['DataCount'] = len(data) |
| 1078 |
|
| 1079 |
respData['NT_Trans_DataLength'] = respParameters['DataCount'] |
| 1080 |
respParameters['SetupCount'] = len(setup) |
| 1081 |
respParameters['Setup'] = setup |
| 1082 |
# TODO: Make sure we're calculating the pad right |
| 1083 |
if len(parameters) > 0: |
| 1084 |
#padLen = 4 - (71 + len(setup)) % 4 |
| 1085 |
padLen = (4 - (73 + len(setup)) % 4 ) % 4 |
| 1086 |
padBytes = '\xFF' * padLen |
| 1087 |
respData['Pad1'] = padBytes |
| 1088 |
respParameters['ParameterOffset'] = 73 + len(setup) + padLen |
| 1089 |
else: |
| 1090 |
padLen = 0 |
| 1091 |
respParameters['ParameterOffset'] = 0 |
| 1092 |
respData['Pad1'] = '' |
| 1093 |
|
| 1094 |
if len(data) > 0: |
| 1095 |
#pad2Len = 4 - (71 + len(setup) + padLen + len(parameters)) % 4 |
| 1096 |
pad2Len = (4 - (73 + len(setup) + padLen + len(parameters)) % 4) % 4 |
| 1097 |
respData['Pad2'] = '\xFF' * pad2Len |
| 1098 |
respParameters['DataOffset'] = 73 + len(setup) + padLen + len(parameters) + pad2Len |
| 1099 |
else: |
| 1100 |
respParameters['DataOffset'] = 0 |
| 1101 |
respData['Pad2'] = '' |
| 1102 |
|
| 1103 |
respData['NT_Trans_Parameters'] = parameters[:respParameters['ParameterCount']] |
| 1104 |
respData['NT_Trans_Data'] = data[:respParameters['DataCount']] |
| 1105 |
respSMBCommand['Parameters'] = respParameters |
| 1106 |
respSMBCommand['Data'] = respData |
| 1107 |
|
| 1108 |
data = data[respParameters['DataCount']:] |
| 1109 |
remainingData -= respParameters['DataCount'] |
| 1110 |
dataDisplacement += respParameters['DataCount'] + 1 |
| 1111 |
|
| 1112 |
parameters = parameters[respParameters['ParameterCount']:] |
| 1113 |
remainingParameters -= respParameters['ParameterCount'] |
| 1114 |
commands.append(respSMBCommand) |
| 1115 |
|
| 1116 |
smbServer.setConnectionData(connId, connData) |
| 1117 |
return commands, None, errorCode |
| 1118 |
|
| 1119 |
else: |
| 1120 |
#smbServer.log("Unsupported NTTransact command 0x%x" % command, logging.ERROR) |
| 1121 |
respParameters = '' |
| 1122 |
respData = '' |
| 1123 |
errorCode = STATUS_NOT_IMPLEMENTED |
| 1124 |
|
| 1125 |
respSMBCommand['Parameters'] = respParameters |
| 1126 |
respSMBCommand['Data'] = respData |
| 1127 |
|
| 1128 |
smbServer.setConnectionData(connId, connData) |
| 1129 |
return [respSMBCommand], None, errorCode |
| 1130 |
|
| 1131 |
|
| 1132 |
@staticmethod |
| 1133 |
def smbTransaction2(connId, smbServer, SMBCommand, recvPacket, transCommands): |
| 1134 |
connData = smbServer.getConnectionData(connId) |
| 1135 |
|
| 1136 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 1137 |
|
| 1138 |
trans2Parameters= smb.SMBTransaction2_Parameters(SMBCommand['Parameters']) |
| 1139 |
|
| 1140 |
# Do the stuff |
| 1141 |
if trans2Parameters['ParameterCount'] != trans2Parameters['TotalParameterCount']: |
| 1142 |
# TODO: Handle partial parameters |
| 1143 |
#print "Unsupported partial parameters in TRANSACT2!" |
| 1144 |
raise Exception("Unsupported partial parameters in TRANSACT2!") |
| 1145 |
else: |
| 1146 |
trans2Data = smb.SMBTransaction2_Data() |
| 1147 |
# Standard says servers shouldn't trust Parameters and Data comes |
| 1148 |
# in order, so we have to parse the offsets, ugly |
| 1149 |
|
| 1150 |
paramCount = trans2Parameters['ParameterCount'] |
| 1151 |
trans2Data['Trans_ParametersLength'] = paramCount |
| 1152 |
dataCount = trans2Parameters['DataCount'] |
| 1153 |
trans2Data['Trans_DataLength'] = dataCount |
| 1154 |
|
| 1155 |
if trans2Parameters['ParameterOffset'] > 0: |
| 1156 |
paramOffset = trans2Parameters['ParameterOffset'] - 63 - trans2Parameters['SetupLength'] |
| 1157 |
trans2Data['Trans_Parameters'] = SMBCommand['Data'][paramOffset:paramOffset+paramCount] |
| 1158 |
else: |
| 1159 |
trans2Data['Trans_Parameters'] = '' |
| 1160 |
|
| 1161 |
if trans2Parameters['DataOffset'] > 0: |
| 1162 |
dataOffset = trans2Parameters['DataOffset'] - 63 - trans2Parameters['SetupLength'] |
| 1163 |
trans2Data['Trans_Data'] = SMBCommand['Data'][dataOffset:dataOffset + dataCount] |
| 1164 |
else: |
| 1165 |
trans2Data['Trans_Data'] = '' |
| 1166 |
|
| 1167 |
# Call the handler for this TRANSACTION |
| 1168 |
command = struct.unpack('<H', trans2Parameters['Setup'])[0] |
| 1169 |
if command in transCommands: |
| 1170 |
# Call the TRANS2 subcommand |
| 1171 |
try: |
| 1172 |
setup, parameters, data, errorCode = transCommands[command](connId, |
| 1173 |
smbServer, |
| 1174 |
recvPacket, |
| 1175 |
trans2Data['Trans_Parameters'], |
| 1176 |
trans2Data['Trans_Data'], |
| 1177 |
trans2Parameters['MaxDataCount']) |
| 1178 |
except Exception as e: |
| 1179 |
smbServer.log('Transaction2: (0x%x,%s)' % (command, e), logging.ERROR) |
| 1180 |
#import traceback |
| 1181 |
#traceback.print_exc() |
| 1182 |
raise |
| 1183 |
|
| 1184 |
if setup == '' and parameters == '' and data == '': |
| 1185 |
# Something wen't wrong |
| 1186 |
respParameters = '' |
| 1187 |
respData = '' |
| 1188 |
else: |
| 1189 |
# Build the answer |
| 1190 |
data = str(data) |
| 1191 |
remainingData = len(data) |
| 1192 |
parameters = str(parameters) |
| 1193 |
remainingParameters = len(parameters) |
| 1194 |
commands = [] |
| 1195 |
dataDisplacement = 0 |
| 1196 |
while remainingData > 0 or remainingParameters > 0: |
| 1197 |
respSMBCommand = smb.SMBCommand(recvPacket['Command']) |
| 1198 |
respParameters = smb.SMBTransaction2Response_Parameters() |
| 1199 |
respData = smb.SMBTransaction2Response_Data() |
| 1200 |
|
| 1201 |
respParameters['TotalParameterCount'] = len(parameters) |
| 1202 |
respParameters['ParameterCount'] = len(parameters) |
| 1203 |
respData['Trans_ParametersLength'] = len(parameters) |
| 1204 |
respParameters['TotalDataCount'] = len(data) |
| 1205 |
respParameters['DataDisplacement'] = dataDisplacement |
| 1206 |
# TODO: Do the same for parameters |
| 1207 |
if len(data) > trans2Parameters['MaxDataCount']: |
| 1208 |
# Answer doesn't fit in this packet |
| 1209 |
LOG.debug("Lowering answer from %d to %d" % (len(data),trans2Parameters['MaxDataCount']) ) |
| 1210 |
respParameters['DataCount'] = trans2Parameters['MaxDataCount'] |
| 1211 |
else: |
| 1212 |
respParameters['DataCount'] = len(data) |
| 1213 |
|
| 1214 |
respData['Trans_DataLength'] = respParameters['DataCount'] |
| 1215 |
respParameters['SetupCount'] = len(setup) |
| 1216 |
respParameters['Setup'] = setup |
| 1217 |
# TODO: Make sure we're calculating the pad right |
| 1218 |
if len(parameters) > 0: |
| 1219 |
#padLen = 4 - (55 + len(setup)) % 4 |
| 1220 |
padLen = (4 - (55 + len(setup)) % 4 ) % 4 |
| 1221 |
padBytes = '\xFF' * padLen |
| 1222 |
respData['Pad1'] = padBytes |
| 1223 |
respParameters['ParameterOffset'] = 55 + len(setup) + padLen |
| 1224 |
else: |
| 1225 |
padLen = 0 |
| 1226 |
respParameters['ParameterOffset'] = 0 |
| 1227 |
respData['Pad1'] = '' |
| 1228 |
|
| 1229 |
if len(data) > 0: |
| 1230 |
#pad2Len = 4 - (55 + len(setup) + padLen + len(parameters)) % 4 |
| 1231 |
pad2Len = (4 - (55 + len(setup) + padLen + len(parameters)) % 4) % 4 |
| 1232 |
respData['Pad2'] = '\xFF' * pad2Len |
| 1233 |
respParameters['DataOffset'] = 55 + len(setup) + padLen + len(parameters) + pad2Len |
| 1234 |
else: |
| 1235 |
respParameters['DataOffset'] = 0 |
| 1236 |
respData['Pad2'] = '' |
| 1237 |
|
| 1238 |
respData['Trans_Parameters'] = parameters[:respParameters['ParameterCount']] |
| 1239 |
respData['Trans_Data'] = data[:respParameters['DataCount']] |
| 1240 |
respSMBCommand['Parameters'] = respParameters |
| 1241 |
respSMBCommand['Data'] = respData |
| 1242 |
|
| 1243 |
data = data[respParameters['DataCount']:] |
| 1244 |
remainingData -= respParameters['DataCount'] |
| 1245 |
dataDisplacement += respParameters['DataCount'] + 1 |
| 1246 |
|
| 1247 |
parameters = parameters[respParameters['ParameterCount']:] |
| 1248 |
remainingParameters -= respParameters['ParameterCount'] |
| 1249 |
commands.append(respSMBCommand) |
| 1250 |
|
| 1251 |
smbServer.setConnectionData(connId, connData) |
| 1252 |
return commands, None, errorCode |
| 1253 |
|
| 1254 |
else: |
| 1255 |
smbServer.log("Unsupported Transact/2 command 0x%x" % command, logging.ERROR) |
| 1256 |
respParameters = '' |
| 1257 |
respData = '' |
| 1258 |
errorCode = STATUS_NOT_IMPLEMENTED |
| 1259 |
|
| 1260 |
respSMBCommand['Parameters'] = respParameters |
| 1261 |
respSMBCommand['Data'] = respData |
| 1262 |
|
| 1263 |
smbServer.setConnectionData(connId, connData) |
| 1264 |
return [respSMBCommand], None, errorCode |
| 1265 |
|
| 1266 |
@staticmethod |
| 1267 |
def smbComLockingAndX(connId, smbServer, SMBCommand, recvPacket): |
| 1268 |
connData = smbServer.getConnectionData(connId) |
| 1269 |
|
| 1270 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_LOCKING_ANDX) |
| 1271 |
respParameters = '' |
| 1272 |
respData = '' |
| 1273 |
|
| 1274 |
# I'm actually doing nothing.. just make MacOS happy ;) |
| 1275 |
errorCode = STATUS_SUCCESS |
| 1276 |
|
| 1277 |
respSMBCommand['Parameters'] = respParameters |
| 1278 |
respSMBCommand['Data'] = respData |
| 1279 |
smbServer.setConnectionData(connId, connData) |
| 1280 |
|
| 1281 |
return [respSMBCommand], None, errorCode |
| 1282 |
|
| 1283 |
|
| 1284 |
@staticmethod |
| 1285 |
def smbComClose(connId, smbServer, SMBCommand, recvPacket): |
| 1286 |
connData = smbServer.getConnectionData(connId) |
| 1287 |
|
| 1288 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_CLOSE) |
| 1289 |
respParameters = '' |
| 1290 |
respData = '' |
| 1291 |
|
| 1292 |
comClose = smb.SMBClose_Parameters(SMBCommand['Parameters']) |
| 1293 |
|
| 1294 |
if comClose['FID'] in connData['OpenedFiles']: |
| 1295 |
errorCode = STATUS_SUCCESS |
| 1296 |
fileHandle = connData['OpenedFiles'][comClose['FID']]['FileHandle'] |
| 1297 |
try: |
| 1298 |
if fileHandle == PIPE_FILE_DESCRIPTOR: |
| 1299 |
connData['OpenedFiles'][comClose['FID']]['Socket'].close() |
| 1300 |
elif fileHandle != VOID_FILE_DESCRIPTOR: |
| 1301 |
os.close(fileHandle) |
| 1302 |
except Exception as e: |
| 1303 |
smbServer.log("comClose %s" % e, logging.ERROR) |
| 1304 |
errorCode = STATUS_ACCESS_DENIED |
| 1305 |
else: |
| 1306 |
# Check if the file was marked for removal |
| 1307 |
if connData['OpenedFiles'][comClose['FID']]['DeleteOnClose'] is True: |
| 1308 |
try: |
| 1309 |
os.remove(connData['OpenedFiles'][comClose['FID']]['FileName']) |
| 1310 |
except Exception as e: |
| 1311 |
smbServer.log("comClose %s" % e, logging.ERROR) |
| 1312 |
errorCode = STATUS_ACCESS_DENIED |
| 1313 |
del(connData['OpenedFiles'][comClose['FID']]) |
| 1314 |
else: |
| 1315 |
errorCode = STATUS_INVALID_HANDLE |
| 1316 |
|
| 1317 |
if errorCode > 0: |
| 1318 |
respParameters = '' |
| 1319 |
respData = '' |
| 1320 |
|
| 1321 |
respSMBCommand['Parameters'] = respParameters |
| 1322 |
respSMBCommand['Data'] = respData |
| 1323 |
smbServer.setConnectionData(connId, connData) |
| 1324 |
|
| 1325 |
return [respSMBCommand], None, errorCode |
| 1326 |
|
| 1327 |
@staticmethod |
| 1328 |
def smbComWrite(connId, smbServer, SMBCommand, recvPacket): |
| 1329 |
connData = smbServer.getConnectionData(connId) |
| 1330 |
|
| 1331 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_WRITE) |
| 1332 |
respParameters = smb.SMBWriteResponse_Parameters() |
| 1333 |
respData = '' |
| 1334 |
|
| 1335 |
comWriteParameters = smb.SMBWrite_Parameters(SMBCommand['Parameters']) |
| 1336 |
comWriteData = smb.SMBWrite_Data(SMBCommand['Data']) |
| 1337 |
|
| 1338 |
if comWriteParameters['Fid'] in connData['OpenedFiles']: |
| 1339 |
fileHandle = connData['OpenedFiles'][comWriteParameters['Fid']]['FileHandle'] |
| 1340 |
errorCode = STATUS_SUCCESS |
| 1341 |
try: |
| 1342 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 1343 |
# TODO: Handle big size files |
| 1344 |
# If we're trying to write past the file end we just skip the write call (Vista does this) |
| 1345 |
if os.lseek(fileHandle, 0, 2) >= comWriteParameters['Offset']: |
| 1346 |
os.lseek(fileHandle,comWriteParameters['Offset'],0) |
| 1347 |
os.write(fileHandle,comWriteData['Data']) |
| 1348 |
else: |
| 1349 |
sock = connData['OpenedFiles'][comWriteParameters['Fid']]['Socket'] |
| 1350 |
sock.send(comWriteData['Data']) |
| 1351 |
respParameters['Count'] = comWriteParameters['Count'] |
| 1352 |
except Exception as e: |
| 1353 |
smbServer.log('smbComWrite: %s' % e, logging.ERROR) |
| 1354 |
errorCode = STATUS_ACCESS_DENIED |
| 1355 |
else: |
| 1356 |
errorCode = STATUS_INVALID_HANDLE |
| 1357 |
|
| 1358 |
|
| 1359 |
if errorCode > 0: |
| 1360 |
respParameters = '' |
| 1361 |
respData = '' |
| 1362 |
|
| 1363 |
respSMBCommand['Parameters'] = respParameters |
| 1364 |
respSMBCommand['Data'] = respData |
| 1365 |
smbServer.setConnectionData(connId, connData) |
| 1366 |
|
| 1367 |
return [respSMBCommand], None, errorCode |
| 1368 |
|
| 1369 |
@staticmethod |
| 1370 |
def smbComFlush(connId, smbServer, SMBCommand,recvPacket ): |
| 1371 |
connData = smbServer.getConnectionData(connId) |
| 1372 |
|
| 1373 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_FLUSH) |
| 1374 |
respParameters = '' |
| 1375 |
respData = '' |
| 1376 |
|
| 1377 |
comFlush = smb.SMBFlush_Parameters(SMBCommand['Parameters']) |
| 1378 |
|
| 1379 |
if comFlush['FID'] in connData['OpenedFiles']: |
| 1380 |
errorCode = STATUS_SUCCESS |
| 1381 |
fileHandle = connData['OpenedFiles'][comFlush['FID']]['FileHandle'] |
| 1382 |
try: |
| 1383 |
os.fsync(fileHandle) |
| 1384 |
except Exception as e: |
| 1385 |
smbServer.log("comFlush %s" % e, logging.ERROR) |
| 1386 |
errorCode = STATUS_ACCESS_DENIED |
| 1387 |
else: |
| 1388 |
errorCode = STATUS_INVALID_HANDLE |
| 1389 |
|
| 1390 |
if errorCode > 0: |
| 1391 |
respParameters = '' |
| 1392 |
respData = '' |
| 1393 |
|
| 1394 |
respSMBCommand['Parameters'] = respParameters |
| 1395 |
respSMBCommand['Data'] = respData |
| 1396 |
smbServer.setConnectionData(connId, connData) |
| 1397 |
|
| 1398 |
return [respSMBCommand], None, errorCode |
| 1399 |
|
| 1400 |
|
| 1401 |
@staticmethod |
| 1402 |
def smbComCreateDirectory(connId, smbServer, SMBCommand,recvPacket ): |
| 1403 |
connData = smbServer.getConnectionData(connId) |
| 1404 |
|
| 1405 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_CREATE_DIRECTORY) |
| 1406 |
respParameters = '' |
| 1407 |
respData = '' |
| 1408 |
|
| 1409 |
comCreateDirectoryData= smb.SMBCreateDirectory_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1410 |
|
| 1411 |
# Get the Tid associated |
| 1412 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1413 |
errorCode = STATUS_SUCCESS |
| 1414 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 1415 |
fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comCreateDirectoryData['DirectoryName']).replace('\\','/')) |
| 1416 |
if len(fileName) > 0: |
| 1417 |
if fileName[0] == '/' or fileName[0] == '\\': |
| 1418 |
# strip leading '/' |
| 1419 |
fileName = fileName[1:] |
| 1420 |
pathName = os.path.join(path,fileName) |
| 1421 |
if os.path.exists(pathName): |
| 1422 |
errorCode = STATUS_OBJECT_NAME_COLLISION |
| 1423 |
|
| 1424 |
# TODO: More checks here in the future.. Specially when we support |
| 1425 |
# user access |
| 1426 |
else: |
| 1427 |
try: |
| 1428 |
os.mkdir(pathName) |
| 1429 |
except Exception as e: |
| 1430 |
smbServer.log("smbComCreateDirectory: %s" % e, logging.ERROR) |
| 1431 |
errorCode = STATUS_ACCESS_DENIED |
| 1432 |
else: |
| 1433 |
errorCode = STATUS_SMB_BAD_TID |
| 1434 |
|
| 1435 |
|
| 1436 |
if errorCode > 0: |
| 1437 |
respParameters = '' |
| 1438 |
respData = '' |
| 1439 |
|
| 1440 |
respSMBCommand['Parameters'] = respParameters |
| 1441 |
respSMBCommand['Data'] = respData |
| 1442 |
smbServer.setConnectionData(connId, connData) |
| 1443 |
|
| 1444 |
return [respSMBCommand], None, errorCode |
| 1445 |
|
| 1446 |
@staticmethod |
| 1447 |
def smbComRename(connId, smbServer, SMBCommand, recvPacket ): |
| 1448 |
connData = smbServer.getConnectionData(connId) |
| 1449 |
|
| 1450 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_RENAME) |
| 1451 |
respParameters = '' |
| 1452 |
respData = '' |
| 1453 |
|
| 1454 |
comRenameData = smb.SMBRename_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1455 |
# Get the Tid associated |
| 1456 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1457 |
errorCode = STATUS_SUCCESS |
| 1458 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 1459 |
oldFileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comRenameData['OldFileName']).replace('\\','/')) |
| 1460 |
newFileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comRenameData['NewFileName']).replace('\\','/')) |
| 1461 |
if len(oldFileName) > 0 and (oldFileName[0] == '/' or oldFileName[0] == '\\'): |
| 1462 |
# strip leading '/' |
| 1463 |
oldFileName = oldFileName[1:] |
| 1464 |
oldPathName = os.path.join(path,oldFileName) |
| 1465 |
if len(newFileName) > 0 and (newFileName[0] == '/' or newFileName[0] == '\\'): |
| 1466 |
# strip leading '/' |
| 1467 |
newFileName = newFileName[1:] |
| 1468 |
newPathName = os.path.join(path,newFileName) |
| 1469 |
|
| 1470 |
if os.path.exists(oldPathName) is not True: |
| 1471 |
errorCode = STATUS_NO_SUCH_FILE |
| 1472 |
|
| 1473 |
# TODO: More checks here in the future.. Specially when we support |
| 1474 |
# user access |
| 1475 |
else: |
| 1476 |
try: |
| 1477 |
os.rename(oldPathName,newPathName) |
| 1478 |
except OSError as e: |
| 1479 |
smbServer.log("smbComRename: %s" % e, logging.ERROR) |
| 1480 |
errorCode = STATUS_ACCESS_DENIED |
| 1481 |
else: |
| 1482 |
errorCode = STATUS_SMB_BAD_TID |
| 1483 |
|
| 1484 |
|
| 1485 |
if errorCode > 0: |
| 1486 |
respParameters = '' |
| 1487 |
respData = '' |
| 1488 |
|
| 1489 |
respSMBCommand['Parameters'] = respParameters |
| 1490 |
respSMBCommand['Data'] = respData |
| 1491 |
smbServer.setConnectionData(connId, connData) |
| 1492 |
|
| 1493 |
return [respSMBCommand], None, errorCode |
| 1494 |
|
| 1495 |
@staticmethod |
| 1496 |
def smbComDelete(connId, smbServer, SMBCommand, recvPacket ): |
| 1497 |
connData = smbServer.getConnectionData(connId) |
| 1498 |
|
| 1499 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_DELETE) |
| 1500 |
respParameters = '' |
| 1501 |
respData = '' |
| 1502 |
|
| 1503 |
comDeleteData = smb.SMBDelete_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1504 |
|
| 1505 |
# Get the Tid associated |
| 1506 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1507 |
errorCode = STATUS_SUCCESS |
| 1508 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 1509 |
fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comDeleteData['FileName']).replace('\\','/')) |
| 1510 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 1511 |
# strip leading '/' |
| 1512 |
fileName = fileName[1:] |
| 1513 |
pathName = os.path.join(path,fileName) |
| 1514 |
if os.path.exists(pathName) is not True: |
| 1515 |
errorCode = STATUS_NO_SUCH_FILE |
| 1516 |
|
| 1517 |
# TODO: More checks here in the future.. Specially when we support |
| 1518 |
# user access |
| 1519 |
else: |
| 1520 |
try: |
| 1521 |
os.remove(pathName) |
| 1522 |
except OSError as e: |
| 1523 |
smbServer.log("smbComDelete: %s" % e, logging.ERROR) |
| 1524 |
errorCode = STATUS_ACCESS_DENIED |
| 1525 |
else: |
| 1526 |
errorCode = STATUS_SMB_BAD_TID |
| 1527 |
|
| 1528 |
if errorCode > 0: |
| 1529 |
respParameters = '' |
| 1530 |
respData = '' |
| 1531 |
|
| 1532 |
respSMBCommand['Parameters'] = respParameters |
| 1533 |
respSMBCommand['Data'] = respData |
| 1534 |
smbServer.setConnectionData(connId, connData) |
| 1535 |
|
| 1536 |
return [respSMBCommand], None, errorCode |
| 1537 |
|
| 1538 |
|
| 1539 |
@staticmethod |
| 1540 |
def smbComDeleteDirectory(connId, smbServer, SMBCommand, recvPacket ): |
| 1541 |
connData = smbServer.getConnectionData(connId) |
| 1542 |
|
| 1543 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_DELETE_DIRECTORY) |
| 1544 |
respParameters = '' |
| 1545 |
respData = '' |
| 1546 |
|
| 1547 |
comDeleteDirectoryData= smb.SMBDeleteDirectory_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1548 |
|
| 1549 |
# Get the Tid associated |
| 1550 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1551 |
errorCode = STATUS_SUCCESS |
| 1552 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 1553 |
fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comDeleteDirectoryData['DirectoryName']).replace('\\','/')) |
| 1554 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 1555 |
# strip leading '/' |
| 1556 |
fileName = fileName[1:] |
| 1557 |
pathName = os.path.join(path,fileName) |
| 1558 |
if os.path.exists(pathName) is not True: |
| 1559 |
errorCode = STATUS_NO_SUCH_FILE |
| 1560 |
|
| 1561 |
# TODO: More checks here in the future.. Specially when we support |
| 1562 |
# user access |
| 1563 |
else: |
| 1564 |
try: |
| 1565 |
os.rmdir(pathName) |
| 1566 |
except OSError as e: |
| 1567 |
smbServer.log("smbComDeleteDirectory: %s" % e,logging.ERROR) |
| 1568 |
if e.errno == errno.ENOTEMPTY: |
| 1569 |
errorCode = STATUS_DIRECTORY_NOT_EMPTY |
| 1570 |
else: |
| 1571 |
errorCode = STATUS_ACCESS_DENIED |
| 1572 |
else: |
| 1573 |
errorCode = STATUS_SMB_BAD_TID |
| 1574 |
|
| 1575 |
if errorCode > 0: |
| 1576 |
respParameters = '' |
| 1577 |
respData = '' |
| 1578 |
|
| 1579 |
respSMBCommand['Parameters'] = respParameters |
| 1580 |
respSMBCommand['Data'] = respData |
| 1581 |
smbServer.setConnectionData(connId, connData) |
| 1582 |
|
| 1583 |
return [respSMBCommand], None, errorCode |
| 1584 |
|
| 1585 |
|
| 1586 |
@staticmethod |
| 1587 |
def smbComWriteAndX(connId, smbServer, SMBCommand, recvPacket): |
| 1588 |
connData = smbServer.getConnectionData(connId) |
| 1589 |
|
| 1590 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_WRITE_ANDX) |
| 1591 |
respParameters = smb.SMBWriteAndXResponse_Parameters() |
| 1592 |
respData = '' |
| 1593 |
|
| 1594 |
if SMBCommand['WordCount'] == 0x0C: |
| 1595 |
writeAndX = smb.SMBWriteAndX_Parameters_Short(SMBCommand['Parameters']) |
| 1596 |
writeAndXData = smb.SMBWriteAndX_Data_Short() |
| 1597 |
else: |
| 1598 |
writeAndX = smb.SMBWriteAndX_Parameters(SMBCommand['Parameters']) |
| 1599 |
writeAndXData = smb.SMBWriteAndX_Data() |
| 1600 |
writeAndXData['DataLength'] = writeAndX['DataLength'] |
| 1601 |
writeAndXData['DataOffset'] = writeAndX['DataOffset'] |
| 1602 |
writeAndXData.fromString(SMBCommand['Data']) |
| 1603 |
|
| 1604 |
|
| 1605 |
if writeAndX['Fid'] in connData['OpenedFiles']: |
| 1606 |
fileHandle = connData['OpenedFiles'][writeAndX['Fid']]['FileHandle'] |
| 1607 |
errorCode = STATUS_SUCCESS |
| 1608 |
try: |
| 1609 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 1610 |
offset = writeAndX['Offset'] |
| 1611 |
if 'HighOffset' in writeAndX.fields: |
| 1612 |
offset += (writeAndX['HighOffset'] << 32) |
| 1613 |
# If we're trying to write past the file end we just skip the write call (Vista does this) |
| 1614 |
if os.lseek(fileHandle, 0, 2) >= offset: |
| 1615 |
os.lseek(fileHandle,offset,0) |
| 1616 |
os.write(fileHandle,writeAndXData['Data']) |
| 1617 |
else: |
| 1618 |
sock = connData['OpenedFiles'][writeAndX['Fid']]['Socket'] |
| 1619 |
sock.send(writeAndXData['Data']) |
| 1620 |
|
| 1621 |
respParameters['Count'] = writeAndX['DataLength'] |
| 1622 |
respParameters['Available']= 0xff |
| 1623 |
except Exception as e: |
| 1624 |
smbServer.log('smbComWriteAndx: %s' % e, logging.ERROR) |
| 1625 |
errorCode = STATUS_ACCESS_DENIED |
| 1626 |
else: |
| 1627 |
errorCode = STATUS_INVALID_HANDLE |
| 1628 |
|
| 1629 |
if errorCode > 0: |
| 1630 |
respParameters = '' |
| 1631 |
respData = '' |
| 1632 |
|
| 1633 |
respSMBCommand['Parameters'] = respParameters |
| 1634 |
respSMBCommand['Data'] = respData |
| 1635 |
smbServer.setConnectionData(connId, connData) |
| 1636 |
|
| 1637 |
return [respSMBCommand], None, errorCode |
| 1638 |
|
| 1639 |
@staticmethod |
| 1640 |
def smbComRead(connId, smbServer, SMBCommand, recvPacket): |
| 1641 |
connData = smbServer.getConnectionData(connId) |
| 1642 |
|
| 1643 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_READ) |
| 1644 |
respParameters = smb.SMBReadResponse_Parameters() |
| 1645 |
respData = smb.SMBReadResponse_Data() |
| 1646 |
|
| 1647 |
comReadParameters = smb.SMBRead_Parameters(SMBCommand['Parameters']) |
| 1648 |
|
| 1649 |
if comReadParameters['Fid'] in connData['OpenedFiles']: |
| 1650 |
fileHandle = connData['OpenedFiles'][comReadParameters['Fid']]['FileHandle'] |
| 1651 |
errorCode = STATUS_SUCCESS |
| 1652 |
try: |
| 1653 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 1654 |
# TODO: Handle big size files |
| 1655 |
os.lseek(fileHandle,comReadParameters['Offset'],0) |
| 1656 |
content = os.read(fileHandle,comReadParameters['Count']) |
| 1657 |
else: |
| 1658 |
sock = connData['OpenedFiles'][comReadParameters['Fid']]['Socket'] |
| 1659 |
content = sock.recv(comReadParameters['Count']) |
| 1660 |
respParameters['Count'] = len(content) |
| 1661 |
respData['DataLength'] = len(content) |
| 1662 |
respData['Data'] = content |
| 1663 |
except Exception as e: |
| 1664 |
smbServer.log('smbComRead: %s ' % e, logging.ERROR) |
| 1665 |
errorCode = STATUS_ACCESS_DENIED |
| 1666 |
else: |
| 1667 |
errorCode = STATUS_INVALID_HANDLE |
| 1668 |
|
| 1669 |
if errorCode > 0: |
| 1670 |
respParameters = '' |
| 1671 |
respData = '' |
| 1672 |
|
| 1673 |
respSMBCommand['Parameters'] = respParameters |
| 1674 |
respSMBCommand['Data'] = respData |
| 1675 |
smbServer.setConnectionData(connId, connData) |
| 1676 |
|
| 1677 |
return [respSMBCommand], None, errorCode |
| 1678 |
|
| 1679 |
@staticmethod |
| 1680 |
def smbComReadAndX(connId, smbServer, SMBCommand, recvPacket): |
| 1681 |
connData = smbServer.getConnectionData(connId) |
| 1682 |
|
| 1683 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_READ_ANDX) |
| 1684 |
respParameters = smb.SMBReadAndXResponse_Parameters() |
| 1685 |
respData = '' |
| 1686 |
|
| 1687 |
if SMBCommand['WordCount'] == 0x0A: |
| 1688 |
readAndX = smb.SMBReadAndX_Parameters2(SMBCommand['Parameters']) |
| 1689 |
else: |
| 1690 |
readAndX = smb.SMBReadAndX_Parameters(SMBCommand['Parameters']) |
| 1691 |
|
| 1692 |
if readAndX['Fid'] in connData['OpenedFiles']: |
| 1693 |
fileHandle = connData['OpenedFiles'][readAndX['Fid']]['FileHandle'] |
| 1694 |
errorCode = 0 |
| 1695 |
try: |
| 1696 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 1697 |
offset = readAndX['Offset'] |
| 1698 |
if 'HighOffset' in readAndX.fields: |
| 1699 |
offset += (readAndX['HighOffset'] << 32) |
| 1700 |
os.lseek(fileHandle,offset,0) |
| 1701 |
content = os.read(fileHandle,readAndX['MaxCount']) |
| 1702 |
else: |
| 1703 |
sock = connData['OpenedFiles'][readAndX['Fid']]['Socket'] |
| 1704 |
content = sock.recv(readAndX['MaxCount']) |
| 1705 |
respParameters['Remaining'] = 0xffff |
| 1706 |
respParameters['DataCount'] = len(content) |
| 1707 |
respParameters['DataOffset'] = 59 |
| 1708 |
respParameters['DataCount_Hi'] = 0 |
| 1709 |
respData = content |
| 1710 |
except Exception as e: |
| 1711 |
smbServer.log('smbComReadAndX: %s ' % e, logging.ERROR) |
| 1712 |
errorCode = STATUS_ACCESS_DENIED |
| 1713 |
else: |
| 1714 |
errorCode = STATUS_INVALID_HANDLE |
| 1715 |
|
| 1716 |
if errorCode > 0: |
| 1717 |
respParameters = '' |
| 1718 |
respData = '' |
| 1719 |
|
| 1720 |
respSMBCommand['Parameters'] = respParameters |
| 1721 |
respSMBCommand['Data'] = respData |
| 1722 |
smbServer.setConnectionData(connId, connData) |
| 1723 |
|
| 1724 |
return [respSMBCommand], None, errorCode |
| 1725 |
|
| 1726 |
@staticmethod |
| 1727 |
def smbQueryInformation(connId, smbServer, SMBCommand, recvPacket): |
| 1728 |
connData = smbServer.getConnectionData(connId) |
| 1729 |
|
| 1730 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION) |
| 1731 |
respParameters = smb.SMBQueryInformationResponse_Parameters() |
| 1732 |
respData = '' |
| 1733 |
|
| 1734 |
queryInformation= smb.SMBQueryInformation_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1735 |
|
| 1736 |
# Get the Tid associated |
| 1737 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1738 |
fileSize, lastWriteTime, fileAttributes = queryFsInformation( |
| 1739 |
connData['ConnectedShares'][recvPacket['Tid']]['path'], |
| 1740 |
decodeSMBString(recvPacket['Flags2'],queryInformation['FileName'])) |
| 1741 |
|
| 1742 |
respParameters['FileSize'] = fileSize |
| 1743 |
respParameters['LastWriteTime'] = lastWriteTime |
| 1744 |
respParameters['FileAttributes'] = fileAttributes |
| 1745 |
errorCode = STATUS_SUCCESS |
| 1746 |
else: |
| 1747 |
# STATUS_SMB_BAD_TID |
| 1748 |
errorCode = STATUS_SMB_BAD_TID |
| 1749 |
respParameters = '' |
| 1750 |
respData = '' |
| 1751 |
|
| 1752 |
respSMBCommand['Parameters'] = respParameters |
| 1753 |
respSMBCommand['Data'] = respData |
| 1754 |
|
| 1755 |
smbServer.setConnectionData(connId, connData) |
| 1756 |
return [respSMBCommand], None, errorCode |
| 1757 |
|
| 1758 |
@staticmethod |
| 1759 |
def smbQueryInformationDisk(connId, smbServer, SMBCommand, recvPacket): |
| 1760 |
connData = smbServer.getConnectionData(connId) |
| 1761 |
|
| 1762 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION_DISK) |
| 1763 |
respParameters = smb.SMBQueryInformationDiskResponse_Parameters() |
| 1764 |
respData = '' |
| 1765 |
|
| 1766 |
# Get the Tid associated |
| 1767 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1768 |
totalUnits, freeUnits = queryDiskInformation( |
| 1769 |
connData['ConnectedShares'][recvPacket['Tid']]['path']) |
| 1770 |
|
| 1771 |
respParameters['TotalUnits'] = totalUnits |
| 1772 |
respParameters['BlocksPerUnit'] = 1 |
| 1773 |
respParameters['BlockSize'] = 1 |
| 1774 |
respParameters['FreeUnits'] = freeUnits |
| 1775 |
errorCode = STATUS_SUCCESS |
| 1776 |
else: |
| 1777 |
# STATUS_SMB_BAD_TID |
| 1778 |
respData = '' |
| 1779 |
respParameters = '' |
| 1780 |
errorCode = STATUS_SMB_BAD_TID |
| 1781 |
|
| 1782 |
|
| 1783 |
respSMBCommand['Parameters'] = respParameters |
| 1784 |
respSMBCommand['Data'] = respData |
| 1785 |
|
| 1786 |
smbServer.setConnectionData(connId, connData) |
| 1787 |
return [respSMBCommand], None, errorCode |
| 1788 |
|
| 1789 |
@staticmethod |
| 1790 |
def smbComEcho(connId, smbServer, SMBCommand, recvPacket): |
| 1791 |
connData = smbServer.getConnectionData(connId) |
| 1792 |
|
| 1793 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_ECHO) |
| 1794 |
respParameters = smb.SMBEchoResponse_Parameters() |
| 1795 |
respData = smb.SMBEchoResponse_Data() |
| 1796 |
|
| 1797 |
echoData = smb.SMBEcho_Data(SMBCommand['Data']) |
| 1798 |
|
| 1799 |
respParameters['SequenceNumber'] = 1 |
| 1800 |
respData['Data'] = echoData['Data'] |
| 1801 |
|
| 1802 |
respSMBCommand['Parameters'] = respParameters |
| 1803 |
respSMBCommand['Data'] = respData |
| 1804 |
|
| 1805 |
errorCode = STATUS_SUCCESS |
| 1806 |
smbServer.setConnectionData(connId, connData) |
| 1807 |
return [respSMBCommand], None, errorCode |
| 1808 |
|
| 1809 |
@staticmethod |
| 1810 |
def smbComTreeDisconnect(connId, smbServer, SMBCommand, recvPacket): |
| 1811 |
connData = smbServer.getConnectionData(connId) |
| 1812 |
|
| 1813 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_TREE_DISCONNECT) |
| 1814 |
|
| 1815 |
# Check if the Tid matches the Tid trying to disconnect |
| 1816 |
respParameters = '' |
| 1817 |
respData = '' |
| 1818 |
|
| 1819 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1820 |
smbServer.log("Disconnecting Share(%d:%s)" % (recvPacket['Tid'],connData['ConnectedShares'][recvPacket['Tid']]['shareName'])) |
| 1821 |
del(connData['ConnectedShares'][recvPacket['Tid']]) |
| 1822 |
errorCode = STATUS_SUCCESS |
| 1823 |
else: |
| 1824 |
# STATUS_SMB_BAD_TID |
| 1825 |
errorCode = STATUS_SMB_BAD_TID |
| 1826 |
|
| 1827 |
respSMBCommand['Parameters'] = respParameters |
| 1828 |
respSMBCommand['Data'] = respData |
| 1829 |
|
| 1830 |
smbServer.setConnectionData(connId, connData) |
| 1831 |
return [respSMBCommand], None, errorCode |
| 1832 |
|
| 1833 |
@staticmethod |
| 1834 |
def smbComLogOffAndX(connId, smbServer, SMBCommand, recvPacket): |
| 1835 |
connData = smbServer.getConnectionData(connId) |
| 1836 |
|
| 1837 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_LOGOFF_ANDX) |
| 1838 |
|
| 1839 |
# Check if the Uid matches the user trying to logoff |
| 1840 |
respParameters = '' |
| 1841 |
respData = '' |
| 1842 |
if recvPacket['Uid'] != connData['Uid']: |
| 1843 |
# STATUS_SMB_BAD_UID |
| 1844 |
errorCode = STATUS_SMB_BAD_UID |
| 1845 |
else: |
| 1846 |
errorCode = STATUS_SUCCESS |
| 1847 |
|
| 1848 |
respSMBCommand['Parameters'] = respParameters |
| 1849 |
respSMBCommand['Data'] = respData |
| 1850 |
connData['Uid'] = 0 |
| 1851 |
|
| 1852 |
smbServer.setConnectionData(connId, connData) |
| 1853 |
|
| 1854 |
return [respSMBCommand], None, errorCode |
| 1855 |
|
| 1856 |
@staticmethod |
| 1857 |
def smbComQueryInformation2(connId, smbServer, SMBCommand, recvPacket): |
| 1858 |
connData = smbServer.getConnectionData(connId) |
| 1859 |
|
| 1860 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_QUERY_INFORMATION2) |
| 1861 |
respParameters = smb.SMBQueryInformation2Response_Parameters() |
| 1862 |
respData = '' |
| 1863 |
|
| 1864 |
queryInformation2 = smb.SMBQueryInformation2_Parameters(SMBCommand['Parameters']) |
| 1865 |
errorCode = 0xFF |
| 1866 |
if queryInformation2['Fid'] in connData['OpenedFiles']: |
| 1867 |
errorCode = STATUS_SUCCESS |
| 1868 |
pathName = connData['OpenedFiles'][queryInformation2['Fid']]['FileName'] |
| 1869 |
try: |
| 1870 |
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathName) |
| 1871 |
respParameters['CreateDate'] = getSMBDate(ctime) |
| 1872 |
respParameters['CreationTime'] = getSMBTime(ctime) |
| 1873 |
respParameters['LastAccessDate'] = getSMBDate(atime) |
| 1874 |
respParameters['LastAccessTime'] = getSMBTime(atime) |
| 1875 |
respParameters['LastWriteDate'] = getSMBDate(mtime) |
| 1876 |
respParameters['LastWriteTime'] = getSMBTime(mtime) |
| 1877 |
respParameters['FileDataSize'] = size |
| 1878 |
respParameters['FileAllocationSize'] = size |
| 1879 |
attribs = 0 |
| 1880 |
if os.path.isdir(pathName): |
| 1881 |
attribs = smb.SMB_FILE_ATTRIBUTE_DIRECTORY |
| 1882 |
if os.path.isfile(pathName): |
| 1883 |
attribs = smb.SMB_FILE_ATTRIBUTE_NORMAL |
| 1884 |
respParameters['FileAttributes'] = attribs |
| 1885 |
except Exception as e: |
| 1886 |
smbServer.log('smbComQueryInformation2 %s' % e,logging.ERROR) |
| 1887 |
errorCode = STATUS_ACCESS_DENIED |
| 1888 |
|
| 1889 |
if errorCode > 0: |
| 1890 |
respParameters = '' |
| 1891 |
respData = '' |
| 1892 |
|
| 1893 |
respSMBCommand['Parameters'] = respParameters |
| 1894 |
respSMBCommand['Data'] = respData |
| 1895 |
smbServer.setConnectionData(connId, connData) |
| 1896 |
|
| 1897 |
return [respSMBCommand], None, errorCode |
| 1898 |
|
| 1899 |
@staticmethod |
| 1900 |
def smbComNtCreateAndX(connId, smbServer, SMBCommand, recvPacket): |
| 1901 |
# TODO: Fully implement this |
| 1902 |
connData = smbServer.getConnectionData(connId) |
| 1903 |
|
| 1904 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX) |
| 1905 |
respParameters = smb.SMBNtCreateAndXResponse_Parameters() |
| 1906 |
respData = '' |
| 1907 |
|
| 1908 |
ntCreateAndXParameters = smb.SMBNtCreateAndX_Parameters(SMBCommand['Parameters']) |
| 1909 |
ntCreateAndXData = smb.SMBNtCreateAndX_Data( flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 1910 |
|
| 1911 |
#if ntCreateAndXParameters['CreateFlags'] & 0x10: # NT_CREATE_REQUEST_EXTENDED_RESPONSE |
| 1912 |
# respParameters = smb.SMBNtCreateAndXExtendedResponse_Parameters() |
| 1913 |
# respParameters['VolumeGUID'] = '\x00' |
| 1914 |
|
| 1915 |
# Get the Tid associated |
| 1916 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 1917 |
# If we have a rootFid, the path is relative to that fid |
| 1918 |
errorCode = STATUS_SUCCESS |
| 1919 |
if ntCreateAndXParameters['RootFid'] > 0: |
| 1920 |
path = connData['OpenedFiles'][ntCreateAndXParameters['RootFid']]['FileName'] |
| 1921 |
LOG.debug("RootFid present %s!" % path) |
| 1922 |
else: |
| 1923 |
if 'path' in connData['ConnectedShares'][recvPacket['Tid']]: |
| 1924 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 1925 |
else: |
| 1926 |
path = 'NONE' |
| 1927 |
errorCode = STATUS_ACCESS_DENIED |
| 1928 |
|
| 1929 |
deleteOnClose = False |
| 1930 |
|
| 1931 |
fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],ntCreateAndXData['FileName']).replace('\\','/')) |
| 1932 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 1933 |
# strip leading '/' |
| 1934 |
fileName = fileName[1:] |
| 1935 |
pathName = os.path.join(path,fileName) |
| 1936 |
createDisposition = ntCreateAndXParameters['Disposition'] |
| 1937 |
mode = 0 |
| 1938 |
|
| 1939 |
if createDisposition == smb.FILE_SUPERSEDE: |
| 1940 |
mode |= os.O_TRUNC | os.O_CREAT |
| 1941 |
elif createDisposition & smb.FILE_OVERWRITE_IF == smb.FILE_OVERWRITE_IF: |
| 1942 |
mode |= os.O_TRUNC | os.O_CREAT |
| 1943 |
elif createDisposition & smb.FILE_OVERWRITE == smb.FILE_OVERWRITE: |
| 1944 |
if os.path.exists(pathName) is True: |
| 1945 |
mode |= os.O_TRUNC |
| 1946 |
else: |
| 1947 |
errorCode = STATUS_NO_SUCH_FILE |
| 1948 |
elif createDisposition & smb.FILE_OPEN_IF == smb.FILE_OPEN_IF: |
| 1949 |
if os.path.exists(pathName) is True: |
| 1950 |
mode |= os.O_TRUNC |
| 1951 |
else: |
| 1952 |
mode |= os.O_TRUNC | os.O_CREAT |
| 1953 |
elif createDisposition & smb.FILE_CREATE == smb.FILE_CREATE: |
| 1954 |
if os.path.exists(pathName) is True: |
| 1955 |
errorCode = STATUS_OBJECT_NAME_COLLISION |
| 1956 |
else: |
| 1957 |
mode |= os.O_CREAT |
| 1958 |
elif createDisposition & smb.FILE_OPEN == smb.FILE_OPEN: |
| 1959 |
if os.path.exists(pathName) is not True and (unicode(pathName) in smbServer.getRegisteredNamedPipes()) is not True: |
| 1960 |
errorCode = STATUS_NO_SUCH_FILE |
| 1961 |
|
| 1962 |
if errorCode == STATUS_SUCCESS: |
| 1963 |
desiredAccess = ntCreateAndXParameters['AccessMask'] |
| 1964 |
if (desiredAccess & smb.FILE_READ_DATA) or (desiredAccess & smb.GENERIC_READ): |
| 1965 |
mode |= os.O_RDONLY |
| 1966 |
if (desiredAccess & smb.FILE_WRITE_DATA) or (desiredAccess & smb.GENERIC_WRITE): |
| 1967 |
if (desiredAccess & smb.FILE_READ_DATA) or (desiredAccess & smb.GENERIC_READ): |
| 1968 |
mode |= os.O_RDWR #| os.O_APPEND |
| 1969 |
else: |
| 1970 |
mode |= os.O_WRONLY #| os.O_APPEND |
| 1971 |
if desiredAccess & smb.GENERIC_ALL: |
| 1972 |
mode |= os.O_RDWR #| os.O_APPEND |
| 1973 |
|
| 1974 |
createOptions = ntCreateAndXParameters['CreateOptions'] |
| 1975 |
if mode & os.O_CREAT == os.O_CREAT: |
| 1976 |
if createOptions & smb.FILE_DIRECTORY_FILE == smb.FILE_DIRECTORY_FILE: |
| 1977 |
try: |
| 1978 |
# Let's create the directory |
| 1979 |
os.mkdir(pathName) |
| 1980 |
mode = os.O_RDONLY |
| 1981 |
except Exception as e: |
| 1982 |
smbServer.log("NTCreateAndX: %s,%s,%s" % (pathName,mode,e),logging.ERROR) |
| 1983 |
errorCode = STATUS_ACCESS_DENIED |
| 1984 |
if createOptions & smb.FILE_NON_DIRECTORY_FILE == smb.FILE_NON_DIRECTORY_FILE: |
| 1985 |
# If the file being opened is a directory, the server MUST fail the request with |
| 1986 |
# STATUS_FILE_IS_A_DIRECTORY in the Status field of the SMB Header in the server |
| 1987 |
# response. |
| 1988 |
if os.path.isdir(pathName) is True: |
| 1989 |
errorCode = STATUS_FILE_IS_A_DIRECTORY |
| 1990 |
|
| 1991 |
if createOptions & smb.FILE_DELETE_ON_CLOSE == smb.FILE_DELETE_ON_CLOSE: |
| 1992 |
deleteOnClose = True |
| 1993 |
|
| 1994 |
if errorCode == STATUS_SUCCESS: |
| 1995 |
try: |
| 1996 |
if os.path.isdir(pathName) and sys.platform == 'win32': |
| 1997 |
fid = VOID_FILE_DESCRIPTOR |
| 1998 |
else: |
| 1999 |
if sys.platform == 'win32': |
| 2000 |
mode |= os.O_BINARY |
| 2001 |
if unicode(pathName) in smbServer.getRegisteredNamedPipes(): |
| 2002 |
fid = PIPE_FILE_DESCRIPTOR |
| 2003 |
sock = socket.socket() |
| 2004 |
sock.connect(smbServer.getRegisteredNamedPipes()[unicode(pathName)]) |
| 2005 |
else: |
| 2006 |
fid = os.open(pathName, mode) |
| 2007 |
except Exception as e: |
| 2008 |
smbServer.log("NTCreateAndX: %s,%s,%s" % (pathName,mode,e),logging.ERROR) |
| 2009 |
#print e |
| 2010 |
fid = 0 |
| 2011 |
errorCode = STATUS_ACCESS_DENIED |
| 2012 |
else: |
| 2013 |
errorCode = STATUS_SMB_BAD_TID |
| 2014 |
|
| 2015 |
if errorCode == STATUS_SUCCESS: |
| 2016 |
# Simple way to generate a fid |
| 2017 |
if len(connData['OpenedFiles']) == 0: |
| 2018 |
fakefid = 1 |
| 2019 |
else: |
| 2020 |
fakefid = connData['OpenedFiles'].keys()[-1] + 1 |
| 2021 |
respParameters['Fid'] = fakefid |
| 2022 |
respParameters['CreateAction'] = createDisposition |
| 2023 |
if fid == PIPE_FILE_DESCRIPTOR: |
| 2024 |
respParameters['FileAttributes'] = 0x80 |
| 2025 |
respParameters['IsDirectory'] = 0 |
| 2026 |
respParameters['CreateTime'] = 0 |
| 2027 |
respParameters['LastAccessTime'] = 0 |
| 2028 |
respParameters['LastWriteTime'] = 0 |
| 2029 |
respParameters['LastChangeTime'] = 0 |
| 2030 |
respParameters['AllocationSize'] = 4096 |
| 2031 |
respParameters['EndOfFile'] = 0 |
| 2032 |
respParameters['FileType'] = 2 |
| 2033 |
respParameters['IPCState'] = 0x5ff |
| 2034 |
else: |
| 2035 |
if os.path.isdir(pathName): |
| 2036 |
respParameters['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY |
| 2037 |
respParameters['IsDirectory'] = 1 |
| 2038 |
else: |
| 2039 |
respParameters['IsDirectory'] = 0 |
| 2040 |
respParameters['FileAttributes'] = ntCreateAndXParameters['FileAttributes'] |
| 2041 |
# Let's get this file's information |
| 2042 |
respInfo, errorCode = queryPathInformation('',pathName,level= smb.SMB_QUERY_FILE_ALL_INFO) |
| 2043 |
if errorCode == STATUS_SUCCESS: |
| 2044 |
respParameters['CreateTime'] = respInfo['CreationTime'] |
| 2045 |
respParameters['LastAccessTime'] = respInfo['LastAccessTime'] |
| 2046 |
respParameters['LastWriteTime'] = respInfo['LastWriteTime'] |
| 2047 |
respParameters['LastChangeTime'] = respInfo['LastChangeTime'] |
| 2048 |
respParameters['FileAttributes'] = respInfo['ExtFileAttributes'] |
| 2049 |
respParameters['AllocationSize'] = respInfo['AllocationSize'] |
| 2050 |
respParameters['EndOfFile'] = respInfo['EndOfFile'] |
| 2051 |
else: |
| 2052 |
respParameters = '' |
| 2053 |
respData = '' |
| 2054 |
|
| 2055 |
if errorCode == STATUS_SUCCESS: |
| 2056 |
# Let's store the fid for the connection |
| 2057 |
# smbServer.log('Create file %s, mode:0x%x' % (pathName, mode)) |
| 2058 |
connData['OpenedFiles'][fakefid] = {} |
| 2059 |
connData['OpenedFiles'][fakefid]['FileHandle'] = fid |
| 2060 |
connData['OpenedFiles'][fakefid]['FileName'] = pathName |
| 2061 |
connData['OpenedFiles'][fakefid]['DeleteOnClose'] = deleteOnClose |
| 2062 |
if fid == PIPE_FILE_DESCRIPTOR: |
| 2063 |
connData['OpenedFiles'][fakefid]['Socket'] = sock |
| 2064 |
else: |
| 2065 |
respParameters = '' |
| 2066 |
respData = '' |
| 2067 |
|
| 2068 |
respSMBCommand['Parameters'] = respParameters |
| 2069 |
respSMBCommand['Data'] = respData |
| 2070 |
smbServer.setConnectionData(connId, connData) |
| 2071 |
|
| 2072 |
return [respSMBCommand], None, errorCode |
| 2073 |
|
| 2074 |
@staticmethod |
| 2075 |
def smbComOpenAndX(connId, smbServer, SMBCommand, recvPacket): |
| 2076 |
connData = smbServer.getConnectionData(connId) |
| 2077 |
|
| 2078 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_OPEN_ANDX) |
| 2079 |
respParameters = smb.SMBOpenAndXResponse_Parameters() |
| 2080 |
respData = '' |
| 2081 |
|
| 2082 |
openAndXParameters = smb.SMBOpenAndX_Parameters(SMBCommand['Parameters']) |
| 2083 |
openAndXData = smb.SMBOpenAndX_Data( flags = recvPacket['Flags2'], data = SMBCommand['Data']) |
| 2084 |
|
| 2085 |
# Get the Tid associated |
| 2086 |
if recvPacket['Tid'] in connData['ConnectedShares']: |
| 2087 |
path = connData['ConnectedShares'][recvPacket['Tid']]['path'] |
| 2088 |
openedFile, mode, pathName, errorCode = openFile(path, |
| 2089 |
decodeSMBString(recvPacket['Flags2'],openAndXData['FileName']), |
| 2090 |
openAndXParameters['DesiredAccess'], |
| 2091 |
openAndXParameters['FileAttributes'], |
| 2092 |
openAndXParameters['OpenMode']) |
| 2093 |
else: |
| 2094 |
errorCode = STATUS_SMB_BAD_TID |
| 2095 |
|
| 2096 |
if errorCode == STATUS_SUCCESS: |
| 2097 |
# Simple way to generate a fid |
| 2098 |
fid = len(connData['OpenedFiles']) + 1 |
| 2099 |
if len(connData['OpenedFiles']) == 0: |
| 2100 |
fid = 1 |
| 2101 |
else: |
| 2102 |
fid = connData['OpenedFiles'].keys()[-1] + 1 |
| 2103 |
respParameters['Fid'] = fid |
| 2104 |
if mode & os.O_CREAT: |
| 2105 |
# File did not exist and was created |
| 2106 |
respParameters['Action'] = 0x2 |
| 2107 |
elif mode & os.O_RDONLY: |
| 2108 |
# File existed and was opened |
| 2109 |
respParameters['Action'] = 0x1 |
| 2110 |
elif mode & os.O_APPEND: |
| 2111 |
# File existed and was opened |
| 2112 |
respParameters['Action'] = 0x1 |
| 2113 |
else: |
| 2114 |
# File existed and was truncated |
| 2115 |
respParameters['Action'] = 0x3 |
| 2116 |
|
| 2117 |
# Let's store the fid for the connection |
| 2118 |
#smbServer.log('Opening file %s' % pathName) |
| 2119 |
connData['OpenedFiles'][fid] = {} |
| 2120 |
connData['OpenedFiles'][fid]['FileHandle'] = openedFile |
| 2121 |
connData['OpenedFiles'][fid]['FileName'] = pathName |
| 2122 |
connData['OpenedFiles'][fid]['DeleteOnClose'] = False |
| 2123 |
else: |
| 2124 |
respParameters = '' |
| 2125 |
respData = '' |
| 2126 |
|
| 2127 |
respSMBCommand['Parameters'] = respParameters |
| 2128 |
respSMBCommand['Data'] = respData |
| 2129 |
smbServer.setConnectionData(connId, connData) |
| 2130 |
|
| 2131 |
return [respSMBCommand], None, errorCode |
| 2132 |
|
| 2133 |
@staticmethod |
| 2134 |
def smbComTreeConnectAndX(connId, smbServer, SMBCommand, recvPacket): |
| 2135 |
connData = smbServer.getConnectionData(connId) |
| 2136 |
|
| 2137 |
resp = smb.NewSMBPacket() |
| 2138 |
resp['Flags1'] = smb.SMB.FLAGS1_REPLY |
| 2139 |
resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | recvPacket['Flags2'] & smb.SMB.FLAGS2_UNICODE |
| 2140 |
|
| 2141 |
resp['Tid'] = recvPacket['Tid'] |
| 2142 |
resp['Mid'] = recvPacket['Mid'] |
| 2143 |
resp['Pid'] = connData['Pid'] |
| 2144 |
|
| 2145 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX) |
| 2146 |
respParameters = smb.SMBTreeConnectAndXResponse_Parameters() |
| 2147 |
respData = smb.SMBTreeConnectAndXResponse_Data() |
| 2148 |
|
| 2149 |
treeConnectAndXParameters = smb.SMBTreeConnectAndX_Parameters(SMBCommand['Parameters']) |
| 2150 |
|
| 2151 |
if treeConnectAndXParameters['Flags'] & 0x8: |
| 2152 |
respParameters = smb.SMBTreeConnectAndXExtendedResponse_Parameters() |
| 2153 |
|
| 2154 |
treeConnectAndXData = smb.SMBTreeConnectAndX_Data( flags = recvPacket['Flags2'] ) |
| 2155 |
treeConnectAndXData['_PasswordLength'] = treeConnectAndXParameters['PasswordLength'] |
| 2156 |
treeConnectAndXData.fromString(SMBCommand['Data']) |
| 2157 |
|
| 2158 |
errorCode = STATUS_SUCCESS |
| 2159 |
|
| 2160 |
## Process here the request, does the share exist? |
| 2161 |
UNCOrShare = decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Path']) |
| 2162 |
|
| 2163 |
# Is this a UNC? |
| 2164 |
if ntpath.ismount(UNCOrShare): |
| 2165 |
path = UNCOrShare.split('\\')[3] |
| 2166 |
else: |
| 2167 |
path = ntpath.basename(UNCOrShare) |
| 2168 |
|
| 2169 |
share = searchShare(connId, path, smbServer) |
| 2170 |
if share is not None: |
| 2171 |
# Simple way to generate a Tid |
| 2172 |
if len(connData['ConnectedShares']) == 0: |
| 2173 |
tid = 1 |
| 2174 |
else: |
| 2175 |
tid = connData['ConnectedShares'].keys()[-1] + 1 |
| 2176 |
connData['ConnectedShares'][tid] = share |
| 2177 |
connData['ConnectedShares'][tid]['shareName'] = path |
| 2178 |
resp['Tid'] = tid |
| 2179 |
#smbServer.log("Connecting Share(%d:%s)" % (tid,path)) |
| 2180 |
else: |
| 2181 |
smbServer.log("TreeConnectAndX not found %s" % path, logging.ERROR) |
| 2182 |
errorCode = STATUS_OBJECT_PATH_NOT_FOUND |
| 2183 |
resp['ErrorCode'] = errorCode >> 16 |
| 2184 |
resp['ErrorClass'] = errorCode & 0xff |
| 2185 |
## |
| 2186 |
respParameters['OptionalSupport'] = smb.SMB.SMB_SUPPORT_SEARCH_BITS |
| 2187 |
|
| 2188 |
if path == 'IPC$': |
| 2189 |
respData['Service'] = 'IPC' |
| 2190 |
else: |
| 2191 |
respData['Service'] = path |
| 2192 |
respData['PadLen'] = 0 |
| 2193 |
respData['NativeFileSystem'] = encodeSMBString(recvPacket['Flags2'], 'NTFS' ) |
| 2194 |
|
| 2195 |
respSMBCommand['Parameters'] = respParameters |
| 2196 |
respSMBCommand['Data'] = respData |
| 2197 |
|
| 2198 |
resp['Uid'] = connData['Uid'] |
| 2199 |
resp.addCommand(respSMBCommand) |
| 2200 |
smbServer.setConnectionData(connId, connData) |
| 2201 |
|
| 2202 |
return None, [resp], errorCode |
| 2203 |
|
| 2204 |
@staticmethod |
| 2205 |
def smbComSessionSetupAndX(connId, smbServer, SMBCommand, recvPacket): |
| 2206 |
connData = smbServer.getConnectionData(connId, checkStatus = False) |
| 2207 |
|
| 2208 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX) |
| 2209 |
|
| 2210 |
# From [MS-SMB] |
| 2211 |
# When extended security is being used (see section 3.2.4.2.4), the |
| 2212 |
# request MUST take the following form |
| 2213 |
# [..] |
| 2214 |
# WordCount (1 byte): The value of this field MUST be 0x0C. |
| 2215 |
if SMBCommand['WordCount'] == 12: |
| 2216 |
# Extended security. Here we deal with all SPNEGO stuff |
| 2217 |
respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters() |
| 2218 |
respData = smb.SMBSessionSetupAndX_Extended_Response_Data(flags = recvPacket['Flags2']) |
| 2219 |
sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(SMBCommand['Parameters']) |
| 2220 |
sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data() |
| 2221 |
sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength'] |
| 2222 |
sessionSetupData.fromString(SMBCommand['Data']) |
| 2223 |
connData['Capabilities'] = sessionSetupParameters['Capabilities'] |
| 2224 |
|
| 2225 |
rawNTLM = False |
| 2226 |
if struct.unpack('B',sessionSetupData['SecurityBlob'][0])[0] == ASN1_AID: |
| 2227 |
# NEGOTIATE packet |
| 2228 |
blob = SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob']) |
| 2229 |
token = blob['MechToken'] |
| 2230 |
if len(blob['MechTypes'][0]) > 0: |
| 2231 |
# Is this GSSAPI NTLM or something else we don't support? |
| 2232 |
mechType = blob['MechTypes'][0] |
| 2233 |
if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']: |
| 2234 |
# Nope, do we know it? |
| 2235 |
if mechType in MechTypes: |
| 2236 |
mechStr = MechTypes[mechType] |
| 2237 |
else: |
| 2238 |
mechStr = hexlify(mechType) |
| 2239 |
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL) |
| 2240 |
# We don't know the token, we answer back again saying |
| 2241 |
# we just support NTLM. |
| 2242 |
# ToDo: Build this into a SPNEGO_NegTokenResp() |
| 2243 |
respToken = '\xa1\x15\x30\x13\xa0\x03\x0a\x01\x03\xa1\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a' |
| 2244 |
respParameters['SecurityBlobLength'] = len(respToken) |
| 2245 |
respData['SecurityBlobLength'] = respParameters['SecurityBlobLength'] |
| 2246 |
respData['SecurityBlob'] = respToken |
| 2247 |
respData['NativeOS'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS()) |
| 2248 |
respData['NativeLanMan'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS()) |
| 2249 |
respSMBCommand['Parameters'] = respParameters |
| 2250 |
respSMBCommand['Data'] = respData |
| 2251 |
return [respSMBCommand], None, STATUS_MORE_PROCESSING_REQUIRED |
| 2252 |
|
| 2253 |
elif struct.unpack('B',sessionSetupData['SecurityBlob'][0])[0] == ASN1_SUPPORTED_MECH: |
| 2254 |
# AUTH packet |
| 2255 |
blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob']) |
| 2256 |
token = blob['ResponseToken'] |
| 2257 |
else: |
| 2258 |
# No GSSAPI stuff, raw NTLMSSP |
| 2259 |
rawNTLM = True |
| 2260 |
token = sessionSetupData['SecurityBlob'] |
| 2261 |
|
| 2262 |
# Here we only handle NTLMSSP, depending on what stage of the |
| 2263 |
# authentication we are, we act on it |
| 2264 |
messageType = struct.unpack('<L',token[len('NTLMSSP\x00'):len('NTLMSSP\x00')+4])[0] |
| 2265 |
|
| 2266 |
if messageType == 0x01: |
| 2267 |
# NEGOTIATE_MESSAGE |
| 2268 |
negotiateMessage = ntlm.NTLMAuthNegotiate() |
| 2269 |
negotiateMessage.fromString(token) |
| 2270 |
# Let's store it in the connection data |
| 2271 |
connData['NEGOTIATE_MESSAGE'] = negotiateMessage |
| 2272 |
# Let's build the answer flags |
| 2273 |
# TODO: Parse all the flags. With this we're leaving some clients out |
| 2274 |
|
| 2275 |
ansFlags = 0 |
| 2276 |
|
| 2277 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56: |
| 2278 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56 |
| 2279 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128: |
| 2280 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128 |
| 2281 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH: |
| 2282 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH |
| 2283 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: |
| 2284 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY |
| 2285 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE: |
| 2286 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE |
| 2287 |
if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM: |
| 2288 |
ansFlags |= ntlm.NTLM_NEGOTIATE_OEM |
| 2289 |
|
| 2290 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_REQUEST_TARGET |
| 2291 |
|
| 2292 |
# Generate the AV_PAIRS |
| 2293 |
av_pairs = ntlm.AV_PAIRS() |
| 2294 |
# TODO: Put the proper data from SMBSERVER config |
| 2295 |
av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] = smbServer.getServerName().encode('utf-16le') |
| 2296 |
av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = smbServer.getServerDomain().encode('utf-16le') |
| 2297 |
av_pairs[ntlm.NTLMSSP_AV_TIME] = struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000) ) |
| 2298 |
|
| 2299 |
challengeMessage = ntlm.NTLMAuthChallenge() |
| 2300 |
challengeMessage['flags'] = ansFlags |
| 2301 |
challengeMessage['domain_len'] = len(smbServer.getServerDomain().encode('utf-16le')) |
| 2302 |
challengeMessage['domain_max_len'] = challengeMessage['domain_len'] |
| 2303 |
challengeMessage['domain_offset'] = 40 + 16 |
| 2304 |
challengeMessage['challenge'] = smbServer.getSMBChallenge() |
| 2305 |
challengeMessage['domain_name'] = smbServer.getServerDomain().encode('utf-16le') |
| 2306 |
challengeMessage['TargetInfoFields_len'] = len(av_pairs) |
| 2307 |
challengeMessage['TargetInfoFields_max_len'] = len(av_pairs) |
| 2308 |
challengeMessage['TargetInfoFields'] = av_pairs |
| 2309 |
challengeMessage['TargetInfoFields_offset'] = 40 + 16 + len(challengeMessage['domain_name']) |
| 2310 |
challengeMessage['Version'] = '\xff'*8 |
| 2311 |
challengeMessage['VersionLen'] = 8 |
| 2312 |
|
| 2313 |
if rawNTLM is False: |
| 2314 |
respToken = SPNEGO_NegTokenResp() |
| 2315 |
# accept-incomplete. We want more data |
| 2316 |
respToken['NegResult'] = '\x01' |
| 2317 |
respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] |
| 2318 |
|
| 2319 |
respToken['ResponseToken'] = challengeMessage.getData() |
| 2320 |
else: |
| 2321 |
respToken = challengeMessage |
| 2322 |
|
| 2323 |
# Setting the packet to STATUS_MORE_PROCESSING |
| 2324 |
errorCode = STATUS_MORE_PROCESSING_REQUIRED |
| 2325 |
# Let's set up an UID for this connection and store it |
| 2326 |
# in the connection's data |
| 2327 |
# Picking a fixed value |
| 2328 |
# TODO: Manage more UIDs for the same session |
| 2329 |
connData['Uid'] = 10 |
| 2330 |
# Let's store it in the connection data |
| 2331 |
connData['CHALLENGE_MESSAGE'] = challengeMessage |
| 2332 |
|
| 2333 |
elif messageType == 0x02: |
| 2334 |
# CHALLENGE_MESSAGE |
| 2335 |
raise Exception('Challenge Message raise, not implemented!') |
| 2336 |
elif messageType == 0x03: |
| 2337 |
# AUTHENTICATE_MESSAGE, here we deal with authentication |
| 2338 |
authenticateMessage = ntlm.NTLMAuthChallengeResponse() |
| 2339 |
authenticateMessage.fromString(token) |
| 2340 |
smbServer.log("AUTHENTICATE_MESSAGE (%s\\%s,%s)" % (authenticateMessage['domain_name'], authenticateMessage['user_name'], authenticateMessage['host_name'])) |
| 2341 |
# TODO: Check the credentials! Now granting permissions |
| 2342 |
|
| 2343 |
respToken = SPNEGO_NegTokenResp() |
| 2344 |
# accept-completed |
| 2345 |
respToken['NegResult'] = '\x00' |
| 2346 |
|
| 2347 |
# Status SUCCESS |
| 2348 |
errorCode = STATUS_SUCCESS |
| 2349 |
smbServer.log('User %s\\%s authenticated successfully' % (authenticateMessage['user_name'], authenticateMessage['host_name'])) |
| 2350 |
# Let's store it in the connection data |
| 2351 |
connData['AUTHENTICATE_MESSAGE'] = authenticateMessage |
| 2352 |
try: |
| 2353 |
jtr_dump_path = smbServer.getJTRdumpPath() |
| 2354 |
ntlm_hash_data = outputToJohnFormat( connData['CHALLENGE_MESSAGE']['challenge'], authenticateMessage['user_name'], authenticateMessage['domain_name'], authenticateMessage['lanman'], authenticateMessage['ntlm'] ) |
| 2355 |
smbServer.log(ntlm_hash_data['hash_string']) |
| 2356 |
if jtr_dump_path is not '': |
| 2357 |
writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], jtr_dump_path) |
| 2358 |
except: |
| 2359 |
smbServer.log("Could not write NTLM Hashes to the specified JTR_Dump_Path %s" % jtr_dump_path) |
| 2360 |
else: |
| 2361 |
raise Exception("Unknown NTLMSSP MessageType %d" % messageType) |
| 2362 |
|
| 2363 |
respParameters['SecurityBlobLength'] = len(respToken) |
| 2364 |
respData['SecurityBlobLength'] = respParameters['SecurityBlobLength'] |
| 2365 |
respData['SecurityBlob'] = respToken.getData() |
| 2366 |
|
| 2367 |
else: |
| 2368 |
# Process Standard Security |
| 2369 |
respParameters = smb.SMBSessionSetupAndXResponse_Parameters() |
| 2370 |
respData = smb.SMBSessionSetupAndXResponse_Data() |
| 2371 |
sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters']) |
| 2372 |
sessionSetupData = smb.SMBSessionSetupAndX_Data() |
| 2373 |
sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength'] |
| 2374 |
sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength'] |
| 2375 |
sessionSetupData.fromString(SMBCommand['Data']) |
| 2376 |
connData['Capabilities'] = sessionSetupParameters['Capabilities'] |
| 2377 |
# Do the verification here, for just now we grant access |
| 2378 |
# TODO: Manage more UIDs for the same session |
| 2379 |
errorCode = STATUS_SUCCESS |
| 2380 |
connData['Uid'] = 10 |
| 2381 |
respParameters['Action'] = 0 |
| 2382 |
smbServer.log('User %s\\%s authenticated successfully (basic)' % (sessionSetupData['PrimaryDomain'], sessionSetupData['Account'])) |
| 2383 |
try: |
| 2384 |
jtr_dump_path = smbServer.getJTRdumpPath() |
| 2385 |
ntlm_hash_data = outputToJohnFormat( '', sessionSetupData['Account'], sessionSetupData['PrimaryDomain'], sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'] ) |
| 2386 |
smbServer.log(ntlm_hash_data['hash_string']) |
| 2387 |
if jtr_dump_path is not '': |
| 2388 |
writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], jtr_dump_path) |
| 2389 |
except: |
| 2390 |
smbServer.log("Could not write NTLM Hashes to the specified JTR_Dump_Path %s" % jtr_dump_path) |
| 2391 |
|
| 2392 |
respData['NativeOS'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS()) |
| 2393 |
respData['NativeLanMan'] = encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS()) |
| 2394 |
respSMBCommand['Parameters'] = respParameters |
| 2395 |
respSMBCommand['Data'] = respData |
| 2396 |
|
| 2397 |
# From now on, the client can ask for other commands |
| 2398 |
connData['Authenticated'] = True |
| 2399 |
# For now, just switching to nobody |
| 2400 |
#os.setregid(65534,65534) |
| 2401 |
#os.setreuid(65534,65534) |
| 2402 |
smbServer.setConnectionData(connId, connData) |
| 2403 |
|
| 2404 |
return [respSMBCommand], None, errorCode |
| 2405 |
|
| 2406 |
@staticmethod |
| 2407 |
def smbComNegotiate(connId, smbServer, SMBCommand, recvPacket ): |
| 2408 |
connData = smbServer.getConnectionData(connId, checkStatus = False) |
| 2409 |
connData['Pid'] = recvPacket['Pid'] |
| 2410 |
|
| 2411 |
SMBCommand = smb.SMBCommand(recvPacket['Data'][0]) |
| 2412 |
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_NEGOTIATE) |
| 2413 |
|
| 2414 |
resp = smb.NewSMBPacket() |
| 2415 |
resp['Flags1'] = smb.SMB.FLAGS1_REPLY |
| 2416 |
resp['Pid'] = connData['Pid'] |
| 2417 |
resp['Tid'] = recvPacket['Tid'] |
| 2418 |
resp['Mid'] = recvPacket['Mid'] |
| 2419 |
|
| 2420 |
# TODO: We support more dialects, and parse them accordingly |
| 2421 |
dialects = SMBCommand['Data'].split('\x02') |
| 2422 |
try: |
| 2423 |
index = dialects.index('NT LM 0.12\x00') - 1 |
| 2424 |
# Let's fill the data for NTLM |
| 2425 |
if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY: |
| 2426 |
resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_UNICODE |
| 2427 |
#resp['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS |
| 2428 |
_dialects_data = smb.SMBExtended_Security_Data() |
| 2429 |
_dialects_data['ServerGUID'] = 'A'*16 |
| 2430 |
blob = SPNEGO_NegTokenInit() |
| 2431 |
blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] |
| 2432 |
_dialects_data['SecurityBlob'] = blob.getData() |
| 2433 |
|
| 2434 |
_dialects_parameters = smb.SMBExtended_Security_Parameters() |
| 2435 |
_dialects_parameters['Capabilities'] = smb.SMB.CAP_EXTENDED_SECURITY | smb.SMB.CAP_USE_NT_ERRORS | smb.SMB.CAP_NT_SMBS | smb.SMB.CAP_UNICODE |
| 2436 |
_dialects_parameters['ChallengeLength'] = 0 |
| 2437 |
|
| 2438 |
else: |
| 2439 |
resp['Flags2'] = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_UNICODE |
| 2440 |
_dialects_parameters = smb.SMBNTLMDialect_Parameters() |
| 2441 |
_dialects_data= smb.SMBNTLMDialect_Data() |
| 2442 |
_dialects_data['Payload'] = '' |
| 2443 |
if 'EncryptionKey' in connData: |
| 2444 |
_dialects_data['Challenge'] = connData['EncryptionKey'] |
| 2445 |
_dialects_parameters['ChallengeLength'] = len(str(_dialects_data)) |
| 2446 |
else: |
| 2447 |
# TODO: Handle random challenges, now one that can be used with rainbow tables |
| 2448 |
_dialects_data['Challenge'] = '\x11\x22\x33\x44\x55\x66\x77\x88' |
| 2449 |
_dialects_parameters['ChallengeLength'] = 8 |
| 2450 |
_dialects_parameters['Capabilities'] = smb.SMB.CAP_USE_NT_ERRORS | smb.SMB.CAP_NT_SMBS |
| 2451 |
|
| 2452 |
# Let's see if we need to support RPC_REMOTE_APIS |
| 2453 |
config = smbServer.getServerConfig() |
| 2454 |
if config.has_option('global','rpc_apis'): |
| 2455 |
if config.getboolean('global', 'rpc_apis') is True: |
| 2456 |
_dialects_parameters['Capabilities'] |= smb.SMB.CAP_RPC_REMOTE_APIS |
| 2457 |
|
| 2458 |
_dialects_parameters['DialectIndex'] = index |
| 2459 |
_dialects_parameters['SecurityMode'] = smb.SMB.SECURITY_AUTH_ENCRYPTED | smb.SMB.SECURITY_SHARE_USER |
| 2460 |
_dialects_parameters['MaxMpxCount'] = 1 |
| 2461 |
_dialects_parameters['MaxNumberVcs'] = 1 |
| 2462 |
_dialects_parameters['MaxBufferSize'] = 64000 |
| 2463 |
_dialects_parameters['MaxRawSize'] = 65536 |
| 2464 |
_dialects_parameters['SessionKey'] = 0 |
| 2465 |
_dialects_parameters['LowDateTime'] = 0 |
| 2466 |
_dialects_parameters['HighDateTime'] = 0 |
| 2467 |
_dialects_parameters['ServerTimeZone'] = 0 |
| 2468 |
|
| 2469 |
|
| 2470 |
respSMBCommand['Data'] = _dialects_data |
| 2471 |
respSMBCommand['Parameters'] = _dialects_parameters |
| 2472 |
connData['_dialects_data'] = _dialects_data |
| 2473 |
connData['_dialects_parameters'] = _dialects_parameters |
| 2474 |
|
| 2475 |
except Exception as e: |
| 2476 |
# No NTLM throw an error |
| 2477 |
smbServer.log('smbComNegotiate: %s' % e, logging.ERROR) |
| 2478 |
respSMBCommand['Data'] = struct.pack('<H',0xffff) |
| 2479 |
|
| 2480 |
|
| 2481 |
smbServer.setConnectionData(connId, connData) |
| 2482 |
|
| 2483 |
resp.addCommand(respSMBCommand) |
| 2484 |
|
| 2485 |
return None, [resp], STATUS_SUCCESS |
| 2486 |
|
| 2487 |
@staticmethod |
| 2488 |
def default(connId, smbServer, SMBCommand, recvPacket): |
| 2489 |
# By default we return an SMB Packet with error not implemented |
| 2490 |
smbServer.log("Not implemented command: 0x%x" % recvPacket['Command'],logging.DEBUG) |
| 2491 |
packet = smb.NewSMBPacket() |
| 2492 |
packet['Flags1'] = smb.SMB.FLAGS1_REPLY |
| 2493 |
packet['Flags2'] = smb.SMB.FLAGS2_NT_STATUS |
| 2494 |
packet['Command'] = recvPacket['Command'] |
| 2495 |
packet['Pid'] = recvPacket['Pid'] |
| 2496 |
packet['Tid'] = recvPacket['Tid'] |
| 2497 |
packet['Mid'] = recvPacket['Mid'] |
| 2498 |
packet['Uid'] = recvPacket['Uid'] |
| 2499 |
packet['Data'] = '\x00\x00\x00' |
| 2500 |
errorCode = STATUS_NOT_IMPLEMENTED |
| 2501 |
packet['ErrorCode'] = errorCode >> 16 |
| 2502 |
packet['ErrorClass'] = errorCode & 0xff |
| 2503 |
|
| 2504 |
return None, [packet], errorCode |
| 2505 |
|
| 2506 |
class SMB2Commands: |
| 2507 |
@staticmethod |
| 2508 |
def smb2Negotiate(connId, smbServer, recvPacket, isSMB1 = False): |
| 2509 |
connData = smbServer.getConnectionData(connId, checkStatus = False) |
| 2510 |
|
| 2511 |
respPacket = smb2.SMB2Packet() |
| 2512 |
respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR |
| 2513 |
respPacket['Status'] = STATUS_SUCCESS |
| 2514 |
respPacket['CreditRequestResponse'] = 1 |
| 2515 |
respPacket['Command'] = smb2.SMB2_NEGOTIATE |
| 2516 |
respPacket['SessionID'] = 0 |
| 2517 |
if isSMB1 is False: |
| 2518 |
respPacket['MessageID'] = recvPacket['MessageID'] |
| 2519 |
else: |
| 2520 |
respPacket['MessageID'] = 0 |
| 2521 |
respPacket['TreeID'] = 0 |
| 2522 |
|
| 2523 |
|
| 2524 |
respSMBCommand = smb2.SMB2Negotiate_Response() |
| 2525 |
|
| 2526 |
respSMBCommand['SecurityMode'] = 1 |
| 2527 |
if isSMB1 is True: |
| 2528 |
# Let's first parse the packet to see if the client supports SMB2 |
| 2529 |
SMBCommand = smb.SMBCommand(recvPacket['Data'][0]) |
| 2530 |
|
| 2531 |
dialects = SMBCommand['Data'].split('\x02') |
| 2532 |
if 'SMB 2.002\x00' in dialects or 'SMB 2.???\x00' in dialects: |
| 2533 |
respSMBCommand['DialectRevision'] = smb2.SMB2_DIALECT_002 |
| 2534 |
else: |
| 2535 |
# Client does not support SMB2 fallbacking |
| 2536 |
raise Exception('SMB2 not supported, fallbacking') |
| 2537 |
else: |
| 2538 |
respSMBCommand['DialectRevision'] = smb2.SMB2_DIALECT_002 |
| 2539 |
respSMBCommand['ServerGuid'] = 'A'*16 |
| 2540 |
respSMBCommand['Capabilities'] = 0 |
| 2541 |
respSMBCommand['MaxTransactSize'] = 65536 |
| 2542 |
respSMBCommand['MaxReadSize'] = 65536 |
| 2543 |
respSMBCommand['MaxWriteSize'] = 65536 |
| 2544 |
respSMBCommand['SystemTime'] = getFileTime(calendar.timegm(time.gmtime())) |
| 2545 |
respSMBCommand['ServerStartTime'] = getFileTime(calendar.timegm(time.gmtime())) |
| 2546 |
respSMBCommand['SecurityBufferOffset'] = 0x80 |
| 2547 |
|
| 2548 |
blob = SPNEGO_NegTokenInit() |
| 2549 |
blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] |
| 2550 |
|
| 2551 |
respSMBCommand['Buffer'] = blob.getData() |
| 2552 |
respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer']) |
| 2553 |
|
| 2554 |
respPacket['Data'] = respSMBCommand |
| 2555 |
|
| 2556 |
smbServer.setConnectionData(connId, connData) |
| 2557 |
|
| 2558 |
return None, [respPacket], STATUS_SUCCESS |
| 2559 |
|
| 2560 |
@staticmethod |
| 2561 |
def smb2SessionSetup(connId, smbServer, recvPacket): |
| 2562 |
connData = smbServer.getConnectionData(connId, checkStatus = False) |
| 2563 |
|
| 2564 |
respSMBCommand = smb2.SMB2SessionSetup_Response() |
| 2565 |
|
| 2566 |
sessionSetupData = smb2.SMB2SessionSetup(recvPacket['Data']) |
| 2567 |
|
| 2568 |
connData['Capabilities'] = sessionSetupData['Capabilities'] |
| 2569 |
|
| 2570 |
securityBlob = sessionSetupData['Buffer'] |
| 2571 |
|
| 2572 |
rawNTLM = False |
| 2573 |
if struct.unpack('B',securityBlob[0])[0] == ASN1_AID: |
| 2574 |
# NEGOTIATE packet |
| 2575 |
blob = SPNEGO_NegTokenInit(securityBlob) |
| 2576 |
token = blob['MechToken'] |
| 2577 |
if len(blob['MechTypes'][0]) > 0: |
| 2578 |
# Is this GSSAPI NTLM or something else we don't support? |
| 2579 |
mechType = blob['MechTypes'][0] |
| 2580 |
if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']: |
| 2581 |
# Nope, do we know it? |
| 2582 |
if mechType in MechTypes: |
| 2583 |
mechStr = MechTypes[mechType] |
| 2584 |
else: |
| 2585 |
mechStr = hexlify(mechType) |
| 2586 |
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL) |
| 2587 |
# We don't know the token, we answer back again saying |
| 2588 |
# we just support NTLM. |
| 2589 |
# ToDo: Build this into a SPNEGO_NegTokenResp() |
| 2590 |
respToken = '\xa1\x15\x30\x13\xa0\x03\x0a\x01\x03\xa1\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a' |
| 2591 |
respSMBCommand['SecurityBufferOffset'] = 0x48 |
| 2592 |
respSMBCommand['SecurityBufferLength'] = len(respToken) |
| 2593 |
respSMBCommand['Buffer'] = respToken |
| 2594 |
|
| 2595 |
return [respSMBCommand], None, STATUS_MORE_PROCESSING_REQUIRED |
| 2596 |
elif struct.unpack('B',securityBlob[0])[0] == ASN1_SUPPORTED_MECH: |
| 2597 |
# AUTH packet |
| 2598 |
blob = SPNEGO_NegTokenResp(securityBlob) |
| 2599 |
token = blob['ResponseToken'] |
| 2600 |
else: |
| 2601 |
# No GSSAPI stuff, raw NTLMSSP |
| 2602 |
rawNTLM = True |
| 2603 |
token = securityBlob |
| 2604 |
|
| 2605 |
# Here we only handle NTLMSSP, depending on what stage of the |
| 2606 |
# authentication we are, we act on it |
| 2607 |
messageType = struct.unpack('<L',token[len('NTLMSSP\x00'):len('NTLMSSP\x00')+4])[0] |
| 2608 |
|
| 2609 |
if messageType == 0x01: |
| 2610 |
# NEGOTIATE_MESSAGE |
| 2611 |
negotiateMessage = ntlm.NTLMAuthNegotiate() |
| 2612 |
negotiateMessage.fromString(token) |
| 2613 |
# Let's store it in the connection data |
| 2614 |
connData['NEGOTIATE_MESSAGE'] = negotiateMessage |
| 2615 |
# Let's build the answer flags |
| 2616 |
# TODO: Parse all the flags. With this we're leaving some clients out |
| 2617 |
|
| 2618 |
ansFlags = 0 |
| 2619 |
|
| 2620 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_56: |
| 2621 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_56 |
| 2622 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_128: |
| 2623 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_128 |
| 2624 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH: |
| 2625 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH |
| 2626 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: |
| 2627 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY |
| 2628 |
if negotiateMessage['flags'] & ntlm.NTLMSSP_NEGOTIATE_UNICODE: |
| 2629 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_UNICODE |
| 2630 |
if negotiateMessage['flags'] & ntlm.NTLM_NEGOTIATE_OEM: |
| 2631 |
ansFlags |= ntlm.NTLM_NEGOTIATE_OEM |
| 2632 |
|
| 2633 |
ansFlags |= ntlm.NTLMSSP_NEGOTIATE_VERSION | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO | ntlm.NTLMSSP_TARGET_TYPE_SERVER | ntlm.NTLMSSP_NEGOTIATE_NTLM | ntlm.NTLMSSP_REQUEST_TARGET |
| 2634 |
|
| 2635 |
# Generate the AV_PAIRS |
| 2636 |
av_pairs = ntlm.AV_PAIRS() |
| 2637 |
# TODO: Put the proper data from SMBSERVER config |
| 2638 |
av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] = smbServer.getServerName().encode('utf-16le') |
| 2639 |
av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = smbServer.getServerDomain().encode('utf-16le') |
| 2640 |
av_pairs[ntlm.NTLMSSP_AV_TIME] = struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000) ) |
| 2641 |
|
| 2642 |
challengeMessage = ntlm.NTLMAuthChallenge() |
| 2643 |
challengeMessage['flags'] = ansFlags |
| 2644 |
challengeMessage['domain_len'] = len(smbServer.getServerDomain().encode('utf-16le')) |
| 2645 |
challengeMessage['domain_max_len'] = challengeMessage['domain_len'] |
| 2646 |
challengeMessage['domain_offset'] = 40 + 16 |
| 2647 |
challengeMessage['challenge'] = smbServer.getSMBChallenge() |
| 2648 |
challengeMessage['domain_name'] = smbServer.getServerDomain().encode('utf-16le') |
| 2649 |
challengeMessage['TargetInfoFields_len'] = len(av_pairs) |
| 2650 |
challengeMessage['TargetInfoFields_max_len'] = len(av_pairs) |
| 2651 |
challengeMessage['TargetInfoFields'] = av_pairs |
| 2652 |
challengeMessage['TargetInfoFields_offset'] = 40 + 16 + len(challengeMessage['domain_name']) |
| 2653 |
challengeMessage['Version'] = '\xff'*8 |
| 2654 |
challengeMessage['VersionLen'] = 8 |
| 2655 |
|
| 2656 |
if rawNTLM is False: |
| 2657 |
respToken = SPNEGO_NegTokenResp() |
| 2658 |
# accept-incomplete. We want more data |
| 2659 |
respToken['NegResult'] = '\x01' |
| 2660 |
respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] |
| 2661 |
|
| 2662 |
respToken['ResponseToken'] = challengeMessage.getData() |
| 2663 |
else: |
| 2664 |
respToken = challengeMessage |
| 2665 |
|
| 2666 |
# Setting the packet to STATUS_MORE_PROCESSING |
| 2667 |
errorCode = STATUS_MORE_PROCESSING_REQUIRED |
| 2668 |
# Let's set up an UID for this connection and store it |
| 2669 |
# in the connection's data |
| 2670 |
# Picking a fixed value |
| 2671 |
# TODO: Manage more UIDs for the same session |
| 2672 |
connData['Uid'] = random.randint(1,0xffffffff) |
| 2673 |
# Let's store it in the connection data |
| 2674 |
connData['CHALLENGE_MESSAGE'] = challengeMessage |
| 2675 |
|
| 2676 |
elif messageType == 0x02: |
| 2677 |
# CHALLENGE_MESSAGE |
| 2678 |
raise Exception('Challenge Message raise, not implemented!') |
| 2679 |
elif messageType == 0x03: |
| 2680 |
# AUTHENTICATE_MESSAGE, here we deal with authentication |
| 2681 |
authenticateMessage = ntlm.NTLMAuthChallengeResponse() |
| 2682 |
authenticateMessage.fromString(token) |
| 2683 |
smbServer.log("AUTHENTICATE_MESSAGE (%s\\%s,%s)" % (authenticateMessage['domain_name'], authenticateMessage['user_name'], authenticateMessage['host_name'])) |
| 2684 |
# TODO: Check the credentials! Now granting permissions |
| 2685 |
|
| 2686 |
respToken = SPNEGO_NegTokenResp() |
| 2687 |
# accept-completed |
| 2688 |
respToken['NegResult'] = '\x00' |
| 2689 |
|
| 2690 |
# Status SUCCESS |
| 2691 |
errorCode = STATUS_SUCCESS |
| 2692 |
smbServer.log('User %s\\%s authenticated successfully' % (authenticateMessage['user_name'], authenticateMessage['host_name'])) |
| 2693 |
# Let's store it in the connection data |
| 2694 |
connData['AUTHENTICATE_MESSAGE'] = authenticateMessage |
| 2695 |
try: |
| 2696 |
jtr_dump_path = smbServer.getJTRdumpPath() |
| 2697 |
ntlm_hash_data = outputToJohnFormat( connData['CHALLENGE_MESSAGE']['challenge'], authenticateMessage['user_name'], authenticateMessage['domain_name'], authenticateMessage['lanman'], authenticateMessage['ntlm'] ) |
| 2698 |
smbServer.log(ntlm_hash_data['hash_string']) |
| 2699 |
if jtr_dump_path is not '': |
| 2700 |
writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], jtr_dump_path) |
| 2701 |
except: |
| 2702 |
smbServer.log("Could not write NTLM Hashes to the specified JTR_Dump_Path %s" % jtr_dump_path) |
| 2703 |
respSMBCommand['SessionFlags'] = 1 |
| 2704 |
else: |
| 2705 |
raise Exception("Unknown NTLMSSP MessageType %d" % messageType) |
| 2706 |
|
| 2707 |
respSMBCommand['SecurityBufferOffset'] = 0x48 |
| 2708 |
respSMBCommand['SecurityBufferLength'] = len(respToken) |
| 2709 |
respSMBCommand['Buffer'] = respToken.getData() |
| 2710 |
|
| 2711 |
# From now on, the client can ask for other commands |
| 2712 |
connData['Authenticated'] = True |
| 2713 |
# For now, just switching to nobody |
| 2714 |
#os.setregid(65534,65534) |
| 2715 |
#os.setreuid(65534,65534) |
| 2716 |
smbServer.setConnectionData(connId, connData) |
| 2717 |
|
| 2718 |
return [respSMBCommand], None, errorCode |
| 2719 |
|
| 2720 |
@staticmethod |
| 2721 |
def smb2TreeConnect(connId, smbServer, recvPacket): |
| 2722 |
connData = smbServer.getConnectionData(connId) |
| 2723 |
|
| 2724 |
respPacket = smb2.SMB2Packet() |
| 2725 |
respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR |
| 2726 |
respPacket['Status'] = STATUS_SUCCESS |
| 2727 |
respPacket['CreditRequestResponse'] = 1 |
| 2728 |
respPacket['Command'] = recvPacket['Command'] |
| 2729 |
respPacket['SessionID'] = connData['Uid'] |
| 2730 |
respPacket['Reserved'] = recvPacket['Reserved'] |
| 2731 |
respPacket['MessageID'] = recvPacket['MessageID'] |
| 2732 |
respPacket['TreeID'] = recvPacket['TreeID'] |
| 2733 |
|
| 2734 |
respSMBCommand = smb2.SMB2TreeConnect_Response() |
| 2735 |
|
| 2736 |
treeConnectRequest = smb2.SMB2TreeConnect(recvPacket['Data']) |
| 2737 |
|
| 2738 |
errorCode = STATUS_SUCCESS |
| 2739 |
|
| 2740 |
## Process here the request, does the share exist? |
| 2741 |
path = str(recvPacket)[treeConnectRequest['PathOffset']:][:treeConnectRequest['PathLength']] |
| 2742 |
UNCOrShare = path.decode('utf-16le') |
| 2743 |
|
| 2744 |
# Is this a UNC? |
| 2745 |
if ntpath.ismount(UNCOrShare): |
| 2746 |
path = UNCOrShare.split('\\')[3] |
| 2747 |
else: |
| 2748 |
path = ntpath.basename(UNCOrShare) |
| 2749 |
|
| 2750 |
share = searchShare(connId, path.upper(), smbServer) |
| 2751 |
if share is not None: |
| 2752 |
# Simple way to generate a Tid |
| 2753 |
if len(connData['ConnectedShares']) == 0: |
| 2754 |
tid = 1 |
| 2755 |
else: |
| 2756 |
tid = connData['ConnectedShares'].keys()[-1] + 1 |
| 2757 |
connData['ConnectedShares'][tid] = share |
| 2758 |
connData['ConnectedShares'][tid]['shareName'] = path |
| 2759 |
respPacket['TreeID'] = tid |
| 2760 |
smbServer.log("Connecting Share(%d:%s)" % (tid,path)) |
| 2761 |
else: |
| 2762 |
smbServer.log("SMB2_TREE_CONNECT not found %s" % path, logging.ERROR) |
| 2763 |
errorCode = STATUS_OBJECT_PATH_NOT_FOUND |
| 2764 |
respPacket['Status'] = errorCode |
| 2765 |
## |
| 2766 |
|
| 2767 |
if path == 'IPC$': |
| 2768 |
respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_PIPE |
| 2769 |
respSMBCommand['ShareFlags'] = 0x30 |
| 2770 |
else: |
| 2771 |
respSMBCommand['ShareType'] = smb2.SMB2_SHARE_TYPE_DISK |
| 2772 |
respSMBCommand['ShareFlags'] = 0x0 |
| 2773 |
|
| 2774 |
respSMBCommand['Capabilities'] = 0 |
| 2775 |
respSMBCommand['MaximalAccess'] = 0x000f01ff |
| 2776 |
|
| 2777 |
respPacket['Data'] = respSMBCommand |
| 2778 |
|
| 2779 |
smbServer.setConnectionData(connId, connData) |
| 2780 |
|
| 2781 |
return None, [respPacket], errorCode |
| 2782 |
|
| 2783 |
@staticmethod |
| 2784 |
def smb2Create(connId, smbServer, recvPacket): |
| 2785 |
connData = smbServer.getConnectionData(connId) |
| 2786 |
|
| 2787 |
respSMBCommand = smb2.SMB2Create_Response() |
| 2788 |
|
| 2789 |
ntCreateRequest = smb2.SMB2Create(recvPacket['Data']) |
| 2790 |
|
| 2791 |
respSMBCommand['Buffer'] = '\x00' |
| 2792 |
# Get the Tid associated |
| 2793 |
if recvPacket['TreeID'] in connData['ConnectedShares']: |
| 2794 |
# If we have a rootFid, the path is relative to that fid |
| 2795 |
errorCode = STATUS_SUCCESS |
| 2796 |
if 'path' in connData['ConnectedShares'][recvPacket['TreeID']]: |
| 2797 |
path = connData['ConnectedShares'][recvPacket['TreeID']]['path'] |
| 2798 |
else: |
| 2799 |
path = 'NONE' |
| 2800 |
errorCode = STATUS_ACCESS_DENIED |
| 2801 |
|
| 2802 |
deleteOnClose = False |
| 2803 |
|
| 2804 |
fileName = os.path.normpath(ntCreateRequest['Buffer'][:ntCreateRequest['NameLength']].decode('utf-16le').replace('\\','/')) |
| 2805 |
if len(fileName) > 0 and (fileName[0] == '/' or fileName[0] == '\\'): |
| 2806 |
# strip leading '/' |
| 2807 |
fileName = fileName[1:] |
| 2808 |
pathName = os.path.join(path,fileName) |
| 2809 |
createDisposition = ntCreateRequest['CreateDisposition'] |
| 2810 |
mode = 0 |
| 2811 |
|
| 2812 |
if createDisposition == smb2.FILE_SUPERSEDE: |
| 2813 |
mode |= os.O_TRUNC | os.O_CREAT |
| 2814 |
elif createDisposition & smb2.FILE_OVERWRITE_IF == smb2.FILE_OVERWRITE_IF: |
| 2815 |
mode |= os.O_TRUNC | os.O_CREAT |
| 2816 |
elif createDisposition & smb2.FILE_OVERWRITE == smb2.FILE_OVERWRITE: |
| 2817 |
if os.path.exists(pathName) is True: |
| 2818 |
mode |= os.O_TRUNC |
| 2819 |
else: |
| 2820 |
errorCode = STATUS_NO_SUCH_FILE |
| 2821 |
elif createDisposition & smb2.FILE_OPEN_IF == smb2.FILE_OPEN_IF: |
| 2822 |
if os.path.exists(pathName) is True: |
| 2823 |
mode |= os.O_TRUNC |
| 2824 |
else: |
| 2825 |
mode |= os.O_TRUNC | os.O_CREAT |
| 2826 |
elif createDisposition & smb2.FILE_CREATE == smb2.FILE_CREATE: |
| 2827 |
if os.path.exists(pathName) is True: |
| 2828 |
errorCode = STATUS_OBJECT_NAME_COLLISION |
| 2829 |
else: |
| 2830 |
mode |= os.O_CREAT |
| 2831 |
elif createDisposition & smb2.FILE_OPEN == smb2.FILE_OPEN: |
| 2832 |
if os.path.exists(pathName) is not True and (unicode(pathName) in smbServer.getRegisteredNamedPipes()) is not True: |
| 2833 |
errorCode = STATUS_NO_SUCH_FILE |
| 2834 |
|
| 2835 |
if errorCode == STATUS_SUCCESS: |
| 2836 |
desiredAccess = ntCreateRequest['DesiredAccess'] |
| 2837 |
if (desiredAccess & smb2.FILE_READ_DATA) or (desiredAccess & smb2.GENERIC_READ): |
| 2838 |
mode |= os.O_RDONLY |
| 2839 |
if (desiredAccess & smb2.FILE_WRITE_DATA) or (desiredAccess & smb2.GENERIC_WRITE): |
| 2840 |
if (desiredAccess & smb2.FILE_READ_DATA) or (desiredAccess & smb2.GENERIC_READ): |
| 2841 |
mode |= os.O_RDWR #| os.O_APPEND |
| 2842 |
else: |
| 2843 |
mode |= os.O_WRONLY #| os.O_APPEND |
| 2844 |
if desiredAccess & smb2.GENERIC_ALL: |
| 2845 |
mode |= os.O_RDWR #| os.O_APPEND |
| 2846 |
|
| 2847 |
createOptions = ntCreateRequest['CreateOptions'] |
| 2848 |
if mode & os.O_CREAT == os.O_CREAT: |
| 2849 |
if createOptions & smb2.FILE_DIRECTORY_FILE == smb2.FILE_DIRECTORY_FILE: |
| 2850 |
try: |
| 2851 |
# Let's create the directory |
| 2852 |
os.mkdir(pathName) |
| 2853 |
mode = os.O_RDONLY |
| 2854 |
except Exception as e: |
| 2855 |
smbServer.log("SMB2_CREATE: %s,%s,%s" % (pathName,mode,e),logging.ERROR) |
| 2856 |
errorCode = STATUS_ACCESS_DENIED |
| 2857 |
if createOptions & smb2.FILE_NON_DIRECTORY_FILE == smb2.FILE_NON_DIRECTORY_FILE: |
| 2858 |
# If the file being opened is a directory, the server MUST fail the request with |
| 2859 |
# STATUS_FILE_IS_A_DIRECTORY in the Status field of the SMB Header in the server |
| 2860 |
# response. |
| 2861 |
if os.path.isdir(pathName) is True: |
| 2862 |
errorCode = STATUS_FILE_IS_A_DIRECTORY |
| 2863 |
|
| 2864 |
if createOptions & smb2.FILE_DELETE_ON_CLOSE == smb2.FILE_DELETE_ON_CLOSE: |
| 2865 |
deleteOnClose = True |
| 2866 |
|
| 2867 |
if errorCode == STATUS_SUCCESS: |
| 2868 |
try: |
| 2869 |
if os.path.isdir(pathName) and sys.platform == 'win32': |
| 2870 |
fid = VOID_FILE_DESCRIPTOR |
| 2871 |
else: |
| 2872 |
if sys.platform == 'win32': |
| 2873 |
mode |= os.O_BINARY |
| 2874 |
if unicode(pathName) in smbServer.getRegisteredNamedPipes(): |
| 2875 |
fid = PIPE_FILE_DESCRIPTOR |
| 2876 |
sock = socket.socket() |
| 2877 |
sock.connect(smbServer.getRegisteredNamedPipes()[unicode(pathName)]) |
| 2878 |
else: |
| 2879 |
fid = os.open(pathName, mode) |
| 2880 |
except Exception as e: |
| 2881 |
smbServer.log("SMB2_CREATE: %s,%s,%s" % (pathName,mode,e),logging.ERROR) |
| 2882 |
#print e |
| 2883 |
fid = 0 |
| 2884 |
errorCode = STATUS_ACCESS_DENIED |
| 2885 |
else: |
| 2886 |
errorCode = STATUS_SMB_BAD_TID |
| 2887 |
|
| 2888 |
if errorCode == STATUS_SUCCESS: |
| 2889 |
# Simple way to generate a fid |
| 2890 |
fakefid = uuid.generate() |
| 2891 |
|
| 2892 |
respSMBCommand['FileID'] = fakefid |
| 2893 |
respSMBCommand['CreateAction'] = createDisposition |
| 2894 |
|
| 2895 |
if fid == PIPE_FILE_DESCRIPTOR: |
| 2896 |
respSMBCommand['CreationTime'] = 0 |
| 2897 |
respSMBCommand['LastAccessTime'] = 0 |
| 2898 |
respSMBCommand['LastWriteTime'] = 0 |
| 2899 |
respSMBCommand['ChangeTime'] = 0 |
| 2900 |
respSMBCommand['AllocationSize'] = 4096 |
| 2901 |
respSMBCommand['EndOfFile'] = 0 |
| 2902 |
respSMBCommand['FileAttributes'] = 0x80 |
| 2903 |
|
| 2904 |
else: |
| 2905 |
if os.path.isdir(pathName): |
| 2906 |
respSMBCommand['FileAttributes'] = smb.SMB_FILE_ATTRIBUTE_DIRECTORY |
| 2907 |
else: |
| 2908 |
respSMBCommand['FileAttributes'] = ntCreateRequest['FileAttributes'] |
| 2909 |
# Let's get this file's information |
| 2910 |
respInfo, errorCode = queryPathInformation('',pathName,level= smb.SMB_QUERY_FILE_ALL_INFO) |
| 2911 |
if errorCode == STATUS_SUCCESS: |
| 2912 |
respSMBCommand['CreationTime'] = respInfo['CreationTime'] |
| 2913 |
respSMBCommand['LastAccessTime'] = respInfo['LastAccessTime'] |
| 2914 |
respSMBCommand['LastWriteTime'] = respInfo['LastWriteTime'] |
| 2915 |
respSMBCommand['LastChangeTime'] = respInfo['LastChangeTime'] |
| 2916 |
respSMBCommand['FileAttributes'] = respInfo['ExtFileAttributes'] |
| 2917 |
respSMBCommand['AllocationSize'] = respInfo['AllocationSize'] |
| 2918 |
respSMBCommand['EndOfFile'] = respInfo['EndOfFile'] |
| 2919 |
|
| 2920 |
if errorCode == STATUS_SUCCESS: |
| 2921 |
# Let's store the fid for the connection |
| 2922 |
# smbServer.log('Create file %s, mode:0x%x' % (pathName, mode)) |
| 2923 |
connData['OpenedFiles'][fakefid] = {} |
| 2924 |
connData['OpenedFiles'][fakefid]['FileHandle'] = fid |
| 2925 |
connData['OpenedFiles'][fakefid]['FileName'] = pathName |
| 2926 |
connData['OpenedFiles'][fakefid]['DeleteOnClose'] = deleteOnClose |
| 2927 |
connData['OpenedFiles'][fakefid]['Open'] = {} |
| 2928 |
connData['OpenedFiles'][fakefid]['Open']['EnumerationLocation'] = 0 |
| 2929 |
connData['OpenedFiles'][fakefid]['Open']['EnumerationSearchPattern'] = '' |
| 2930 |
if fid == PIPE_FILE_DESCRIPTOR: |
| 2931 |
connData['OpenedFiles'][fakefid]['Socket'] = sock |
| 2932 |
else: |
| 2933 |
respSMBCommand = smb2.SMB2Error() |
| 2934 |
|
| 2935 |
if errorCode == STATUS_SUCCESS: |
| 2936 |
connData['LastRequest']['SMB2_CREATE'] = respSMBCommand |
| 2937 |
smbServer.setConnectionData(connId, connData) |
| 2938 |
|
| 2939 |
return [respSMBCommand], None, errorCode |
| 2940 |
|
| 2941 |
@staticmethod |
| 2942 |
def smb2Close(connId, smbServer, recvPacket): |
| 2943 |
connData = smbServer.getConnectionData(connId) |
| 2944 |
|
| 2945 |
respSMBCommand = smb2.SMB2Close_Response() |
| 2946 |
|
| 2947 |
closeRequest = smb2.SMB2Close(recvPacket['Data']) |
| 2948 |
|
| 2949 |
if str(closeRequest['FileID']) == '\xff'*16: |
| 2950 |
# Let's take the data from the lastRequest |
| 2951 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 2952 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 2953 |
else: |
| 2954 |
fileID = str(closeRequest['FileID']) |
| 2955 |
else: |
| 2956 |
fileID = str(closeRequest['FileID']) |
| 2957 |
|
| 2958 |
if fileID in connData['OpenedFiles']: |
| 2959 |
errorCode = STATUS_SUCCESS |
| 2960 |
fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] |
| 2961 |
pathName = connData['OpenedFiles'][fileID]['FileName'] |
| 2962 |
infoRecord = None |
| 2963 |
try: |
| 2964 |
if fileHandle == PIPE_FILE_DESCRIPTOR: |
| 2965 |
connData['OpenedFiles'][fileID]['Socket'].close() |
| 2966 |
elif fileHandle != VOID_FILE_DESCRIPTOR: |
| 2967 |
os.close(fileHandle) |
| 2968 |
infoRecord, errorCode = queryFileInformation(os.path.dirname(pathName), os.path.basename(pathName), smb2.SMB2_FILE_NETWORK_OPEN_INFO) |
| 2969 |
except Exception as e: |
| 2970 |
smbServer.log("SMB2_CLOSE %s" % e, logging.ERROR) |
| 2971 |
errorCode = STATUS_INVALID_HANDLE |
| 2972 |
else: |
| 2973 |
# Check if the file was marked for removal |
| 2974 |
if connData['OpenedFiles'][fileID]['DeleteOnClose'] is True: |
| 2975 |
try: |
| 2976 |
if os.path.isdir(pathName): |
| 2977 |
shutil.rmtree(connData['OpenedFiles'][fileID]['FileName']) |
| 2978 |
else: |
| 2979 |
os.remove(connData['OpenedFiles'][fileID]['FileName']) |
| 2980 |
except Exception as e: |
| 2981 |
smbServer.log("SMB2_CLOSE %s" % e, logging.ERROR) |
| 2982 |
errorCode = STATUS_ACCESS_DENIED |
| 2983 |
|
| 2984 |
# Now fill out the response |
| 2985 |
if infoRecord is not None: |
| 2986 |
respSMBCommand['CreationTime'] = infoRecord['CreationTime'] |
| 2987 |
respSMBCommand['LastAccessTime'] = infoRecord['LastAccessTime'] |
| 2988 |
respSMBCommand['LastWriteTime'] = infoRecord['LastWriteTime'] |
| 2989 |
respSMBCommand['ChangeTime'] = infoRecord['ChangeTime'] |
| 2990 |
respSMBCommand['AllocationSize'] = infoRecord['AllocationSize'] |
| 2991 |
respSMBCommand['EndofFile'] = infoRecord['EndOfFile'] |
| 2992 |
respSMBCommand['FileAttributes'] = infoRecord['FileAttributes'] |
| 2993 |
if errorCode == STATUS_SUCCESS: |
| 2994 |
del(connData['OpenedFiles'][fileID]) |
| 2995 |
else: |
| 2996 |
errorCode = STATUS_INVALID_HANDLE |
| 2997 |
|
| 2998 |
smbServer.setConnectionData(connId, connData) |
| 2999 |
return [respSMBCommand], None, errorCode |
| 3000 |
|
| 3001 |
@staticmethod |
| 3002 |
def smb2QueryInfo(connId, smbServer, recvPacket): |
| 3003 |
connData = smbServer.getConnectionData(connId) |
| 3004 |
|
| 3005 |
respSMBCommand = smb2.SMB2QueryInfo_Response() |
| 3006 |
|
| 3007 |
queryInfo = smb2.SMB2QueryInfo(recvPacket['Data']) |
| 3008 |
|
| 3009 |
errorCode = STATUS_SUCCESS |
| 3010 |
|
| 3011 |
respSMBCommand['OutputBufferOffset'] = 0x48 |
| 3012 |
respSMBCommand['Buffer'] = '\x00' |
| 3013 |
|
| 3014 |
if str(queryInfo['FileID']) == '\xff'*16: |
| 3015 |
# Let's take the data from the lastRequest |
| 3016 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 3017 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 3018 |
else: |
| 3019 |
fileID = str(queryInfo['FileID']) |
| 3020 |
else: |
| 3021 |
fileID = str(queryInfo['FileID']) |
| 3022 |
|
| 3023 |
if recvPacket['TreeID'] in connData['ConnectedShares']: |
| 3024 |
if fileID in connData['OpenedFiles']: |
| 3025 |
fileName = connData['OpenedFiles'][fileID]['FileName'] |
| 3026 |
|
| 3027 |
if queryInfo['InfoType'] == smb2.SMB2_0_INFO_FILE: |
| 3028 |
if queryInfo['FileInfoClass'] == smb2.SMB2_FILE_INTERNAL_INFO: |
| 3029 |
# No need to call queryFileInformation, we have the data here |
| 3030 |
infoRecord = smb2.FileInternalInformation() |
| 3031 |
infoRecord['IndexNumber'] = fileID |
| 3032 |
else: |
| 3033 |
infoRecord, errorCode = queryFileInformation(os.path.dirname(fileName), os.path.basename(fileName), queryInfo['FileInfoClass']) |
| 3034 |
elif queryInfo['InfoType'] == smb2.SMB2_0_INFO_FILESYSTEM: |
| 3035 |
infoRecord = queryFsInformation(os.path.dirname(fileName), os.path.basename(fileName), queryInfo['FileInfoClass']) |
| 3036 |
elif queryInfo['InfoType'] == smb2.SMB2_0_INFO_SECURITY: |
| 3037 |
# Failing for now, until we support it |
| 3038 |
infoRecord = None |
| 3039 |
errorCode = STATUS_ACCESS_DENIED |
| 3040 |
else: |
| 3041 |
smbServer.log("queryInfo not supported (%x)" % queryInfo['InfoType'], logging.ERROR) |
| 3042 |
|
| 3043 |
if infoRecord is not None: |
| 3044 |
respSMBCommand['OutputBufferLength'] = len(infoRecord) |
| 3045 |
respSMBCommand['Buffer'] = infoRecord |
| 3046 |
else: |
| 3047 |
errorCode = STATUS_INVALID_HANDLE |
| 3048 |
else: |
| 3049 |
errorCode = STATUS_SMB_BAD_TID |
| 3050 |
|
| 3051 |
|
| 3052 |
smbServer.setConnectionData(connId, connData) |
| 3053 |
return [respSMBCommand], None, errorCode |
| 3054 |
|
| 3055 |
@staticmethod |
| 3056 |
def smb2SetInfo(connId, smbServer, recvPacket): |
| 3057 |
connData = smbServer.getConnectionData(connId) |
| 3058 |
|
| 3059 |
respSMBCommand = smb2.SMB2SetInfo_Response() |
| 3060 |
|
| 3061 |
setInfo = smb2.SMB2SetInfo(recvPacket['Data']) |
| 3062 |
|
| 3063 |
errorCode = STATUS_SUCCESS |
| 3064 |
|
| 3065 |
if str(setInfo['FileID']) == '\xff'*16: |
| 3066 |
# Let's take the data from the lastRequest |
| 3067 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 3068 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 3069 |
else: |
| 3070 |
fileID = str(setInfo['FileID']) |
| 3071 |
else: |
| 3072 |
fileID = str(setInfo['FileID']) |
| 3073 |
|
| 3074 |
if recvPacket['TreeID'] in connData['ConnectedShares']: |
| 3075 |
path = connData['ConnectedShares'][recvPacket['TreeID']]['path'] |
| 3076 |
if fileID in connData['OpenedFiles']: |
| 3077 |
pathName = connData['OpenedFiles'][fileID]['FileName'] |
| 3078 |
|
| 3079 |
if setInfo['InfoType'] == smb2.SMB2_0_INFO_FILE: |
| 3080 |
# The file information is being set |
| 3081 |
informationLevel = setInfo['FileInfoClass'] |
| 3082 |
if informationLevel == smb2.SMB2_FILE_DISPOSITION_INFO: |
| 3083 |
infoRecord = smb.SMBSetFileDispositionInfo(setInfo['Buffer']) |
| 3084 |
if infoRecord['DeletePending'] > 0: |
| 3085 |
# Mark this file for removal after closed |
| 3086 |
connData['OpenedFiles'][fileID]['DeleteOnClose'] = True |
| 3087 |
elif informationLevel == smb2.SMB2_FILE_BASIC_INFO: |
| 3088 |
infoRecord = smb.SMBSetFileBasicInfo(setInfo['Buffer']) |
| 3089 |
# Creation time won't be set, the other ones we play with. |
| 3090 |
atime = infoRecord['LastWriteTime'] |
| 3091 |
if atime == 0: |
| 3092 |
atime = -1 |
| 3093 |
else: |
| 3094 |
atime = getUnixTime(atime) |
| 3095 |
mtime = infoRecord['ChangeTime'] |
| 3096 |
if mtime == 0: |
| 3097 |
mtime = -1 |
| 3098 |
else: |
| 3099 |
mtime = getUnixTime(mtime) |
| 3100 |
if atime > 0 and mtime > 0: |
| 3101 |
os.utime(pathName,(atime,mtime)) |
| 3102 |
elif informationLevel == smb2.SMB2_FILE_END_OF_FILE_INFO: |
| 3103 |
fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] |
| 3104 |
infoRecord = smb.SMBSetFileEndOfFileInfo(setInfo['Buffer']) |
| 3105 |
if infoRecord['EndOfFile'] > 0: |
| 3106 |
os.lseek(fileHandle, infoRecord['EndOfFile']-1, 0) |
| 3107 |
os.write(fileHandle, '\x00') |
| 3108 |
elif informationLevel == smb2.SMB2_FILE_RENAME_INFO: |
| 3109 |
renameInfo = smb2.FILE_RENAME_INFORMATION_TYPE_2(setInfo['Buffer']) |
| 3110 |
newPathName = os.path.join(path,renameInfo['FileName'].decode('utf-16le').replace('\\', '/')) |
| 3111 |
if renameInfo['ReplaceIfExists'] == 0 and os.path.exists(newPathName): |
| 3112 |
return [smb2.SMB2Error()], None, STATUS_OBJECT_NAME_COLLISION |
| 3113 |
try: |
| 3114 |
os.rename(pathName,newPathName) |
| 3115 |
connData['OpenedFiles'][fileID]['FileName'] = newPathName |
| 3116 |
except Exception as e: |
| 3117 |
smbServer.log("smb2SetInfo: %s" % e, logging.ERROR) |
| 3118 |
errorCode = STATUS_ACCESS_DENIED |
| 3119 |
else: |
| 3120 |
smbServer.log('Unknown level for set file info! 0x%x' % informationLevel, logging.ERROR) |
| 3121 |
# UNSUPPORTED |
| 3122 |
errorCode = STATUS_NOT_SUPPORTED |
| 3123 |
#elif setInfo['InfoType'] == smb2.SMB2_0_INFO_FILESYSTEM: |
| 3124 |
# # The underlying object store information is being set. |
| 3125 |
# setInfo = queryFsInformation('/', fileName, queryInfo['FileInfoClass']) |
| 3126 |
#elif setInfo['InfoType'] == smb2.SMB2_0_INFO_SECURITY: |
| 3127 |
# # The security information is being set. |
| 3128 |
# # Failing for now, until we support it |
| 3129 |
# infoRecord = None |
| 3130 |
# errorCode = STATUS_ACCESS_DENIED |
| 3131 |
#elif setInfo['InfoType'] == smb2.SMB2_0_INFO_QUOTA: |
| 3132 |
# # The underlying object store quota information is being set. |
| 3133 |
# setInfo = queryFsInformation('/', fileName, queryInfo['FileInfoClass']) |
| 3134 |
else: |
| 3135 |
smbServer.log("setInfo not supported (%x)" % setInfo['InfoType'], logging.ERROR) |
| 3136 |
|
| 3137 |
else: |
| 3138 |
errorCode = STATUS_INVALID_HANDLE |
| 3139 |
else: |
| 3140 |
errorCode = STATUS_SMB_BAD_TID |
| 3141 |
|
| 3142 |
|
| 3143 |
smbServer.setConnectionData(connId, connData) |
| 3144 |
return [respSMBCommand], None, errorCode |
| 3145 |
|
| 3146 |
@staticmethod |
| 3147 |
def smb2Write(connId, smbServer, recvPacket): |
| 3148 |
connData = smbServer.getConnectionData(connId) |
| 3149 |
|
| 3150 |
respSMBCommand = smb2.SMB2Write_Response() |
| 3151 |
writeRequest = smb2.SMB2Write(recvPacket['Data']) |
| 3152 |
|
| 3153 |
respSMBCommand['Buffer'] = '\x00' |
| 3154 |
|
| 3155 |
if str(writeRequest['FileID']) == '\xff'*16: |
| 3156 |
# Let's take the data from the lastRequest |
| 3157 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 3158 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 3159 |
else: |
| 3160 |
fileID = str(writeRequest['FileID']) |
| 3161 |
else: |
| 3162 |
fileID = str(writeRequest['FileID']) |
| 3163 |
|
| 3164 |
if fileID in connData['OpenedFiles']: |
| 3165 |
fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] |
| 3166 |
errorCode = STATUS_SUCCESS |
| 3167 |
try: |
| 3168 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 3169 |
offset = writeRequest['Offset'] |
| 3170 |
# If we're trying to write past the file end we just skip the write call (Vista does this) |
| 3171 |
if os.lseek(fileHandle, 0, 2) >= offset: |
| 3172 |
os.lseek(fileHandle,offset,0) |
| 3173 |
os.write(fileHandle,writeRequest['Buffer']) |
| 3174 |
else: |
| 3175 |
sock = connData['OpenedFiles'][fileID]['Socket'] |
| 3176 |
sock.send(writeRequest['Buffer']) |
| 3177 |
|
| 3178 |
respSMBCommand['Count'] = writeRequest['Length'] |
| 3179 |
respSMBCommand['Remaining']= 0xff |
| 3180 |
except Exception as e: |
| 3181 |
smbServer.log('SMB2_WRITE: %s' % e, logging.ERROR) |
| 3182 |
errorCode = STATUS_ACCESS_DENIED |
| 3183 |
else: |
| 3184 |
errorCode = STATUS_INVALID_HANDLE |
| 3185 |
|
| 3186 |
smbServer.setConnectionData(connId, connData) |
| 3187 |
return [respSMBCommand], None, errorCode |
| 3188 |
|
| 3189 |
@staticmethod |
| 3190 |
def smb2Read(connId, smbServer, recvPacket): |
| 3191 |
connData = smbServer.getConnectionData(connId) |
| 3192 |
|
| 3193 |
respSMBCommand = smb2.SMB2Read_Response() |
| 3194 |
readRequest = smb2.SMB2Read(recvPacket['Data']) |
| 3195 |
|
| 3196 |
respSMBCommand['Buffer'] = '\x00' |
| 3197 |
|
| 3198 |
if str(readRequest['FileID']) == '\xff'*16: |
| 3199 |
# Let's take the data from the lastRequest |
| 3200 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 3201 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 3202 |
else: |
| 3203 |
fileID = str(readRequest['FileID']) |
| 3204 |
else: |
| 3205 |
fileID = str(readRequest['FileID']) |
| 3206 |
|
| 3207 |
if fileID in connData['OpenedFiles']: |
| 3208 |
fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] |
| 3209 |
errorCode = 0 |
| 3210 |
try: |
| 3211 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 3212 |
offset = readRequest['Offset'] |
| 3213 |
os.lseek(fileHandle,offset,0) |
| 3214 |
content = os.read(fileHandle,readRequest['Length']) |
| 3215 |
else: |
| 3216 |
sock = connData['OpenedFiles'][fileID]['Socket'] |
| 3217 |
content = sock.recv(readRequest['Length']) |
| 3218 |
|
| 3219 |
respSMBCommand['DataOffset'] = 0x50 |
| 3220 |
respSMBCommand['DataLength'] = len(content) |
| 3221 |
respSMBCommand['DataRemaining']= 0 |
| 3222 |
respSMBCommand['Buffer'] = content |
| 3223 |
except Exception as e: |
| 3224 |
smbServer.log('SMB2_READ: %s ' % e, logging.ERROR) |
| 3225 |
errorCode = STATUS_ACCESS_DENIED |
| 3226 |
else: |
| 3227 |
errorCode = STATUS_INVALID_HANDLE |
| 3228 |
|
| 3229 |
smbServer.setConnectionData(connId, connData) |
| 3230 |
return [respSMBCommand], None, errorCode |
| 3231 |
|
| 3232 |
@staticmethod |
| 3233 |
def smb2Flush(connId, smbServer, recvPacket): |
| 3234 |
connData = smbServer.getConnectionData(connId) |
| 3235 |
|
| 3236 |
respSMBCommand = smb2.SMB2Flush_Response() |
| 3237 |
flushRequest = smb2.SMB2Flush(recvPacket['Data']) |
| 3238 |
|
| 3239 |
if str(flushRequest['FileID']) in connData['OpenedFiles']: |
| 3240 |
fileHandle = connData['OpenedFiles'][str(flushRequest['FileID'])]['FileHandle'] |
| 3241 |
errorCode = STATUS_SUCCESS |
| 3242 |
try: |
| 3243 |
os.fsync(fileHandle) |
| 3244 |
except Exception as e: |
| 3245 |
smbServer.log("SMB2_FLUSH %s" % e, logging.ERROR) |
| 3246 |
errorCode = STATUS_ACCESS_DENIED |
| 3247 |
else: |
| 3248 |
errorCode = STATUS_INVALID_HANDLE |
| 3249 |
|
| 3250 |
smbServer.setConnectionData(connId, connData) |
| 3251 |
return [respSMBCommand], None, errorCode |
| 3252 |
|
| 3253 |
|
| 3254 |
@staticmethod |
| 3255 |
def smb2QueryDirectory(connId, smbServer, recvPacket): |
| 3256 |
connData = smbServer.getConnectionData(connId) |
| 3257 |
respSMBCommand = smb2.SMB2QueryDirectory_Response() |
| 3258 |
queryDirectoryRequest = smb2.SMB2QueryDirectory(recvPacket['Data']) |
| 3259 |
|
| 3260 |
respSMBCommand['Buffer'] = '\x00' |
| 3261 |
|
| 3262 |
# The server MUST locate the tree connection, as specified in section 3.3.5.2.11. |
| 3263 |
if (recvPacket['TreeID'] in connData['ConnectedShares']) is False: |
| 3264 |
return [smb2.SMB2Error()], None, STATUS_NETWORK_NAME_DELETED |
| 3265 |
|
| 3266 |
# Next, the server MUST locate the open for the directory to be queried |
| 3267 |
# If no open is found, the server MUST fail the request with STATUS_FILE_CLOSED |
| 3268 |
if str(queryDirectoryRequest['FileID']) == '\xff'*16: |
| 3269 |
# Let's take the data from the lastRequest |
| 3270 |
if 'SMB2_CREATE' in connData['LastRequest']: |
| 3271 |
fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] |
| 3272 |
else: |
| 3273 |
fileID = str(queryDirectoryRequest['FileID']) |
| 3274 |
else: |
| 3275 |
fileID = str(queryDirectoryRequest['FileID']) |
| 3276 |
|
| 3277 |
if (fileID in connData['OpenedFiles']) is False: |
| 3278 |
return [smb2.SMB2Error()], None, STATUS_FILE_CLOSED |
| 3279 |
|
| 3280 |
# If the open is not an open to a directory, the request MUST be failed |
| 3281 |
# with STATUS_INVALID_PARAMETER. |
| 3282 |
if os.path.isdir(connData['OpenedFiles'][fileID]['FileName']) is False: |
| 3283 |
return [smb2.SMB2Error()], None, STATUS_INVALID_PARAMETER |
| 3284 |
|
| 3285 |
# If any other information class is specified in the FileInformationClass |
| 3286 |
# field of the SMB2 QUERY_DIRECTORY Request, the server MUST fail the |
| 3287 |
# operation with STATUS_INVALID_INFO_CLASS. |
| 3288 |
if queryDirectoryRequest['FileInformationClass'] not in ( |
| 3289 |
smb2.FILE_DIRECTORY_INFORMATION, smb2.FILE_FULL_DIRECTORY_INFORMATION, smb2.FILEID_FULL_DIRECTORY_INFORMATION, |
| 3290 |
smb2.FILE_BOTH_DIRECTORY_INFORMATION, smb2.FILEID_BOTH_DIRECTORY_INFORMATION, smb2.FILENAMES_INFORMATION): |
| 3291 |
return [smb2.SMB2Error()], None, STATUS_INVALID_INFO_CLASS |
| 3292 |
|
| 3293 |
# If SMB2_REOPEN is set in the Flags field of the SMB2 QUERY_DIRECTORY |
| 3294 |
# Request, the server SHOULD<326> set Open.EnumerationLocation to 0 |
| 3295 |
# and Open.EnumerationSearchPattern to an empty string. |
| 3296 |
if queryDirectoryRequest['Flags'] & smb2.SMB2_REOPEN: |
| 3297 |
connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = 0 |
| 3298 |
connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = '' |
| 3299 |
|
| 3300 |
# If SMB2_RESTART_SCANS is set in the Flags field of the SMB2 |
| 3301 |
# QUERY_DIRECTORY Request, the server MUST set |
| 3302 |
# Open.EnumerationLocation to 0. |
| 3303 |
if queryDirectoryRequest['Flags'] & smb2.SMB2_RESTART_SCANS: |
| 3304 |
connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = 0 |
| 3305 |
|
| 3306 |
# If Open.EnumerationLocation is 0 and Open.EnumerationSearchPattern |
| 3307 |
# is an empty string, then Open.EnumerationSearchPattern MUST be set |
| 3308 |
# to the search pattern specified in the SMB2 QUERY_DIRECTORY by |
| 3309 |
# FileNameOffset and FileNameLength. If FileNameLength is 0, the server |
| 3310 |
# SHOULD<327> set Open.EnumerationSearchPattern as "*" to search all entries. |
| 3311 |
|
| 3312 |
pattern = queryDirectoryRequest['Buffer'].decode('utf-16le') |
| 3313 |
if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] == 0 and \ |
| 3314 |
connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] == '': |
| 3315 |
if pattern == '': |
| 3316 |
pattern = '*' |
| 3317 |
connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = pattern |
| 3318 |
|
| 3319 |
# If SMB2_INDEX_SPECIFIED is set and FileNameLength is not zero, |
| 3320 |
# the server MUST set Open.EnumerationSearchPattern to the search pattern |
| 3321 |
# specified in the request by FileNameOffset and FileNameLength. |
| 3322 |
if queryDirectoryRequest['Flags'] & smb2.SMB2_INDEX_SPECIFIED and \ |
| 3323 |
queryDirectoryRequest['FileNameLength'] > 0: |
| 3324 |
connData['OpenedFiles'][fileID]['Open']['EnumerationSearchPattern'] = pattern |
| 3325 |
|
| 3326 |
pathName = os.path.join(os.path.normpath(connData['OpenedFiles'][fileID]['FileName']),pattern) |
| 3327 |
searchResult, searchCount, errorCode = findFirst2(os.path.dirname(pathName), |
| 3328 |
os.path.basename(pathName), |
| 3329 |
queryDirectoryRequest['FileInformationClass'], |
| 3330 |
smb.ATTR_DIRECTORY, isSMB2 = True ) |
| 3331 |
|
| 3332 |
if errorCode != STATUS_SUCCESS: |
| 3333 |
return [smb2.SMB2Error()], None, errorCode |
| 3334 |
|
| 3335 |
if searchCount > 2 and pattern == '*': |
| 3336 |
# strip . and .. |
| 3337 |
searchCount -= 2 |
| 3338 |
searchResult = searchResult[2:] |
| 3339 |
|
| 3340 |
if searchCount == 0 and connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] == 0: |
| 3341 |
return [smb2.SMB2Error()], None, STATUS_NO_SUCH_FILE |
| 3342 |
|
| 3343 |
if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] < 0: |
| 3344 |
return [smb2.SMB2Error()], None, STATUS_NO_MORE_FILES |
| 3345 |
|
| 3346 |
totalData = 0 |
| 3347 |
respData = '' |
| 3348 |
for nItem in range(connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'], searchCount): |
| 3349 |
connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] += 1 |
| 3350 |
if queryDirectoryRequest['Flags'] & smb2.SL_RETURN_SINGLE_ENTRY: |
| 3351 |
# If single entry is requested we must clear the NextEntryOffset |
| 3352 |
searchResult[nItem]['NextEntryOffset'] = 0 |
| 3353 |
data = searchResult[nItem].getData() |
| 3354 |
lenData = len(data) |
| 3355 |
padLen = (8-(lenData % 8)) %8 |
| 3356 |
|
| 3357 |
if (totalData+lenData) >= queryDirectoryRequest['OutputBufferLength']: |
| 3358 |
connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] -= 1 |
| 3359 |
break |
| 3360 |
else: |
| 3361 |
respData += data + '\x00'*padLen |
| 3362 |
totalData += lenData + padLen |
| 3363 |
|
| 3364 |
if queryDirectoryRequest['Flags'] & smb2.SL_RETURN_SINGLE_ENTRY: |
| 3365 |
break |
| 3366 |
|
| 3367 |
if connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] >= searchCount: |
| 3368 |
connData['OpenedFiles'][fileID]['Open']['EnumerationLocation'] = -1 |
| 3369 |
|
| 3370 |
respSMBCommand['OutputBufferOffset'] = 0x48 |
| 3371 |
respSMBCommand['OutputBufferLength'] = totalData |
| 3372 |
respSMBCommand['Buffer'] = respData |
| 3373 |
|
| 3374 |
smbServer.setConnectionData(connId, connData) |
| 3375 |
return [respSMBCommand], None, errorCode |
| 3376 |
|
| 3377 |
@staticmethod |
| 3378 |
def smb2ChangeNotify(connId, smbServer, recvPacket): |
| 3379 |
|
| 3380 |
return [smb2.SMB2Error()], None, STATUS_NOT_SUPPORTED |
| 3381 |
|
| 3382 |
@staticmethod |
| 3383 |
def smb2Echo(connId, smbServer, recvPacket): |
| 3384 |
|
| 3385 |
respSMBCommand = smb2.SMB2Echo_Response() |
| 3386 |
|
| 3387 |
return [respSMBCommand], None, STATUS_SUCCESS |
| 3388 |
|
| 3389 |
@staticmethod |
| 3390 |
def smb2TreeDisconnect(connId, smbServer, recvPacket): |
| 3391 |
connData = smbServer.getConnectionData(connId) |
| 3392 |
|
| 3393 |
respSMBCommand = smb2.SMB2TreeDisconnect_Response() |
| 3394 |
|
| 3395 |
if recvPacket['TreeID'] in connData['ConnectedShares']: |
| 3396 |
smbServer.log("Disconnecting Share(%d:%s)" % (recvPacket['TreeID'],connData['ConnectedShares'][recvPacket['TreeID']]['shareName'])) |
| 3397 |
del(connData['ConnectedShares'][recvPacket['TreeID']]) |
| 3398 |
errorCode = STATUS_SUCCESS |
| 3399 |
else: |
| 3400 |
# STATUS_SMB_BAD_TID |
| 3401 |
errorCode = STATUS_SMB_BAD_TID |
| 3402 |
|
| 3403 |
|
| 3404 |
smbServer.setConnectionData(connId, connData) |
| 3405 |
return [respSMBCommand], None, errorCode |
| 3406 |
|
| 3407 |
@staticmethod |
| 3408 |
def smb2Logoff(connId, smbServer, recvPacket): |
| 3409 |
connData = smbServer.getConnectionData(connId) |
| 3410 |
|
| 3411 |
respSMBCommand = smb2.SMB2Logoff_Response() |
| 3412 |
|
| 3413 |
if recvPacket['SessionID'] != connData['Uid']: |
| 3414 |
# STATUS_SMB_BAD_UID |
| 3415 |
errorCode = STATUS_SMB_BAD_UID |
| 3416 |
else: |
| 3417 |
errorCode = STATUS_SUCCESS |
| 3418 |
|
| 3419 |
connData['Uid'] = 0 |
| 3420 |
|
| 3421 |
smbServer.setConnectionData(connId, connData) |
| 3422 |
return [respSMBCommand], None, errorCode |
| 3423 |
|
| 3424 |
@staticmethod |
| 3425 |
def smb2Ioctl(connId, smbServer, recvPacket): |
| 3426 |
connData = smbServer.getConnectionData(connId) |
| 3427 |
|
| 3428 |
respSMBCommand = smb2.SMB2Ioctl_Response() |
| 3429 |
ioctlRequest = smb2.SMB2Ioctl(recvPacket['Data']) |
| 3430 |
|
| 3431 |
ioctls = smbServer.getIoctls() |
| 3432 |
if ioctlRequest['CtlCode'] in ioctls: |
| 3433 |
outputData, errorCode = ioctls[ioctlRequest['CtlCode']](connId, smbServer, ioctlRequest) |
| 3434 |
if errorCode == STATUS_SUCCESS: |
| 3435 |
respSMBCommand['CtlCode'] = ioctlRequest['CtlCode'] |
| 3436 |
respSMBCommand['FileID'] = ioctlRequest['FileID'] |
| 3437 |
respSMBCommand['InputOffset'] = 0 |
| 3438 |
respSMBCommand['InputCount'] = 0 |
| 3439 |
respSMBCommand['OutputOffset'] = 0x70 |
| 3440 |
respSMBCommand['OutputCount'] = len(outputData) |
| 3441 |
respSMBCommand['Flags'] = 0 |
| 3442 |
respSMBCommand['Buffer'] = outputData |
| 3443 |
else: |
| 3444 |
respSMBCommand = outputData |
| 3445 |
else: |
| 3446 |
smbServer.log("Ioctl not implemented command: 0x%x" % ioctlRequest['CtlCode'],logging.DEBUG) |
| 3447 |
errorCode = STATUS_INVALID_DEVICE_REQUEST |
| 3448 |
respSMBCommand = smb2.SMB2Error() |
| 3449 |
|
| 3450 |
smbServer.setConnectionData(connId, connData) |
| 3451 |
return [respSMBCommand], None, errorCode |
| 3452 |
|
| 3453 |
@staticmethod |
| 3454 |
def smb2Lock(connId, smbServer, recvPacket): |
| 3455 |
connData = smbServer.getConnectionData(connId) |
| 3456 |
|
| 3457 |
respSMBCommand = smb2.SMB2Lock_Response() |
| 3458 |
|
| 3459 |
# I'm actually doing nothing.. just make MacOS happy ;) |
| 3460 |
errorCode = STATUS_SUCCESS |
| 3461 |
|
| 3462 |
smbServer.setConnectionData(connId, connData) |
| 3463 |
return [respSMBCommand], None, errorCode |
| 3464 |
|
| 3465 |
@staticmethod |
| 3466 |
def smb2Cancel(connId, smbServer, recvPacket): |
| 3467 |
# I'm actually doing nothing |
| 3468 |
return [smb2.SMB2Error()], None, STATUS_CANCELLED |
| 3469 |
|
| 3470 |
@staticmethod |
| 3471 |
def default(connId, smbServer, recvPacket): |
| 3472 |
# By default we return an SMB Packet with error not implemented |
| 3473 |
smbServer.log("Not implemented command: 0x%x" % recvPacket['Command'],logging.DEBUG) |
| 3474 |
return [smb2.SMB2Error()], None, STATUS_NOT_SUPPORTED |
| 3475 |
|
| 3476 |
class Ioctls: |
| 3477 |
@staticmethod |
| 3478 |
def fsctlDfsGetReferrals(connId, smbServer, ioctlRequest): |
| 3479 |
return smb2.SMB2Error(), STATUS_FS_DRIVER_REQUIRED |
| 3480 |
|
| 3481 |
@staticmethod |
| 3482 |
def fsctlPipeTransceive(connId, smbServer, ioctlRequest): |
| 3483 |
connData = smbServer.getConnectionData(connId) |
| 3484 |
|
| 3485 |
ioctlResponse = '' |
| 3486 |
|
| 3487 |
if str(ioctlRequest['FileID']) in connData['OpenedFiles']: |
| 3488 |
fileHandle = connData['OpenedFiles'][str(ioctlRequest['FileID'])]['FileHandle'] |
| 3489 |
errorCode = STATUS_SUCCESS |
| 3490 |
try: |
| 3491 |
if fileHandle != PIPE_FILE_DESCRIPTOR: |
| 3492 |
errorCode = STATUS_INVALID_DEVICE_REQUEST |
| 3493 |
else: |
| 3494 |
sock = connData['OpenedFiles'][str(ioctlRequest['FileID'])]['Socket'] |
| 3495 |
sock.sendall(ioctlRequest['Buffer']) |
| 3496 |
ioctlResponse = sock.recv(ioctlRequest['MaxOutputResponse']) |
| 3497 |
except Exception as e: |
| 3498 |
smbServer.log('fsctlPipeTransceive: %s ' % e, logging.ERROR) |
| 3499 |
errorCode = STATUS_ACCESS_DENIED |
| 3500 |
else: |
| 3501 |
errorCode = STATUS_INVALID_DEVICE_REQUEST |
| 3502 |
|
| 3503 |
smbServer.setConnectionData(connId, connData) |
| 3504 |
return ioctlResponse, errorCode |
| 3505 |
|
| 3506 |
@staticmethod |
| 3507 |
def fsctlValidateNegotiateInfo(connId, smbServer, ioctlRequest): |
| 3508 |
connData = smbServer.getConnectionData(connId) |
| 3509 |
|
| 3510 |
errorCode = STATUS_SUCCESS |
| 3511 |
|
| 3512 |
validateNegotiateInfo = smb2.VALIDATE_NEGOTIATE_INFO(ioctlRequest['Buffer']) |
| 3513 |
validateNegotiateInfo['Capabilities'] = 0 |
| 3514 |
validateNegotiateInfo['Guid'] = 'A'*16 |
| 3515 |
validateNegotiateInfo['SecurityMode'] = 1 |
| 3516 |
validateNegotiateInfo['Dialects'] = (smb2.SMB2_DIALECT_002,) |
| 3517 |
|
| 3518 |
smbServer.setConnectionData(connId, connData) |
| 3519 |
return validateNegotiateInfo.getData(), errorCode |
| 3520 |
|
| 3521 |
|
| 3522 |
class SMBSERVERHandler(SocketServer.BaseRequestHandler): |
| 3523 |
def __init__(self, request, client_address, server, select_poll = False): |
| 3524 |
self.__SMB = server |
| 3525 |
self.__ip, self.__port = client_address |
| 3526 |
self.__request = request |
| 3527 |
self.__connId = threading.currentThread().getName() |
| 3528 |
self.__timeOut = 60*5 |
| 3529 |
self.__select_poll = select_poll |
| 3530 |
#self.__connId = os.getpid() |
| 3531 |
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) |
| 3532 |
|
| 3533 |
def handle(self): |
| 3534 |
self.__SMB.log("Incoming connection (%s,%d)" % (self.__ip, self.__port)) |
| 3535 |
self.__SMB.addConnection(self.__connId, self.__ip, self.__port) |
| 3536 |
while True: |
| 3537 |
try: |
| 3538 |
# Firt of all let's get the NETBIOS packet |
| 3539 |
session = nmb.NetBIOSTCPSession(self.__SMB.getServerName(),'HOST', self.__ip, sess_port = self.__port, sock = self.__request, select_poll = self.__select_poll) |
| 3540 |
try: |
| 3541 |
p = session.recv_packet(self.__timeOut) |
| 3542 |
except nmb.NetBIOSTimeout: |
| 3543 |
raise |
| 3544 |
except nmb.NetBIOSError: |
| 3545 |
break |
| 3546 |
|
| 3547 |
if p.get_type() == nmb.NETBIOS_SESSION_REQUEST: |
| 3548 |
# Someone is requesting a session, we're gonna accept them all :) |
| 3549 |
_, rn, my = p.get_trailer().split(' ') |
| 3550 |
remote_name = nmb.decode_name('\x20'+rn) |
| 3551 |
myname = nmb.decode_name('\x20'+my) |
| 3552 |
self.__SMB.log("NetBIOS Session request (%s,%s,%s)" % (self.__ip, remote_name[1].strip(), myname[1])) |
| 3553 |
r = nmb.NetBIOSSessionPacket() |
| 3554 |
r.set_type(nmb.NETBIOS_SESSION_POSITIVE_RESPONSE) |
| 3555 |
r.set_trailer(p.get_trailer()) |
| 3556 |
self.__request.send(r.rawData()) |
| 3557 |
else: |
| 3558 |
resp = self.__SMB.processRequest(self.__connId, p.get_trailer()) |
| 3559 |
# Send all the packets recevied. Except for big transactions this should be |
| 3560 |
# a single packet |
| 3561 |
for i in resp: |
| 3562 |
session.send_packet(str(i)) |
| 3563 |
except Exception as e: |
| 3564 |
self.__SMB.log("Handle: %s" % e) |
| 3565 |
#import traceback |
| 3566 |
#traceback.print_exc() |
| 3567 |
break |
| 3568 |
|
| 3569 |
def finish(self): |
| 3570 |
# Thread/process is dying, we should tell the main SMB thread to remove all this thread data |
| 3571 |
self.__SMB.log("Closing down connection (%s,%d)" % (self.__ip, self.__port)) |
| 3572 |
self.__SMB.removeConnection(self.__connId) |
| 3573 |
return SocketServer.BaseRequestHandler.finish(self) |
| 3574 |
|
| 3575 |
class SMBSERVER(SocketServer.ThreadingMixIn, SocketServer.TCPServer): |
| 3576 |
#class SMBSERVER(SocketServer.ForkingMixIn, SocketServer.TCPServer): |
| 3577 |
def __init__(self, server_address, handler_class=SMBSERVERHandler, config_parser = None): |
| 3578 |
SocketServer.TCPServer.allow_reuse_address = True |
| 3579 |
SocketServer.TCPServer.__init__(self, server_address, handler_class) |
| 3580 |
|
| 3581 |
# Server name and OS to be presented whenever is necessary |
| 3582 |
self.__serverName = '' |
| 3583 |
self.__serverOS = '' |
| 3584 |
self.__serverDomain = '' |
| 3585 |
self.__challenge = '' |
| 3586 |
self.__log = None |
| 3587 |
|
| 3588 |
# Our ConfigParser data |
| 3589 |
self.__serverConfig = config_parser |
| 3590 |
|
| 3591 |
# Our credentials to be used during the server's lifetime |
| 3592 |
self.__credentials = {} |
| 3593 |
|
| 3594 |
# Our log file |
| 3595 |
self.__logFile = '' |
| 3596 |
|
| 3597 |
# Registered Named Pipes, format is PipeName,Socket |
| 3598 |
self.__registeredNamedPipes = {} |
| 3599 |
|
| 3600 |
# JTR dump path |
| 3601 |
self.__jtr_dump_path = '' |
| 3602 |
|
| 3603 |
# SMB2 Support flag = default not active |
| 3604 |
self.__SMB2Support = False |
| 3605 |
|
| 3606 |
# Our list of commands we will answer, by default the NOT IMPLEMENTED one |
| 3607 |
self.__smbCommandsHandler = SMBCommands() |
| 3608 |
self.__smbTrans2Handler = TRANS2Commands() |
| 3609 |
self.__smbTransHandler = TRANSCommands() |
| 3610 |
self.__smbNTTransHandler = NTTRANSCommands() |
| 3611 |
self.__smb2CommandsHandler = SMB2Commands() |
| 3612 |
self.__IoctlHandler = Ioctls() |
| 3613 |
|
| 3614 |
self.__smbNTTransCommands = { |
| 3615 |
# NT IOCTL, can't find doc for this |
| 3616 |
0xff :self.__smbNTTransHandler.default |
| 3617 |
} |
| 3618 |
|
| 3619 |
self.__smbTransCommands = { |
| 3620 |
'\\PIPE\\LANMAN' :self.__smbTransHandler.lanMan, |
| 3621 |
smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe, |
| 3622 |
} |
| 3623 |
self.__smbTrans2Commands = { |
| 3624 |
smb.SMB.TRANS2_FIND_FIRST2 :self.__smbTrans2Handler.findFirst2, |
| 3625 |
smb.SMB.TRANS2_FIND_NEXT2 :self.__smbTrans2Handler.findNext2, |
| 3626 |
smb.SMB.TRANS2_QUERY_FS_INFORMATION :self.__smbTrans2Handler.queryFsInformation, |
| 3627 |
smb.SMB.TRANS2_QUERY_PATH_INFORMATION :self.__smbTrans2Handler.queryPathInformation, |
| 3628 |
smb.SMB.TRANS2_QUERY_FILE_INFORMATION :self.__smbTrans2Handler.queryFileInformation, |
| 3629 |
smb.SMB.TRANS2_SET_FILE_INFORMATION :self.__smbTrans2Handler.setFileInformation, |
| 3630 |
smb.SMB.TRANS2_SET_PATH_INFORMATION :self.__smbTrans2Handler.setPathInformation |
| 3631 |
} |
| 3632 |
|
| 3633 |
self.__smbCommands = { |
| 3634 |
#smb.SMB.SMB_COM_FLUSH: self.__smbCommandsHandler.smbComFlush, |
| 3635 |
smb.SMB.SMB_COM_CREATE_DIRECTORY: self.__smbCommandsHandler.smbComCreateDirectory, |
| 3636 |
smb.SMB.SMB_COM_DELETE_DIRECTORY: self.__smbCommandsHandler.smbComDeleteDirectory, |
| 3637 |
smb.SMB.SMB_COM_RENAME: self.__smbCommandsHandler.smbComRename, |
| 3638 |
smb.SMB.SMB_COM_DELETE: self.__smbCommandsHandler.smbComDelete, |
| 3639 |
smb.SMB.SMB_COM_NEGOTIATE: self.__smbCommandsHandler.smbComNegotiate, |
| 3640 |
smb.SMB.SMB_COM_SESSION_SETUP_ANDX: self.__smbCommandsHandler.smbComSessionSetupAndX, |
| 3641 |
smb.SMB.SMB_COM_LOGOFF_ANDX: self.__smbCommandsHandler.smbComLogOffAndX, |
| 3642 |
smb.SMB.SMB_COM_TREE_CONNECT_ANDX: self.__smbCommandsHandler.smbComTreeConnectAndX, |
| 3643 |
smb.SMB.SMB_COM_TREE_DISCONNECT: self.__smbCommandsHandler.smbComTreeDisconnect, |
| 3644 |
smb.SMB.SMB_COM_ECHO: self.__smbCommandsHandler.smbComEcho, |
| 3645 |
smb.SMB.SMB_COM_QUERY_INFORMATION: self.__smbCommandsHandler.smbQueryInformation, |
| 3646 |
smb.SMB.SMB_COM_TRANSACTION2: self.__smbCommandsHandler.smbTransaction2, |
| 3647 |
smb.SMB.SMB_COM_TRANSACTION: self.__smbCommandsHandler.smbTransaction, |
| 3648 |
# Not needed for now |
| 3649 |
smb.SMB.SMB_COM_NT_TRANSACT: self.__smbCommandsHandler.smbNTTransact, |
| 3650 |
smb.SMB.SMB_COM_QUERY_INFORMATION_DISK: self.__smbCommandsHandler.smbQueryInformationDisk, |
| 3651 |
smb.SMB.SMB_COM_OPEN_ANDX: self.__smbCommandsHandler.smbComOpenAndX, |
| 3652 |
smb.SMB.SMB_COM_QUERY_INFORMATION2: self.__smbCommandsHandler.smbComQueryInformation2, |
| 3653 |
smb.SMB.SMB_COM_READ_ANDX: self.__smbCommandsHandler.smbComReadAndX, |
| 3654 |
smb.SMB.SMB_COM_READ: self.__smbCommandsHandler.smbComRead, |
| 3655 |
smb.SMB.SMB_COM_WRITE_ANDX: self.__smbCommandsHandler.smbComWriteAndX, |
| 3656 |
smb.SMB.SMB_COM_WRITE: self.__smbCommandsHandler.smbComWrite, |
| 3657 |
smb.SMB.SMB_COM_CLOSE: self.__smbCommandsHandler.smbComClose, |
| 3658 |
smb.SMB.SMB_COM_LOCKING_ANDX: self.__smbCommandsHandler.smbComLockingAndX, |
| 3659 |
smb.SMB.SMB_COM_NT_CREATE_ANDX: self.__smbCommandsHandler.smbComNtCreateAndX, |
| 3660 |
0xFF: self.__smbCommandsHandler.default |
| 3661 |
} |
| 3662 |
|
| 3663 |
self.__smb2Ioctls = { |
| 3664 |
smb2.FSCTL_DFS_GET_REFERRALS: self.__IoctlHandler.fsctlDfsGetReferrals, |
| 3665 |
# smb2.FSCTL_PIPE_PEEK: self.__IoctlHandler.fsctlPipePeek, |
| 3666 |
# smb2.FSCTL_PIPE_WAIT: self.__IoctlHandler.fsctlPipeWait, |
| 3667 |
smb2.FSCTL_PIPE_TRANSCEIVE: self.__IoctlHandler.fsctlPipeTransceive, |
| 3668 |
# smb2.FSCTL_SRV_COPYCHUNK: self.__IoctlHandler.fsctlSrvCopyChunk, |
| 3669 |
# smb2.FSCTL_SRV_ENUMERATE_SNAPSHOTS: self.__IoctlHandler.fsctlSrvEnumerateSnapshots, |
| 3670 |
# smb2.FSCTL_SRV_REQUEST_RESUME_KEY: self.__IoctlHandler.fsctlSrvRequestResumeKey, |
| 3671 |
# smb2.FSCTL_SRV_READ_HASH: self.__IoctlHandler.fsctlSrvReadHash, |
| 3672 |
# smb2.FSCTL_SRV_COPYCHUNK_WRITE: self.__IoctlHandler.fsctlSrvCopyChunkWrite, |
| 3673 |
# smb2.FSCTL_LMR_REQUEST_RESILIENCY: self.__IoctlHandler.fsctlLmrRequestResiliency, |
| 3674 |
# smb2.FSCTL_QUERY_NETWORK_INTERFACE_INFO: self.__IoctlHandler.fsctlQueryNetworkInterfaceInfo, |
| 3675 |
# smb2.FSCTL_SET_REPARSE_POINT: self.__IoctlHandler.fsctlSetReparsePoint, |
| 3676 |
# smb2.FSCTL_DFS_GET_REFERRALS_EX: self.__IoctlHandler.fsctlDfsGetReferralsEx, |
| 3677 |
# smb2.FSCTL_FILE_LEVEL_TRIM: self.__IoctlHandler.fsctlFileLevelTrim, |
| 3678 |
smb2.FSCTL_VALIDATE_NEGOTIATE_INFO: self.__IoctlHandler.fsctlValidateNegotiateInfo, |
| 3679 |
} |
| 3680 |
|
| 3681 |
self.__smb2Commands = { |
| 3682 |
smb2.SMB2_NEGOTIATE: self.__smb2CommandsHandler.smb2Negotiate, |
| 3683 |
smb2.SMB2_SESSION_SETUP: self.__smb2CommandsHandler.smb2SessionSetup, |
| 3684 |
smb2.SMB2_LOGOFF: self.__smb2CommandsHandler.smb2Logoff, |
| 3685 |
smb2.SMB2_TREE_CONNECT: self.__smb2CommandsHandler.smb2TreeConnect, |
| 3686 |
smb2.SMB2_TREE_DISCONNECT: self.__smb2CommandsHandler.smb2TreeDisconnect, |
| 3687 |
smb2.SMB2_CREATE: self.__smb2CommandsHandler.smb2Create, |
| 3688 |
smb2.SMB2_CLOSE: self.__smb2CommandsHandler.smb2Close, |
| 3689 |
smb2.SMB2_FLUSH: self.__smb2CommandsHandler.smb2Flush, |
| 3690 |
smb2.SMB2_READ: self.__smb2CommandsHandler.smb2Read, |
| 3691 |
smb2.SMB2_WRITE: self.__smb2CommandsHandler.smb2Write, |
| 3692 |
smb2.SMB2_LOCK: self.__smb2CommandsHandler.smb2Lock, |
| 3693 |
smb2.SMB2_IOCTL: self.__smb2CommandsHandler.smb2Ioctl, |
| 3694 |
smb2.SMB2_CANCEL: self.__smb2CommandsHandler.smb2Cancel, |
| 3695 |
smb2.SMB2_ECHO: self.__smb2CommandsHandler.smb2Echo, |
| 3696 |
smb2.SMB2_QUERY_DIRECTORY: self.__smb2CommandsHandler.smb2QueryDirectory, |
| 3697 |
smb2.SMB2_CHANGE_NOTIFY: self.__smb2CommandsHandler.smb2ChangeNotify, |
| 3698 |
smb2.SMB2_QUERY_INFO: self.__smb2CommandsHandler.smb2QueryInfo, |
| 3699 |
smb2.SMB2_SET_INFO: self.__smb2CommandsHandler.smb2SetInfo, |
| 3700 |
# smb2.SMB2_OPLOCK_BREAK: self.__smb2CommandsHandler.smb2SessionSetup, |
| 3701 |
0xFF: self.__smb2CommandsHandler.default |
| 3702 |
} |
| 3703 |
|
| 3704 |
# List of active connections |
| 3705 |
self.__activeConnections = {} |
| 3706 |
|
| 3707 |
def getIoctls(self): |
| 3708 |
return self.__smb2Ioctls |
| 3709 |
|
| 3710 |
def getCredentials(self): |
| 3711 |
return self.__credentials |
| 3712 |
|
| 3713 |
def removeConnection(self, name): |
| 3714 |
try: |
| 3715 |
del(self.__activeConnections[name]) |
| 3716 |
except: |
| 3717 |
pass |
| 3718 |
self.log("Remaining connections %s" % self.__activeConnections.keys()) |
| 3719 |
|
| 3720 |
def addConnection(self, name, ip, port): |
| 3721 |
self.__activeConnections[name] = {} |
| 3722 |
# Let's init with some know stuff we will need to have |
| 3723 |
# TODO: Document what's in there |
| 3724 |
#print "Current Connections", self.__activeConnections.keys() |
| 3725 |
self.__activeConnections[name]['PacketNum'] = 0 |
| 3726 |
self.__activeConnections[name]['ClientIP'] = ip |
| 3727 |
self.__activeConnections[name]['ClientPort'] = port |
| 3728 |
self.__activeConnections[name]['Uid'] = 0 |
| 3729 |
self.__activeConnections[name]['ConnectedShares'] = {} |
| 3730 |
self.__activeConnections[name]['OpenedFiles'] = {} |
| 3731 |
# SID results for findfirst2 |
| 3732 |
self.__activeConnections[name]['SIDs'] = {} |
| 3733 |
self.__activeConnections[name]['LastRequest'] = {} |
| 3734 |
|
| 3735 |
def getActiveConnections(self): |
| 3736 |
return self.__activeConnections |
| 3737 |
|
| 3738 |
def setConnectionData(self, connId, data): |
| 3739 |
self.__activeConnections[connId] = data |
| 3740 |
#print "setConnectionData" |
| 3741 |
#print self.__activeConnections |
| 3742 |
|
| 3743 |
def getConnectionData(self, connId, checkStatus = True): |
| 3744 |
conn = self.__activeConnections[connId] |
| 3745 |
if checkStatus is True: |
| 3746 |
if ('Authenticated' in conn) is not True: |
| 3747 |
# Can't keep going further |
| 3748 |
raise Exception("User not Authenticated!") |
| 3749 |
return conn |
| 3750 |
|
| 3751 |
def getRegisteredNamedPipes(self): |
| 3752 |
return self.__registeredNamedPipes |
| 3753 |
|
| 3754 |
def registerNamedPipe(self, pipeName, address): |
| 3755 |
self.__registeredNamedPipes[unicode(pipeName)] = address |
| 3756 |
return True |
| 3757 |
|
| 3758 |
def unregisterNamedPipe(self, pipeName): |
| 3759 |
if pipeName in self.__registeredNamedPipes: |
| 3760 |
del(self.__registeredNamedPipes[unicode(pipeName)]) |
| 3761 |
return True |
| 3762 |
return False |
| 3763 |
|
| 3764 |
def unregisterTransaction(self, transCommand): |
| 3765 |
if transCommand in self.__smbTransCommands: |
| 3766 |
del(self.__smbTransCommands[transCommand]) |
| 3767 |
|
| 3768 |
def hookTransaction(self, transCommand, callback): |
| 3769 |
# If you call this function, callback will replace |
| 3770 |
# the current Transaction sub command. |
| 3771 |
# (don't get confused with the Transaction smbCommand) |
| 3772 |
# If the transaction sub command doesn't not exist, it is added |
| 3773 |
# If the transaction sub command exists, it returns the original function # replaced |
| 3774 |
# |
| 3775 |
# callback MUST be declared as: |
| 3776 |
# callback(connId, smbServer, recvPacket, parameters, data, maxDataCount=0) |
| 3777 |
# |
| 3778 |
# WHERE: |
| 3779 |
# |
| 3780 |
# connId : the connection Id, used to grab/update information about |
| 3781 |
# the current connection |
| 3782 |
# smbServer : the SMBServer instance available for you to ask |
| 3783 |
# configuration data |
| 3784 |
# recvPacket : the full SMBPacket that triggered this command |
| 3785 |
# parameters : the transaction parameters |
| 3786 |
# data : the transaction data |
| 3787 |
# maxDataCount: the max amount of data that can be transfered agreed |
| 3788 |
# with the client |
| 3789 |
# |
| 3790 |
# and MUST return: |
| 3791 |
# respSetup, respParameters, respData, errorCode |
| 3792 |
# |
| 3793 |
# WHERE: |
| 3794 |
# |
| 3795 |
# respSetup: the setup response of the transaction |
| 3796 |
# respParameters: the parameters response of the transaction |
| 3797 |
# respData: the data reponse of the transaction |
| 3798 |
# errorCode: the NT error code |
| 3799 |
|
| 3800 |
if transCommand in self.__smbTransCommands: |
| 3801 |
originalCommand = self.__smbTransCommands[transCommand] |
| 3802 |
else: |
| 3803 |
originalCommand = None |
| 3804 |
|
| 3805 |
self.__smbTransCommands[transCommand] = callback |
| 3806 |
return originalCommand |
| 3807 |
|
| 3808 |
def unregisterTransaction2(self, transCommand): |
| 3809 |
if transCommand in self.__smbTrans2Commands: |
| 3810 |
del(self.__smbTrans2Commands[transCommand]) |
| 3811 |
|
| 3812 |
def hookTransaction2(self, transCommand, callback): |
| 3813 |
# Here we should add to __smbTrans2Commands |
| 3814 |
# Same description as Transaction |
| 3815 |
if transCommand in self.__smbTrans2Commands: |
| 3816 |
originalCommand = self.__smbTrans2Commands[transCommand] |
| 3817 |
else: |
| 3818 |
originalCommand = None |
| 3819 |
|
| 3820 |
self.__smbTrans2Commands[transCommand] = callback |
| 3821 |
return originalCommand |
| 3822 |
|
| 3823 |
def unregisterNTTransaction(self, transCommand): |
| 3824 |
if transCommand in self.__smbNTTransCommands: |
| 3825 |
del(self.__smbNTTransCommands[transCommand]) |
| 3826 |
|
| 3827 |
def hookNTTransaction(self, transCommand, callback): |
| 3828 |
# Here we should add to __smbNTTransCommands |
| 3829 |
# Same description as Transaction |
| 3830 |
if transCommand in self.__smbNTTransCommands: |
| 3831 |
originalCommand = self.__smbNTTransCommands[transCommand] |
| 3832 |
else: |
| 3833 |
originalCommand = None |
| 3834 |
|
| 3835 |
self.__smbNTTransCommands[transCommand] = callback |
| 3836 |
return originalCommand |
| 3837 |
|
| 3838 |
def unregisterSmbCommand(self, smbCommand): |
| 3839 |
if smbCommand in self.__smbCommands: |
| 3840 |
del(self.__smbCommands[smbCommand]) |
| 3841 |
|
| 3842 |
def hookSmbCommand(self, smbCommand, callback): |
| 3843 |
# Here we should add to self.__smbCommands |
| 3844 |
# If you call this function, callback will replace |
| 3845 |
# the current smbCommand. |
| 3846 |
# If smbCommand doesn't not exist, it is added |
| 3847 |
# If SMB command exists, it returns the original function replaced |
| 3848 |
# |
| 3849 |
# callback MUST be declared as: |
| 3850 |
# callback(connId, smbServer, SMBCommand, recvPacket) |
| 3851 |
# |
| 3852 |
# WHERE: |
| 3853 |
# |
| 3854 |
# connId : the connection Id, used to grab/update information about |
| 3855 |
# the current connection |
| 3856 |
# smbServer : the SMBServer instance available for you to ask |
| 3857 |
# configuration data |
| 3858 |
# SMBCommand: the SMBCommand itself, with its data and parameters. |
| 3859 |
# Check smb.py:SMBCommand() for a reference |
| 3860 |
# recvPacket: the full SMBPacket that triggered this command |
| 3861 |
# |
| 3862 |
# and MUST return: |
| 3863 |
# <list of respSMBCommands>, <list of packets>, errorCode |
| 3864 |
# <list of packets> has higher preference over commands, in case you |
| 3865 |
# want to change the whole packet |
| 3866 |
# errorCode: the NT error code |
| 3867 |
# |
| 3868 |
# For SMB_COM_TRANSACTION2, SMB_COM_TRANSACTION and SMB_COM_NT_TRANSACT |
| 3869 |
# the callback function is slightly different: |
| 3870 |
# |
| 3871 |
# callback(connId, smbServer, SMBCommand, recvPacket, transCommands) |
| 3872 |
# |
| 3873 |
# WHERE: |
| 3874 |
# |
| 3875 |
# transCommands: a list of transaction subcommands already registered |
| 3876 |
# |
| 3877 |
|
| 3878 |
if smbCommand in self.__smbCommands: |
| 3879 |
originalCommand = self.__smbCommands[smbCommand] |
| 3880 |
else: |
| 3881 |
originalCommand = None |
| 3882 |
|
| 3883 |
self.__smbCommands[smbCommand] = callback |
| 3884 |
return originalCommand |
| 3885 |
|
| 3886 |
def unregisterSmb2Command(self, smb2Command): |
| 3887 |
if smb2Command in self.__smb2Commands: |
| 3888 |
del(self.__smb2Commands[smb2Command]) |
| 3889 |
|
| 3890 |
def hookSmb2Command(self, smb2Command, callback): |
| 3891 |
if smb2Command in self.__smb2Commands: |
| 3892 |
originalCommand = self.__smb2Commands[smb2Command] |
| 3893 |
else: |
| 3894 |
originalCommand = None |
| 3895 |
|
| 3896 |
self.__smb2Commands[smb2Command] = callback |
| 3897 |
return originalCommand |
| 3898 |
|
| 3899 |
def log(self, msg, level=logging.INFO): |
| 3900 |
self.__log.log(level,msg) |
| 3901 |
|
| 3902 |
def getServerName(self): |
| 3903 |
return self.__serverName |
| 3904 |
|
| 3905 |
def getServerOS(self): |
| 3906 |
return self.__serverOS |
| 3907 |
|
| 3908 |
def getServerDomain(self): |
| 3909 |
return self.__serverDomain |
| 3910 |
|
| 3911 |
def getSMBChallenge(self): |
| 3912 |
return self.__challenge |
| 3913 |
|
| 3914 |
def getServerConfig(self): |
| 3915 |
return self.__serverConfig |
| 3916 |
|
| 3917 |
def setServerConfig(self, config): |
| 3918 |
self.__serverConfig = config |
| 3919 |
|
| 3920 |
def getJTRdumpPath(self): |
| 3921 |
return self.__jtr_dump_path |
| 3922 |
|
| 3923 |
def verify_request(self, request, client_address): |
| 3924 |
# TODO: Control here the max amount of processes we want to launch |
| 3925 |
# returning False, closes the connection |
| 3926 |
return True |
| 3927 |
|
| 3928 |
def processRequest(self, connId, data): |
| 3929 |
|
| 3930 |
# TODO: Process batched commands. |
| 3931 |
isSMB2 = False |
| 3932 |
SMBCommand = None |
| 3933 |
try: |
| 3934 |
packet = smb.NewSMBPacket(data = data) |
| 3935 |
SMBCommand = smb.SMBCommand(packet['Data'][0]) |
| 3936 |
except: |
| 3937 |
# Maybe a SMB2 packet? |
| 3938 |
packet = smb2.SMB2Packet(data = data) |
| 3939 |
isSMB2 = True |
| 3940 |
|
| 3941 |
# We might have compound requests |
| 3942 |
compoundedPacketsResponse = [] |
| 3943 |
compoundedPackets = [] |
| 3944 |
try: |
| 3945 |
# Search out list of implemented commands |
| 3946 |
# We provide them with: |
| 3947 |
# connId : representing the data for this specific connection |
| 3948 |
# self : the SMBSERVER if they want to ask data to it |
| 3949 |
# SMBCommand : the SMBCommand they are expecting to process |
| 3950 |
# packet : the received packet itself, in case they need more data than the actual command |
| 3951 |
# Only for Transactions |
| 3952 |
# transCommand: a list of transaction subcommands |
| 3953 |
# We expect to get: |
| 3954 |
# respCommands: a list of answers for the commands processed |
| 3955 |
# respPacket : if the commands chose to directly craft packet/s, we use this and not the previous |
| 3956 |
# this MUST be a list |
| 3957 |
# errorCode : self explanatory |
| 3958 |
if isSMB2 is False: |
| 3959 |
if packet['Command'] == smb.SMB.SMB_COM_TRANSACTION2: |
| 3960 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 3961 |
connId, |
| 3962 |
self, |
| 3963 |
SMBCommand, |
| 3964 |
packet, |
| 3965 |
self.__smbTrans2Commands) |
| 3966 |
elif packet['Command'] == smb.SMB.SMB_COM_NT_TRANSACT: |
| 3967 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 3968 |
connId, |
| 3969 |
self, |
| 3970 |
SMBCommand, |
| 3971 |
packet, |
| 3972 |
self.__smbNTTransCommands) |
| 3973 |
elif packet['Command'] == smb.SMB.SMB_COM_TRANSACTION: |
| 3974 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 3975 |
connId, |
| 3976 |
self, |
| 3977 |
SMBCommand, |
| 3978 |
packet, |
| 3979 |
self.__smbTransCommands) |
| 3980 |
else: |
| 3981 |
if packet['Command'] in self.__smbCommands: |
| 3982 |
if self.__SMB2Support is True: |
| 3983 |
if packet['Command'] == smb.SMB.SMB_COM_NEGOTIATE: |
| 3984 |
try: |
| 3985 |
respCommands, respPackets, errorCode = self.__smb2Commands[smb2.SMB2_NEGOTIATE](connId, self, packet, True) |
| 3986 |
isSMB2 = True |
| 3987 |
except Exception as e: |
| 3988 |
self.log('SMB2_NEGOTIATE: %s' % e, logging.ERROR) |
| 3989 |
# If something went wrong, let's fallback to SMB1 |
| 3990 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 3991 |
connId, |
| 3992 |
self, |
| 3993 |
SMBCommand, |
| 3994 |
packet) |
| 3995 |
#self.__SMB2Support = False |
| 3996 |
pass |
| 3997 |
else: |
| 3998 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 3999 |
connId, |
| 4000 |
self, |
| 4001 |
SMBCommand, |
| 4002 |
packet) |
| 4003 |
else: |
| 4004 |
respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( |
| 4005 |
connId, |
| 4006 |
self, |
| 4007 |
SMBCommand, |
| 4008 |
packet) |
| 4009 |
else: |
| 4010 |
respCommands, respPackets, errorCode = self.__smbCommands[255](connId, self, SMBCommand, packet) |
| 4011 |
|
| 4012 |
compoundedPacketsResponse.append((respCommands, respPackets, errorCode)) |
| 4013 |
compoundedPackets.append(packet) |
| 4014 |
|
| 4015 |
else: |
| 4016 |
done = False |
| 4017 |
while not done: |
| 4018 |
if packet['Command'] in self.__smb2Commands: |
| 4019 |
if self.__SMB2Support is True: |
| 4020 |
respCommands, respPackets, errorCode = self.__smb2Commands[packet['Command']]( |
| 4021 |
connId, |
| 4022 |
self, |
| 4023 |
packet) |
| 4024 |
else: |
| 4025 |
respCommands, respPackets, errorCode = self.__smb2Commands[255](connId, self, packet) |
| 4026 |
else: |
| 4027 |
respCommands, respPackets, errorCode = self.__smb2Commands[255](connId, self, packet) |
| 4028 |
# Let's store the result for this compounded packet |
| 4029 |
compoundedPacketsResponse.append((respCommands, respPackets, errorCode)) |
| 4030 |
compoundedPackets.append(packet) |
| 4031 |
if packet['NextCommand'] != 0: |
| 4032 |
data = data[packet['NextCommand']:] |
| 4033 |
packet = smb2.SMB2Packet(data = data) |
| 4034 |
else: |
| 4035 |
done = True |
| 4036 |
|
| 4037 |
except Exception as e: |
| 4038 |
#import traceback |
| 4039 |
#traceback.print_exc() |
| 4040 |
# Something wen't wrong, defaulting to Bad user ID |
| 4041 |
self.log('processRequest (0x%x,%s)' % (packet['Command'],e), logging.ERROR) |
| 4042 |
raise |
| 4043 |
|
| 4044 |
# We prepare the response packet to commands don't need to bother about that. |
| 4045 |
connData = self.getConnectionData(connId, False) |
| 4046 |
|
| 4047 |
# Force reconnection loop.. This is just a test.. client will send me back credentials :) |
| 4048 |
#connData['PacketNum'] += 1 |
| 4049 |
#if connData['PacketNum'] == 15: |
| 4050 |
# connData['PacketNum'] = 0 |
| 4051 |
# # Something wen't wrong, defaulting to Bad user ID |
| 4052 |
# self.log('Sending BAD USER ID!', logging.ERROR) |
| 4053 |
# #raise |
| 4054 |
# packet['Flags1'] |= smb.SMB.FLAGS1_REPLY |
| 4055 |
# packet['Flags2'] = 0 |
| 4056 |
# errorCode = STATUS_SMB_BAD_UID |
| 4057 |
# packet['ErrorCode'] = errorCode >> 16 |
| 4058 |
# packet['ErrorClass'] = errorCode & 0xff |
| 4059 |
# return [packet] |
| 4060 |
|
| 4061 |
self.setConnectionData(connId, connData) |
| 4062 |
|
| 4063 |
packetsToSend = [] |
| 4064 |
for packetNum in range(len(compoundedPacketsResponse)): |
| 4065 |
respCommands, respPackets, errorCode = compoundedPacketsResponse[packetNum] |
| 4066 |
packet = compoundedPackets[packetNum] |
| 4067 |
if respPackets is None: |
| 4068 |
for respCommand in respCommands: |
| 4069 |
if isSMB2 is False: |
| 4070 |
respPacket = smb.NewSMBPacket() |
| 4071 |
respPacket['Flags1'] = smb.SMB.FLAGS1_REPLY |
| 4072 |
|
| 4073 |
# TODO this should come from a per session configuration |
| 4074 |
respPacket['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES | packet['Flags2'] & smb.SMB.FLAGS2_UNICODE |
| 4075 |
#respPacket['Flags2'] = smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_LONG_NAMES |
| 4076 |
#respPacket['Flags1'] = 0x98 |
| 4077 |
#respPacket['Flags2'] = 0xc807 |
| 4078 |
|
| 4079 |
|
| 4080 |
respPacket['Tid'] = packet['Tid'] |
| 4081 |
respPacket['Mid'] = packet['Mid'] |
| 4082 |
respPacket['Pid'] = packet['Pid'] |
| 4083 |
respPacket['Uid'] = connData['Uid'] |
| 4084 |
|
| 4085 |
respPacket['ErrorCode'] = errorCode >> 16 |
| 4086 |
respPacket['_reserved'] = errorCode >> 8 & 0xff |
| 4087 |
respPacket['ErrorClass'] = errorCode & 0xff |
| 4088 |
respPacket.addCommand(respCommand) |
| 4089 |
|
| 4090 |
packetsToSend.append(respPacket) |
| 4091 |
else: |
| 4092 |
respPacket = smb2.SMB2Packet() |
| 4093 |
respPacket['Flags'] = smb2.SMB2_FLAGS_SERVER_TO_REDIR |
| 4094 |
if packetNum > 0: |
| 4095 |
respPacket['Flags'] |= smb2.SMB2_FLAGS_RELATED_OPERATIONS |
| 4096 |
respPacket['Status'] = errorCode |
| 4097 |
respPacket['CreditRequestResponse'] = packet['CreditRequestResponse'] |
| 4098 |
respPacket['Command'] = packet['Command'] |
| 4099 |
respPacket['CreditCharge'] = packet['CreditCharge'] |
| 4100 |
#respPacket['CreditCharge'] = 0 |
| 4101 |
respPacket['Reserved'] = packet['Reserved'] |
| 4102 |
respPacket['SessionID'] = connData['Uid'] |
| 4103 |
respPacket['MessageID'] = packet['MessageID'] |
| 4104 |
respPacket['TreeID'] = packet['TreeID'] |
| 4105 |
respPacket['Data'] = str(respCommand) |
| 4106 |
packetsToSend.append(respPacket) |
| 4107 |
else: |
| 4108 |
# The SMBCommand took care of building the packet |
| 4109 |
packetsToSend = respPackets |
| 4110 |
|
| 4111 |
if isSMB2 is True: |
| 4112 |
# Let's build a compound answer |
| 4113 |
finalData = '' |
| 4114 |
i = 0 |
| 4115 |
for i in range(len(packetsToSend)-1): |
| 4116 |
packet = packetsToSend[i] |
| 4117 |
# Align to 8-bytes |
| 4118 |
padLen = (8 - (len(packet) % 8) ) % 8 |
| 4119 |
packet['NextCommand'] = len(packet) + padLen |
| 4120 |
finalData += str(packet) + padLen*'\x00' |
| 4121 |
|
| 4122 |
# Last one |
| 4123 |
finalData += str(packetsToSend[len(packetsToSend)-1]) |
| 4124 |
packetsToSend = [finalData] |
| 4125 |
|
| 4126 |
# We clear the compound requests |
| 4127 |
connData['LastRequest'] = {} |
| 4128 |
|
| 4129 |
return packetsToSend |
| 4130 |
|
| 4131 |
def processConfigFile(self, configFile = None): |
| 4132 |
# TODO: Do a real config parser |
| 4133 |
if self.__serverConfig is None: |
| 4134 |
if configFile is None: |
| 4135 |
configFile = 'smb.conf' |
| 4136 |
self.__serverConfig = configparser.ConfigParser() |
| 4137 |
self.__serverConfig.read(configFile) |
| 4138 |
|
| 4139 |
self.__serverName = self.__serverConfig.get('global','server_name') |
| 4140 |
self.__serverOS = self.__serverConfig.get('global','server_os') |
| 4141 |
self.__serverDomain = self.__serverConfig.get('global','server_domain') |
| 4142 |
self.__logFile = self.__serverConfig.get('global','log_file') |
| 4143 |
if self.__serverConfig.has_option('global', 'challenge'): |
| 4144 |
self.__challenge = self.__serverConfig.get('global', 'challenge') |
| 4145 |
else: |
| 4146 |
self.__challenge = 'A'*8 |
| 4147 |
|
| 4148 |
if self.__serverConfig.has_option("global", "jtr_dump_path"): |
| 4149 |
self.__jtr_dump_path = self.__serverConfig.get("global", "jtr_dump_path") |
| 4150 |
|
| 4151 |
if self.__serverConfig.has_option("global", "SMB2Support"): |
| 4152 |
self.__SMB2Support = self.__serverConfig.getboolean("global","SMB2Support") |
| 4153 |
else: |
| 4154 |
self.__SMB2Support = False |
| 4155 |
|
| 4156 |
if self.__logFile != 'None': |
| 4157 |
logging.basicConfig(filename = self.__logFile, |
| 4158 |
level = logging.DEBUG, |
| 4159 |
format="%(asctime)s: %(levelname)s: %(message)s", |
| 4160 |
datefmt = '%m/%d/%Y %I:%M:%S %p') |
| 4161 |
self.__log = LOG |
| 4162 |
|
| 4163 |
# Process the credentials |
| 4164 |
credentials_fname = self.__serverConfig.get('global','credentials_file') |
| 4165 |
if credentials_fname is not "": |
| 4166 |
cred = open(credentials_fname) |
| 4167 |
line = cred.readline() |
| 4168 |
while line: |
| 4169 |
name, domain, lmhash, nthash = line.split(':') |
| 4170 |
self.__credentials[name] = (domain, lmhash, nthash.strip('\r\n')) |
| 4171 |
line = cred.readline() |
| 4172 |
cred.close() |
| 4173 |
self.log('Config file parsed') |
| 4174 |
|
| 4175 |
# For windows platforms, opening a directory is not an option, so we set a void FD |
| 4176 |
VOID_FILE_DESCRIPTOR = -1 |
| 4177 |
PIPE_FILE_DESCRIPTOR = -2 |