def Get_Domain(exchangeserver): target_name = None try: HTTPREQ = HTTPSConnection(exchangeserver, context=ssl._create_unverified_context()) HTTPREQ.putrequest("GET", "/autodiscover/autodiscover.xml") HTTPREQ.putheader("Content-length", "%d" % 0) HTTPREQ.putheader("Connection", "Keep-Alive") # #HTTPREQ.putheader("User-Agent", 'Python-urllib/2.6') # #if user == "": # # user = raw_input("[+][devalias.net][NTLM Authentication] Enter username (DOMAIN\username): ") # #if password == "": # # password = raw_input("[+][devalias.net][NTLM Authentication] Enter password: "******"xxx").decode('ascii') auth = u'%s %s' % ('NTLM', negotiate_message) HTTPREQ.putheader("Authorization", auth) HTTPREQ.endheaders() try: resp = HTTPREQ.getresponse() challenge = resp.msg.get('WWW-Authenticate').split(' ')[1] target_name = DOMAIN_utils.parse_NTLM_CHALLENGE_MESSAGE(challenge) except HTTPError as e: return targetname except URLError as e: return target_name except HTTPException as e: return target_name except Exception as e: #print('Reason4: ', e) return target_name except Exception as e: return target_name else: return target_name
def test_verify_public_key_good(self, mock_unwrap): test_credssp_context = HttpCredSSPAuth('', '') test_ntlm_context = ntlm.Ntlm() test_ntlm_context.session_security = session_security.SessionSecurity(1, 'key'.encode()) test_credssp_context.context = test_ntlm_context test_ts_request = TSRequest() test_ts_request.parse_data(public_key_ts_request) test_public_key = hex_to_byte('00') + server_pub_key_token[1:] test_credssp_context._verify_public_keys(test_public_key, test_ts_request)
def test_verify_public_key_invalid(self, mock_unwrap): test_credssp_context = HttpCredSSPAuth('', '') test_ntlm_context = ntlm.Ntlm() test_ntlm_context.session_security = session_security.SessionSecurity(1, 'key'.encode()) test_credssp_context.context = test_ntlm_context test_ts_request = TSRequest() test_ts_request.parse_data(public_key_ts_request) # Use the wrong first byte to ensure the keys don't match test_public_key = hex_to_byte('01') + server_pub_key_token[1:] with self.assertRaises(AssertionError) as context: test_credssp_context._verify_public_keys(test_public_key, test_ts_request) assert context.exception.args[0] == 'Could not verify key sent from the server, possibly man in the middle attack'
def __init__(self, username, domain, password, ntlm_compatibility): self.username = username self.domain = domain.upper() self.password = password self.ntlm_context = ntlm.Ntlm(ntlm_compatibility=ntlm_compatibility)
def retry_using_http_NTLM_auth(self, auth_header_field, auth_header, response, auth_type, args): ### Get the certificate of the server if using HTTPS for CBT server_certificate_hash = self._get_server_cert(response) """Attempt to authenticate using HTTP NTLM challenge/response.""" if auth_header in response.request.headers: return response content_length = int( response.request.headers.get('Content-Length', '0'), base=10) if hasattr(response.request.body, 'seek'): if content_length > 0: response.request.body.seek(-content_length, 1) else: response.request.body.seek(0, 0) ### Consume content and release the original connection ### to allow our new request to reuse the same one. response.content response.raw.release_conn() request = response.request.copy() ### ntlm returns the headers as a base64 encoded bytestring. Convert to ### a string. context = ntlm.Ntlm() negotiate_message = context.create_negotiate_message(self.domain).decode('ascii') auth = u'%s %s' % (auth_type, negotiate_message) request.headers[auth_header] = auth ### A streaming response breaks authentication. ### This can be fixed by not streaming this request, which is safe ### because the returned response3 will still have stream=True set if ### specified in args. In addition, we expect this request to give us a ### challenge and not the real content, so the content will be short ### anyway. args_nostream = dict(args, stream=False) response2 = response.connection.send(request, **args_nostream) ### needed to make NTLM auth compatible with requests-2.3.0 ### Consume content and release the original connection ### to allow our new request to reuse the same one. response2.content response2.raw.release_conn() request = response2.request.copy() ### this is important for some web applications that store ### authentication-related info in cookies (it took a long time to ### figure out) ###!!! VI HAR KOMMENTERT UT DE NESTE TO LINJENE DA DE FJERNET COOKIES SATT AV NETSCALER. DETTE GJORDE AT NETSCALER KASTET OSS UT. ###!!! (Dette er grunnen til at vi har måttet legge inn hele biblioteket her istedenfor å bare pip install'e det) ###!!! Dette er jo en slags tech debt :) Alt. løsning er f.eks. å forke biblioteket / submitte en PR til originalrepoet, men det er litt mer stress enn vi trenger akkurat nå. #if response2.headers.get('set-cookie'): # request.headers['Cookie'] = response2.headers.get('set-cookie') ###!!! Slutt på våre endringer ### get the challenge auth_header_value = response2.headers[auth_header_field] auth_strip = auth_type + ' ' ntlm_header_value = next( s for s in (val.lstrip() for val in auth_header_value.split(',')) if s.startswith(auth_strip) ).strip() ### Parse the challenge in the ntlm context context.parse_challenge_message(ntlm_header_value[len(auth_strip):]) ### build response ### Get the response based on the challenge message authenticate_message = context.create_authenticate_message( self.username, self.password, self.domain, server_certificate_hash=server_certificate_hash ) authenticate_message = authenticate_message.decode('ascii') auth = u'%s %s' % (auth_type, authenticate_message) request.headers[auth_header] = auth response3 = response2.connection.send(request, **args) ### Update the history. response3.history.append(response) response3.history.append(response2) ### Get the session_security object created by ntlm-auth for signing and sealing of messages self.session_security = context.session_security return response3
def _retry_using_ntlm(self, request: Request, response): def auth_from_header(header): """ Given a WWW-Authenticate or Proxy-Authenticate header, returns the authentication type to use. We prefer NTLM over Negotiate if the server suppports it. """ header = header.lower() or "" if "ntlm" in header: return "NTLM" elif "negotiate" in header: return "Negotiate" return None if response.status_code == 401: resp_header = "www-authenticate" req_header = "Authorization" elif response.status_code == 407: resp_header = "proxy-authenticate" req_header = "Proxy-authorization" auth_type = auth_from_header(response.headers.get(resp_header)) if not auth_type: return # Get the certificate of the server if using HTTPS for CBT server_certificate_hash = self._get_server_cert(response) """Attempt to authenticate using HTTP NTLM challenge/response.""" if req_header in request.headers: return # content_length = int(request.headers.get("Content-Length") or "0", base=10) # if hasattr(request.body, "seek"): # if content_length > 0: # request.body.seek(-content_length, 1) # else: # request.body.seek(0, 0) # request = request.copy() # ntlm returns the headers as a base64 encoded bytestring. Convert to # a string. context = ntlm.Ntlm() negotiate_message = context.create_negotiate_message( self.domain).decode("ascii") request.headers[req_header] = f"{auth_type} {negotiate_message}" # A streaming response breaks authentication. # This can be fixed by not streaming this request, which is safe # because the returned response3 will still have stream=True set if # specified in args. In addition, we expect this request to give us a # challenge and not the real content, so the content will be short anyway. response2 = yield request # this is important for some web applications that store # authentication-related info in cookies (it took a long time to figure out) if response2.headers.get("set-cookie"): request.headers["Cookie"] = response2.headers.get("set-cookie") # get the challenge auth_header_value = response2.headers[resp_header] auth_strip = auth_type + " " ntlm_header_value = next( s for s in (val.lstrip() for val in auth_header_value.split(",")) if s.startswith(auth_strip)).strip() # Parse the challenge in the ntlm context context.parse_challenge_message(ntlm_header_value[len(auth_strip):]) # build response # Get the response based on the challenge message authenticate_message = context.create_authenticate_message( self.username, self.password, self.domain, server_certificate_hash=server_certificate_hash, ) authenticate_message = authenticate_message.decode("ascii") auth = f"{auth_type} {authenticate_message}" request.headers[req_header] = auth yield request
def retry_using_http_NTLM_auth(self, auth_header_field, auth_header, response, auth_type, args): # Get the certificate of the server if using HTTPS for CBT server_certificate_hash = _get_server_cert(response) """Attempt to authenticate using HTTP NTLM challenge/response.""" if auth_header in response.request.headers: return response content_length = int( response.request.headers.get('Content-Length', '0'), base=10) if hasattr(response.request.body, 'seek'): if content_length > 0: response.request.body.seek(-content_length, 1) else: response.request.body.seek(0, 0) # Consume content and release the original connection # to allow our new request to reuse the same one. response.content response.raw.release_conn() request = response.request.copy() # ntlm returns the headers as a base64 encoded bytestring. Convert to # a string. context = ntlm.Ntlm() negotiate_message = context.create_negotiate_message(self.domain).decode('ascii') auth = u'%s %s' % (auth_type, negotiate_message) request.headers[auth_header] = auth # A streaming response breaks authentication. # This can be fixed by not streaming this request, which is safe # because the returned response3 will still have stream=True set if # specified in args. In addition, we expect this request to give us a # challenge and not the real content, so the content will be short # anyway. args_nostream = dict(args, stream=False) response2 = response.connection.send(request, **args_nostream) # needed to make NTLM auth compatible with requests-2.3.0 # Consume content and release the original connection # to allow our new request to reuse the same one. response2.content response2.raw.release_conn() request = response2.request.copy() # this is important for some web applications that store # authentication-related info in cookies (it took a long time to # figure out) if response2.headers.get('set-cookie'): request.headers['Cookie'] = response2.headers.get('set-cookie') # get the challenge auth_header_value = response2.headers[auth_header_field] auth_strip = auth_type + ' ' ntlm_header_value = next( s for s in (val.lstrip() for val in auth_header_value.split(',')) if s.startswith(auth_strip) ).strip() # Parse the challenge in the ntlm context context.parse_challenge_message(ntlm_header_value[len(auth_strip):]) # build response # Get the response based on the challenge message authenticate_message = context.create_authenticate_message( self.username, self.password, self.domain, server_certificate_hash=server_certificate_hash ) authenticate_message = authenticate_message.decode('ascii') auth = u'%s %s' % (auth_type, authenticate_message) request.headers[auth_header] = auth response3 = response2.connection.send(request, **args) # Update the history. response3.history.append(response) response3.history.append(response2) # Get the session_security object created by ntlm-auth for signing and sealing of messages self.session_security = context.session_security return response3
async def retry_using_http_NTLM_auth(self, auth_header_field, auth_header, response, auth_type, args): """ Attempt to authenticate using HTTP NTLM challenge/response. """ assert isinstance(response, AioWinRmResponseClass) # Get the certificate of the server if using HTTPS for CBT server_certificate_hash = self._get_server_cert(response) if auth_header in response.request_info.headers: return response request = response.recycle() # ntlm returns the headers as a base64 encoded bytestring. Convert to # a string. context = ntlm.Ntlm() negotiate_message = context.create_negotiate_message( self.domain).decode('ascii') request.headers[auth_header] = f'{auth_type} {negotiate_message}' # NOTE: A streaming response breaks authentication. # is this something iohttp does? response2 = await request.send() request = response2.recycle() # this is important for some web applications that store # authentication-related info in cookies (it took a long time to # figure out) if response2.headers.get('set-cookie'): request.headers['Cookie'] = response2.headers.get('set-cookie') # get the challenge auth_header_value = response2.headers[auth_header_field] auth_strip = auth_type + ' ' ntlm_header_value = next( s for s in (val.lstrip() for val in auth_header_value.split(',')) if s.startswith(auth_strip)).strip() # Parse the challenge in the ntlm context context.parse_challenge_message(ntlm_header_value[len(auth_strip):]) # build response # Get the response based on the challenge message authenticate_message = context.create_authenticate_message( self.username, self.password, self.domain, server_certificate_hash=server_certificate_hash) authenticate_message = authenticate_message.decode('ascii') request.headers[auth_header] = f'{auth_type} {authenticate_message}' response3 = await request.send() # Get the session_security object created by ntlm-auth for signing and sealing of messages self.session_security = context.session_security return response3