ntlmpool.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """
  2. NTLM authenticating pool, contributed by erikcederstran
  3. Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
  4. """
  5. from __future__ import absolute_import
  6. from logging import getLogger
  7. from ntlm import ntlm
  8. from .. import HTTPSConnectionPool
  9. from ..packages.six.moves.http_client import HTTPSConnection
  10. log = getLogger(__name__)
  11. class NTLMConnectionPool(HTTPSConnectionPool):
  12. """
  13. Implements an NTLM authentication version of an urllib3 connection pool
  14. """
  15. scheme = 'https'
  16. def __init__(self, user, pw, authurl, *args, **kwargs):
  17. """
  18. authurl is a random URL on the server that is protected by NTLM.
  19. user is the Windows user, probably in the DOMAIN\\username format.
  20. pw is the password for the user.
  21. """
  22. super(NTLMConnectionPool, self).__init__(*args, **kwargs)
  23. self.authurl = authurl
  24. self.rawuser = user
  25. user_parts = user.split('\\', 1)
  26. self.domain = user_parts[0].upper()
  27. self.user = user_parts[1]
  28. self.pw = pw
  29. def _new_conn(self):
  30. # Performs the NTLM handshake that secures the connection. The socket
  31. # must be kept open while requests are performed.
  32. self.num_connections += 1
  33. log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',
  34. self.num_connections, self.host, self.authurl)
  35. headers = {'Connection': 'Keep-Alive'}
  36. req_header = 'Authorization'
  37. resp_header = 'www-authenticate'
  38. conn = HTTPSConnection(host=self.host, port=self.port)
  39. # Send negotiation message
  40. headers[req_header] = (
  41. 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
  42. log.debug('Request headers: %s', headers)
  43. conn.request('GET', self.authurl, None, headers)
  44. res = conn.getresponse()
  45. reshdr = dict(res.getheaders())
  46. log.debug('Response status: %s %s', res.status, res.reason)
  47. log.debug('Response headers: %s', reshdr)
  48. log.debug('Response data: %s [...]', res.read(100))
  49. # Remove the reference to the socket, so that it can not be closed by
  50. # the response object (we want to keep the socket open)
  51. res.fp = None
  52. # Server should respond with a challenge message
  53. auth_header_values = reshdr[resp_header].split(', ')
  54. auth_header_value = None
  55. for s in auth_header_values:
  56. if s[:5] == 'NTLM ':
  57. auth_header_value = s[5:]
  58. if auth_header_value is None:
  59. raise Exception('Unexpected %s response header: %s' %
  60. (resp_header, reshdr[resp_header]))
  61. # Send authentication message
  62. ServerChallenge, NegotiateFlags = \
  63. ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
  64. auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
  65. self.user,
  66. self.domain,
  67. self.pw,
  68. NegotiateFlags)
  69. headers[req_header] = 'NTLM %s' % auth_msg
  70. log.debug('Request headers: %s', headers)
  71. conn.request('GET', self.authurl, None, headers)
  72. res = conn.getresponse()
  73. log.debug('Response status: %s %s', res.status, res.reason)
  74. log.debug('Response headers: %s', dict(res.getheaders()))
  75. log.debug('Response data: %s [...]', res.read()[:100])
  76. if res.status != 200:
  77. if res.status == 401:
  78. raise Exception('Server rejected request: wrong '
  79. 'username or password')
  80. raise Exception('Wrong server response: %s %s' %
  81. (res.status, res.reason))
  82. res.fp = None
  83. log.debug('Connection established')
  84. return conn
  85. def urlopen(self, method, url, body=None, headers=None, retries=3,
  86. redirect=True, assert_same_host=True):
  87. if headers is None:
  88. headers = {}
  89. headers['Connection'] = 'Keep-Alive'
  90. return super(NTLMConnectionPool, self).urlopen(method, url, body,
  91. headers, retries,
  92. redirect,
  93. assert_same_host)