github.com/Coalfire-Research/Slackor@v0.0.0-20191010164036-aa32a7f9250b/impacket/examples/mssqlclient.py (about) 1 #!/usr/bin/env python 2 # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. 3 # 4 # This software is provided under under a slightly modified version 5 # of the Apache Software License. See the accompanying LICENSE file 6 # for more information. 7 # 8 # Description: [MS-TDS] & [MC-SQLR] example. 9 # 10 # Author: 11 # Alberto Solino (beto@coresecurity.com/@agsolino) 12 # 13 # Reference for: 14 # Structure 15 # 16 17 from __future__ import division 18 from __future__ import print_function 19 import argparse 20 import sys 21 import os 22 import logging 23 24 from impacket.examples import logger 25 from impacket import version, tds 26 27 if __name__ == '__main__': 28 import cmd 29 30 class SQLSHELL(cmd.Cmd): 31 def __init__(self, SQL): 32 cmd.Cmd.__init__(self) 33 self.sql = SQL 34 self.prompt = 'SQL> ' 35 self.intro = '[!] Press help for extra shell commands' 36 37 def do_help(self, line): 38 print(""" 39 lcd {path} - changes the current local directory to {path} 40 exit - terminates the server process (and this session) 41 enable_xp_cmdshell - you know what it means 42 disable_xp_cmdshell - you know what it means 43 xp_cmdshell {cmd} - executes cmd using xp_cmdshell 44 sp_start_job {cmd} - executes cmd using the sql server agent (blind) 45 ! {cmd} - executes a local shell cmd 46 """) 47 48 def do_shell(self, s): 49 os.system(s) 50 51 def do_xp_cmdshell(self, s): 52 try: 53 self.sql.sql_query("exec master..xp_cmdshell '%s'" % s) 54 self.sql.printReplies() 55 self.sql.colMeta[0]['TypeData'] = 80*2 56 self.sql.printRows() 57 except: 58 pass 59 60 def sp_start_job(self, s): 61 try: 62 self.sql.sql_query("DECLARE @job NVARCHAR(100);" 63 "SET @job='IdxDefrag'+CONVERT(NVARCHAR(36),NEWID());" 64 "EXEC msdb..sp_add_job @job_name=@job,@description='INDEXDEFRAG'," 65 "@owner_login_name='sa',@delete_level=3;" 66 "EXEC msdb..sp_add_jobstep @job_name=@job,@step_id=1,@step_name='Defragmentation'," 67 "@subsystem='CMDEXEC',@command='%s',@on_success_action=1;" 68 "EXEC msdb..sp_add_jobserver @job_name=@job;" 69 "EXEC msdb..sp_start_job @job_name=@job;" % s) 70 self.sql.printReplies() 71 self.sql.printRows() 72 except: 73 pass 74 75 def do_lcd(self, s): 76 if s == '': 77 print(os.getcwd()) 78 else: 79 os.chdir(s) 80 81 def do_enable_xp_cmdshell(self, line): 82 try: 83 self.sql.sql_query("exec master.dbo.sp_configure 'show advanced options',1;RECONFIGURE;" 84 "exec master.dbo.sp_configure 'xp_cmdshell', 1;RECONFIGURE;") 85 self.sql.printReplies() 86 self.sql.printRows() 87 except: 88 pass 89 90 def do_disable_xp_cmdshell(self, line): 91 try: 92 self.sql.sql_query("exec sp_configure 'xp_cmdshell', 0 ;RECONFIGURE;exec sp_configure " 93 "'show advanced options', 0 ;RECONFIGURE;") 94 self.sql.printReplies() 95 self.sql.printRows() 96 except: 97 pass 98 99 def default(self, line): 100 try: 101 self.sql.sql_query(line) 102 self.sql.printReplies() 103 self.sql.printRows() 104 except: 105 pass 106 107 def emptyline(self): 108 pass 109 110 def do_exit(self, line): 111 return True 112 113 # Init the example's logger theme 114 logger.init() 115 print(version.BANNER) 116 117 parser = argparse.ArgumentParser(add_help = True, description = "TDS client implementation (SSL supported).") 118 119 parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>') 120 parser.add_argument('-port', action='store', default='1433', help='target MSSQL port (default 1433)') 121 parser.add_argument('-db', action='store', help='MSSQL database instance (default None)') 122 parser.add_argument('-windows-auth', action='store_true', default = 'False', help='whether or not to use Windows ' 123 'Authentication (default False)') 124 parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 125 parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the SQL shell') 126 127 group = parser.add_argument_group('authentication') 128 129 group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH') 130 group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)') 131 group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file ' 132 '(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ' 133 'ones specified in the command line') 134 group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication ' 135 '(128 or 256 bits)') 136 group.add_argument('-dc-ip', action='store',metavar = "ip address", help='IP Address of the domain controller. If ' 137 'ommited it use the domain part (FQDN) specified in the target parameter') 138 139 if len(sys.argv)==1: 140 parser.print_help() 141 sys.exit(1) 142 143 options = parser.parse_args() 144 145 if options.debug is True: 146 logging.getLogger().setLevel(logging.DEBUG) 147 else: 148 logging.getLogger().setLevel(logging.INFO) 149 150 import re 151 152 domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match( 153 options.target).groups('') 154 155 #In case the password contains '@' 156 if '@' in address: 157 password = password + '@' + address.rpartition('@')[0] 158 address = address.rpartition('@')[2] 159 160 if domain is None: 161 domain = '' 162 163 if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None: 164 from getpass import getpass 165 password = getpass("Password:") 166 167 if options.aesKey is not None: 168 options.k = True 169 170 ms_sql = tds.MSSQL(address, int(options.port)) 171 ms_sql.connect() 172 try: 173 if options.k is True: 174 res = ms_sql.kerberosLogin(options.db, username, password, domain, options.hashes, options.aesKey, 175 kdcHost=options.dc_ip) 176 else: 177 res = ms_sql.login(options.db, username, password, domain, options.hashes, options.windows_auth) 178 ms_sql.printReplies() 179 except Exception as e: 180 logging.debug("Exception:", exc_info=True) 181 logging.error(str(e)) 182 res = False 183 if res is True: 184 shell = SQLSHELL(ms_sql) 185 if options.file is None: 186 shell.cmdloop() 187 else: 188 for line in options.file.readlines(): 189 print("SQL> %s" % line, end=' ') 190 shell.onecmd(line) 191 ms_sql.disconnect()