Path: blob/master/venv/Lib/site-packages/urllib3/contrib/ntlmpool.py
811 views
"""1NTLM authenticating pool, contributed by erikcederstran23Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=104"""5from __future__ import absolute_import67from logging import getLogger8from ntlm import ntlm910from .. import HTTPSConnectionPool11from ..packages.six.moves.http_client import HTTPSConnection121314log = getLogger(__name__)151617class NTLMConnectionPool(HTTPSConnectionPool):18"""19Implements an NTLM authentication version of an urllib3 connection pool20"""2122scheme = "https"2324def __init__(self, user, pw, authurl, *args, **kwargs):25"""26authurl is a random URL on the server that is protected by NTLM.27user is the Windows user, probably in the DOMAIN\\username format.28pw is the password for the user.29"""30super(NTLMConnectionPool, self).__init__(*args, **kwargs)31self.authurl = authurl32self.rawuser = user33user_parts = user.split("\\", 1)34self.domain = user_parts[0].upper()35self.user = user_parts[1]36self.pw = pw3738def _new_conn(self):39# Performs the NTLM handshake that secures the connection. The socket40# must be kept open while requests are performed.41self.num_connections += 142log.debug(43"Starting NTLM HTTPS connection no. %d: https://%s%s",44self.num_connections,45self.host,46self.authurl,47)4849headers = {"Connection": "Keep-Alive"}50req_header = "Authorization"51resp_header = "www-authenticate"5253conn = HTTPSConnection(host=self.host, port=self.port)5455# Send negotiation message56headers[req_header] = "NTLM %s" % ntlm.create_NTLM_NEGOTIATE_MESSAGE(57self.rawuser58)59log.debug("Request headers: %s", headers)60conn.request("GET", self.authurl, None, headers)61res = conn.getresponse()62reshdr = dict(res.getheaders())63log.debug("Response status: %s %s", res.status, res.reason)64log.debug("Response headers: %s", reshdr)65log.debug("Response data: %s [...]", res.read(100))6667# Remove the reference to the socket, so that it can not be closed by68# the response object (we want to keep the socket open)69res.fp = None7071# Server should respond with a challenge message72auth_header_values = reshdr[resp_header].split(", ")73auth_header_value = None74for s in auth_header_values:75if s[:5] == "NTLM ":76auth_header_value = s[5:]77if auth_header_value is None:78raise Exception(79"Unexpected %s response header: %s" % (resp_header, reshdr[resp_header])80)8182# Send authentication message83ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(84auth_header_value85)86auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(87ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags88)89headers[req_header] = "NTLM %s" % auth_msg90log.debug("Request headers: %s", headers)91conn.request("GET", self.authurl, None, headers)92res = conn.getresponse()93log.debug("Response status: %s %s", res.status, res.reason)94log.debug("Response headers: %s", dict(res.getheaders()))95log.debug("Response data: %s [...]", res.read()[:100])96if res.status != 200:97if res.status == 401:98raise Exception("Server rejected request: wrong username or password")99raise Exception("Wrong server response: %s %s" % (res.status, res.reason))100101res.fp = None102log.debug("Connection established")103return conn104105def urlopen(106self,107method,108url,109body=None,110headers=None,111retries=3,112redirect=True,113assert_same_host=True,114):115if headers is None:116headers = {}117headers["Connection"] = "Keep-Alive"118return super(NTLMConnectionPool, self).urlopen(119method, url, body, headers, retries, redirect, assert_same_host120)121122123