Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ What protocols are featured?
* MSRPC version 5, over different transports: TCP, SMB/TCP, SMB/NetBIOS and HTTP.
* Plain, NTLM and Kerberos authentications, using password/hashes/tickets/keys.
* Portions/full implementation of the following MSRPC interfaces: EPM, DTYPES, LSAD, LSAT, NRPC, RRP, SAMR, SRVS, WKST, SCMR, BKRP, DHCPM, EVEN6, MGMT, SASEC, TSCH, DCOM, WMI, OXABREF, NSPI, OXNSPI.
* Portions of TDS (MSSQL) and LDAP protocol implementations.
* Portions of TDS (MSSQL), PostgreSQL and LDAP protocol implementations.

Maintainer
==========
Expand Down
147 changes: 147 additions & 0 deletions examples/pgsqlclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
#!/usr/bin/env python
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description:
# PostgreSQL client example. Supports the password based methods (cleartext, md5,
# SCRAM-SHA-256), NTLM (sspi) and Kerberos (gss/sspi) authentication, over TLS or GSSAPI encryption.
#
# Author:
# Giovanni A. (@azoxlpf)
#

import argparse
import codecs
import logging
import sys
from getpass import getpass

from impacket import version
from impacket.examples import logger
from impacket.examples.pgsqlshell import PGSQLSHELL
from impacket.examples.utils import parse_target
from impacket.krb5.kerberosv5 import KerberosError
from impacket.postgresql import PostgreSQL, PostgreSQLError

TLS_MODES = {'prefer': None, 'require': True, 'disable': False, 'direct': True}


if __name__ == '__main__':
print(version.BANNER)

parser = argparse.ArgumentParser(add_help=True, description="PostgreSQL client implementation (TLS supported).")

parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
parser.add_argument('-db', action='store', default='postgres', help='database to connect to (default postgres)')
parser.add_argument('-windows-auth', action='store_true', default=False, help='only accept NTLM (sspi): never '
'send the password to a server asking for a password method (default False)')
parser.add_argument('-role', action='store', help='database role to log in as, when it differs from the '
'username (NTLM/Kerberos user name maps)')
parser.add_argument('-tls', choices=sorted(TLS_MODES), default='prefer', help='TLS mode, direct skips the SSLRequest negotiation '
'(PostgreSQL 17+) (default prefer)')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')
parser.add_argument('-show', action='store_true', help='show the queries')
parser.add_argument('-codec', action='store', default='utf-8', help='Sets encoding used (codec) from the target\'s '
'output of copy_program (default "utf-8"). If errors are detected, run chcp.com at the target, '
'map the result with https://docs.python.org/3/library/codecs.html#standard-encodings')
parser.add_argument('-command', action='extend', nargs='*', help='Commands to execute in the SQL shell. Multiple '
'commands can be passed.')
parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the SQL shell')

group = parser.add_argument_group('authentication')

group.add_argument('-hashes', action="store", metavar="LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
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')
group.add_argument('-aesKey', action="store", metavar="hex key", help='AES key to use for Kerberos Authentication '
'(128 or 256 bits)')
group.add_argument('-gssenc', action='store_true', help='Encrypt the session with GSSAPI (Kerberos) instead of TLS. '
'Implies -k')
group.add_argument('-service', action='store', default='postgres', help='service class of the Kerberos SPN '
'(default postgres)')

group = parser.add_argument_group('connection')

group.add_argument('-dc-ip', action='store', metavar="ip address", help='IP Address of the domain controller. If '
'ommited it use the domain part (FQDN) specified in the target parameter')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
'This is useful when target is the NetBIOS name and you cannot resolve it')
group.add_argument('-port', action='store', default='5432', help='target PostgreSQL port (default 5432)')

if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)

options = parser.parse_args()
logger.init(options.ts, options.debug)

try:
codecs.lookup(options.codec)
except LookupError:
logging.error('Unknown codec: %s' % options.codec)
sys.exit(1)

domain, username, password, remoteName = parse_target(options.target)

if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
password = getpass("Password:")

if options.target_ip is None:
options.target_ip = remoteName

if options.aesKey is not None or options.gssenc:
options.k = True

if options.gssenc:
options.tls = 'disable'

connection = PostgreSQL(options.target_ip, int(options.port), remoteName, TLS_MODES[options.tls],
krbService=options.service, tlsDirect=options.tls == 'direct')
try:
connection.connect()
if options.gssenc:
connection.gssEncrypt(username, password, domain, options.hashes, options.aesKey, kdcHost=options.dc_ip)
if options.k is True:
connection.kerberosLogin(options.db, username, password, domain, options.hashes, options.aesKey,
kdcHost=options.dc_ip, role=options.role)
else:
connection.login(options.db, username, password, domain, options.hashes, role=options.role,
allowedMethods=('sspi',) if options.windows_auth else None)
except (PostgreSQLError, KerberosError, OSError) as e:
logging.debug("Exception:", exc_info=True)
logging.error(str(e))
sys.exit(1)

# The connection timeout must not abort long running statements
connection.settimeout(None)

encryption = ' (TLS)' if connection.tls else ' (GSSAPI encryption)' if connection.gss else ''
logging.info('Connected to PostgreSQL %s%s' % (connection.parameters.get('server_version', ''), encryption))
shell = PGSQLSHELL(connection, options.db, options.show, options.codec)
if options.file:
for line in options.file:
print("SQL> %s" % line, end=' ')
if shell.onecmd(line):
break
elif options.command:
for command in options.command:
print("SQL> %s" % command)
if shell.onecmd(command):
break
else:
try:
shell.cmdloop()
except KeyboardInterrupt:
print()
connection.disconnect()
Loading
Loading