|
| 1 | +# This library is free software: you can redistribute it and/or |
| 2 | +# modify it under the terms of the GNU Lesser General Public |
| 3 | +# License as published by the Free Software Foundation, either |
| 4 | +# version 3 of the License, or (at your option) any later version. |
| 5 | + |
| 6 | +# This library is distributed in the hope that it will be useful, |
| 7 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 8 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 9 | +# Lesser General Public License for more details. |
| 10 | +# |
| 11 | +# You should have received a copy of the GNU Lesser General Public |
| 12 | +# License along with this library. If not, see <http://www.gnu.org/licenses/> or <http://www.gnu.org/licenses/lgpl.txt>. |
| 13 | + |
| 14 | +import urllib2 |
| 15 | +import httplib, socket |
| 16 | +from urllib import addinfourl |
| 17 | +import ntlm |
| 18 | + |
| 19 | +class AbstractNtlmAuthHandler: |
| 20 | + def __init__(self, password_mgr=None, debuglevel=0): |
| 21 | + if password_mgr is None: |
| 22 | + password_mgr = HTTPPasswordMgr() |
| 23 | + self.passwd = password_mgr |
| 24 | + self.add_password = self.passwd.add_password |
| 25 | + self._debuglevel = debuglevel |
| 26 | + |
| 27 | + def set_http_debuglevel(self, level): |
| 28 | + self._debuglevel = level |
| 29 | + |
| 30 | + def http_error_authentication_required(self, auth_header_field, req, fp, headers): |
| 31 | + auth_header_value = headers.get(auth_header_field, None) |
| 32 | + if auth_header_field: |
| 33 | + if auth_header_value is not None and 'ntlm' in auth_header_value.lower(): |
| 34 | + fp.close() |
| 35 | + return self.retry_using_http_NTLM_auth(req, auth_header_field, None, headers) |
| 36 | + |
| 37 | + def retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers): |
| 38 | + user, pw = self.passwd.find_user_password(realm, req.get_full_url()) |
| 39 | + if pw is not None: |
| 40 | + # ntlm secures a socket, so we must use the same socket for the complete handshake |
| 41 | + headers = dict(req.headers) |
| 42 | + headers.update(req.unredirected_hdrs) |
| 43 | + auth = 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(user) |
| 44 | + if req.headers.get(self.auth_header, None) == auth: |
| 45 | + return None |
| 46 | + headers[self.auth_header] = auth |
| 47 | + |
| 48 | + host = req.get_host() |
| 49 | + if not host: |
| 50 | + raise urllib2.URLError('no host given') |
| 51 | + h = None |
| 52 | + if req.get_full_url().startswith('https://'): |
| 53 | + h = httplib.HTTPSConnection(host) # will parse host:port |
| 54 | + else: |
| 55 | + h = httplib.HTTPConnection(host) # will parse host:port |
| 56 | + h.set_debuglevel(self._debuglevel) |
| 57 | + # we must keep the connection because NTLM authenticates the connection, not single requests |
| 58 | + headers["Connection"] = "Keep-Alive" |
| 59 | + headers = dict((name.title(), val) for name, val in headers.items()) |
| 60 | + h.request(req.get_method(), req.get_selector(), req.data, headers) |
| 61 | + r = h.getresponse() |
| 62 | + r.begin() |
| 63 | + r._safe_read(int(r.getheader('content-length'))) |
| 64 | + if r.getheader('set-cookie'): |
| 65 | + # this is important for some web applications that store authentication-related info in cookies (it took a long time to figure out) |
| 66 | + headers['Cookie'] = r.getheader('set-cookie') |
| 67 | + r.fp = None # remove the reference to the socket, so that it can not be closed by the response object (we want to keep the socket open) |
| 68 | + auth_header_value = r.getheader(auth_header_field, None) |
| 69 | + (ServerChallenge, NegotiateFlags) = ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value[5:]) |
| 70 | + user_parts = user.split('\\', 1) |
| 71 | + DomainName = user_parts[0].upper() |
| 72 | + UserName = user_parts[1] |
| 73 | + auth = 'NTLM %s' % ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, UserName, DomainName, pw, NegotiateFlags) |
| 74 | + headers[self.auth_header] = auth |
| 75 | + headers["Connection"] = "Close" |
| 76 | + headers = dict((name.title(), val) for name, val in headers.items()) |
| 77 | + try: |
| 78 | + h.request(req.get_method(), req.get_selector(), req.data, headers) |
| 79 | + # none of the configured handlers are triggered, for example redirect-responses are not handled! |
| 80 | + response = h.getresponse() |
| 81 | + def notimplemented(): |
| 82 | + raise NotImplementedError |
| 83 | + response.readline = notimplemented |
| 84 | + infourl = addinfourl(response, response.msg, req.get_full_url()) |
| 85 | + infourl.code = response.status |
| 86 | + infourl.msg = response.reason |
| 87 | + return infourl |
| 88 | + except socket.error, err: |
| 89 | + raise urllib2.URLError(err) |
| 90 | + else: |
| 91 | + return None |
| 92 | + |
| 93 | + |
| 94 | +class HTTPNtlmAuthHandler(AbstractNtlmAuthHandler, urllib2.BaseHandler): |
| 95 | + |
| 96 | + auth_header = 'Authorization' |
| 97 | + |
| 98 | + def http_error_401(self, req, fp, code, msg, headers): |
| 99 | + return self.http_error_authentication_required('www-authenticate', req, fp, headers) |
| 100 | + |
| 101 | + |
| 102 | +class ProxyNtlmAuthHandler(AbstractNtlmAuthHandler, urllib2.BaseHandler): |
| 103 | + """ |
| 104 | + CAUTION: this class has NOT been tested at all!!! |
| 105 | + use at your own risk |
| 106 | + """ |
| 107 | + auth_header = 'Proxy-authorization' |
| 108 | + |
| 109 | + def http_error_407(self, req, fp, code, msg, headers): |
| 110 | + return self.http_error_authentication_required('proxy-authenticate', req, fp, headers) |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + url = "http://ntlmprotectedserver/securedfile.html" |
| 115 | + user = u'DOMAIN\\User' |
| 116 | + password = 'Password' |
| 117 | + |
| 118 | + passman = urllib2.HTTPPasswordMgrWithDefaultRealm() |
| 119 | + passman.add_password(None, url, user , password) |
| 120 | + auth_basic = urllib2.HTTPBasicAuthHandler(passman) |
| 121 | + auth_digest = urllib2.HTTPDigestAuthHandler(passman) |
| 122 | + auth_NTLM = HTTPNtlmAuthHandler(passman) |
| 123 | + |
| 124 | + # disable proxies (just for testing) |
| 125 | + proxy_handler = urllib2.ProxyHandler({}) |
| 126 | + |
| 127 | + opener = urllib2.build_opener(proxy_handler, auth_NTLM) #, auth_digest, auth_basic) |
| 128 | + |
| 129 | + urllib2.install_opener(opener) |
| 130 | + |
| 131 | + response = urllib2.urlopen(url) |
| 132 | + print(response.read()) |
| 133 | + |
0 commit comments