Adding Negotiate/Kerberos authentication (#3404)

This commit is contained in:
Miroslav Štampar 2026-07-24 22:26:43 +02:00
parent 2d9e9ed959
commit 1bd1b457d7
12 changed files with 1479 additions and 9 deletions

View file

@ -439,6 +439,7 @@ class AUTH_TYPE(object):
DIGEST = "digest"
BEARER = "bearer"
NTLM = "ntlm"
NEGOTIATE = "negotiate"
PKI = "pki"
class AUTOCOMPLETE_TYPE(object):

View file

@ -1332,8 +1332,11 @@ def _setHTTPHandlers():
# proxy - the keep-alive handler pools the proxy socket for plain HTTP and the CONNECT-tunnelled
# socket per origin for HTTPS); '--no-keep-alive' opts out, and they are automatically disabled
# when incompatible (authentication methods, or chunked transfer-encoding of the request body -
# handled by a dedicated, non-pooling handler)
conf.keepAlive = not conf.noKeepAlive and not conf.authType and not conf.chunked
# handled by a dedicated, non-pooling handler). Negotiate is the one auth exception: its token is
# a per-request, end-to-end header (minted fresh each request, no connection-bound handshake), so
# persistent connections remain safe and worthwhile.
negotiateAuth = (conf.authType or "").lower() == AUTH_TYPE.NEGOTIATE
conf.keepAlive = not conf.noKeepAlive and not conf.chunked and (not conf.authType or negotiateAuth)
if conf.keepAlive:
# persistent connections for both HTTP and HTTPS; the keep-alive HTTPS
@ -1449,7 +1452,7 @@ def _setAuthCred():
def _setHTTPAuthentication():
"""
Check and set the HTTP(s) authentication method (Basic, Digest, Bearer, NTLM or PKI),
Check and set the HTTP(s) authentication method (Basic, Digest, Bearer, NTLM, Negotiate or PKI),
username and password for first three methods, or PEM private key file for
PKI authentication
"""
@ -1472,9 +1475,9 @@ def _setHTTPAuthentication():
errMsg += "but did not provide the type (e.g. --auth-type=\"basic\")"
raise SqlmapSyntaxException(errMsg)
elif (conf.authType or "").lower() not in (AUTH_TYPE.BASIC, AUTH_TYPE.DIGEST, AUTH_TYPE.BEARER, AUTH_TYPE.NTLM, AUTH_TYPE.PKI):
elif (conf.authType or "").lower() not in (AUTH_TYPE.BASIC, AUTH_TYPE.DIGEST, AUTH_TYPE.BEARER, AUTH_TYPE.NTLM, AUTH_TYPE.NEGOTIATE, AUTH_TYPE.PKI):
errMsg = "HTTP authentication type value must be "
errMsg += "Basic, Digest, Bearer, NTLM or PKI"
errMsg += "Basic, Digest, Bearer, NTLM, Negotiate or PKI"
raise SqlmapSyntaxException(errMsg)
if not conf.authFile:
@ -1490,11 +1493,12 @@ def _setHTTPAuthentication():
elif authType == AUTH_TYPE.BEARER:
conf.httpHeaders.append((HTTP_HEADER.AUTHORIZATION, "Bearer %s" % conf.authCred.strip()))
return
elif authType == AUTH_TYPE.NTLM:
elif authType in (AUTH_TYPE.NTLM, AUTH_TYPE.NEGOTIATE):
# Note: the DOMAIN\username part is colon-free, so the password group takes the full
# remainder (a greedy first group would otherwise swallow colons inside the password)
# remainder (a greedy first group would otherwise swallow colons inside the password).
# For Negotiate, DOMAIN is the Kerberos realm.
regExp = "^([^:]*\\\\[^:]*):(.*)$"
errMsg = "HTTP NTLM authentication credentials value must "
errMsg = "HTTP %s authentication credentials value must " % authType
errMsg += "be in format 'DOMAIN\\username:password'"
elif authType == AUTH_TYPE.PKI:
errMsg = "HTTP PKI authentication require "
@ -1522,6 +1526,12 @@ def _setHTTPAuthentication():
elif authType == AUTH_TYPE.NTLM:
from lib.request.ntlm import HTTPNtlmAuthHandler
authHandler = HTTPNtlmAuthHandler(kb.passwordMgr)
elif authType == AUTH_TYPE.NEGOTIATE:
from lib.request.kerberos import HTTPNegotiateAuthHandler
# DOMAIN is the Kerberos realm; the KDC is auto-discovered (env / krb5.conf / DNS SRV / realm)
realm, _, user = conf.authUsername.partition('\\')
authHandler = HTTPNegotiateAuthHandler(realm, user, conf.authPassword)
else:
debugMsg = "setting the HTTP(s) authentication PEM private key"
logger.debug(debugMsg)

View file

@ -20,7 +20,7 @@ from lib.core.enums import OS
from thirdparty import six
# sqlmap version (<major>.<minor>.<month>.<monthly commit>)
VERSION = "1.10.7.182"
VERSION = "1.10.7.183"
TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable"
TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34}
VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE)

84
lib/request/kerberos.py Normal file
View file

@ -0,0 +1,84 @@
#!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
# Native, dependency-free HTTP "Negotiate" (SPNEGO/Kerberos) authentication, built on the in-tree
# pure-Python Kerberos client (extra/kerberos). No 'pykerberos'/'gssapi'/'requests-kerberos' needed.
# The TGT and per-service tickets are obtained once and cached; a fresh AP-REQ is minted for every
# request from the cached ticket (as replay caches require), so an entire scan costs a single AS+TGS
# exchange and the token is sent pre-emptively (no extra 401 round-trip per request). Python 2.7 / 3.x.
import base64
import logging
import threading
from lib.core.common import getSafeExString
from lib.core.common import singleTimeLogMessage
from lib.core.convert import getText
from lib.core.enums import HTTP_HEADER
from thirdparty.six.moves import urllib as _urllib
from extra.kerberos.client import getServiceTicket
from extra.kerberos.client import getTGT
from extra.kerberos.client import KerberosError
from extra.kerberos.client import spnegoFromTicket
from extra.kerberos.discovery import discoverKdc
class HTTPNegotiateAuthHandler(_urllib.request.BaseHandler):
handler_order = 480
def __init__(self, realm, username, password, kdcHost=None, kdcPort=None):
self.realm = realm.upper()
self.username = username
self.password = password
self.kdcHost = kdcHost # None -> discovered from the realm on first use
self.kdcPort = kdcPort
self._tgt = None
self._tickets = {} # target host -> service-ticket dict
self._tgtFailure = None # realm-wide failure (bad creds / KDC down)
self._hostFailures = {} # per-host failure (e.g. no HTTP/<host> SPN)
self._lock = threading.Lock()
def _serviceTicket(self, host):
with self._lock:
if self._tgtFailure is not None: # TGT unobtainable -> nothing in the realm works
raise self._tgtFailure
if host in self._hostFailures: # this host already failed -> don't retry it
raise self._hostFailures[host]
if host not in self._tickets:
if self._tgt is None:
if self.kdcHost is None: # krb5.conf / DNS SRV / realm-name discovery
self.kdcHost, self.kdcPort = discoverKdc(self.realm)
try:
self._tgt = getTGT(self.realm, self.username, self.password, self.kdcHost, self.kdcPort)
except Exception as ex: # cache so the AS exchange runs at most once
self._tgtFailure = ex
raise
try:
self._tickets[host] = getServiceTicket(self._tgt, self.realm, self.username, ["HTTP", host], self.kdcHost, self.kdcPort)
except Exception as ex: # host-specific -> other hosts remain usable
self._hostFailures[host] = ex
raise
return self._tickets[host]
def _requestHandler(self, req):
host = _urllib.parse.urlsplit(req.get_full_url()).hostname
if host:
try:
token = spnegoFromTicket(self._serviceTicket(host), self.realm, self.username)
req.add_unredirected_header(HTTP_HEADER.AUTHORIZATION, "Negotiate %s" % getText(base64.b64encode(token)))
except KerberosError as ex:
# bad credentials / KDC-refused: log once, fall through unauthenticated (server 401s)
singleTimeLogMessage("Negotiate (Kerberos) authentication failed: %s" % getSafeExString(ex), logging.ERROR)
except Exception as ex:
# unreachable KDC, malformed reply, etc. - never let it crash the run
singleTimeLogMessage("could not obtain a Kerberos ticket (is the KDC '%s:%s' reachable?): %s" % (self.kdcHost, self.kdcPort, getSafeExString(ex)), logging.ERROR)
return req
def http_request(self, req):
return self._requestHandler(req)
https_request = http_request