ntlmpool.py 4.4 KB

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