def authenticate(login, password): login = login.lower() query = {"f": "pre_auth", "login": login} srp.rfc5054_enable() user = srp.User( login.encode(), None, hash_alg=srp.SHA256, ng_type=srp.NG_CUSTOM, n_hex=S2_N.encode(), g_hex=S2_G.encode(), ) _, A = user.start_authentication() query["A"] = binascii.hexlify(A).decode() result = request(query) if b"B" not in result: return result s = binascii.unhexlify(result[b"salt"]) B = binascii.unhexlify(result[b"B"]) salt2 = result[b"salt2"] user.password = ( sha256((md5((md5(password.encode()).hexdigest()).encode() + salt2 + S2_SRP_MAGIC1.encode()).hexdigest()).encode() + S2_SRP_MAGIC2.encode()).hexdigest()).encode() user.p = user.password M = user.process_challenge(s, B) del query["A"] query["f"] = "srpAuth" query["proof"] = binascii.hexlify(M).decode() result = request(query) return result
def srp_auth(login, password): import srp query = {'f': 'pre_auth', 'login': login} usr = srp.User(login, None, hash_alg=srp.SHA256, ng_type=srp.NG_CUSTOM, n_hex=s2_n, g_hex=s2_g) _, A = usr.start_authentication() query['A'] = A.encode('hex') res = request(query) if 'B' not in res: return res s = res['salt'].decode('hex') B = res['B'].decode('hex') salt2 = res['salt2'] usr.password = sha256( md5(md5(password).hexdigest() + salt2 + '[!~esTo0}').hexdigest() + 'taquzaph_?98phab&junaj=z=kuChusu').hexdigest() usr.p = usr.password M = usr.process_challenge(s, B) del (query['A']) query['f'] = 'srpAuth' query['proof'] = M.encode('hex') res = request(query) return res
def __init__(self, username, password): self.username = username self.srp_user = srp.User(username, password, srp.SHA256, srp.NG_1024) _, A = self.srp_user.start_authentication() self.A = A self.M = None self.M2 = None
def __init__(self, loop, path, packets_per_second, chunk_size, test, username, password): print("Using user:"******"Syncing path:", self.path) print() # Set fetch update interval self.fetch_intercal = 10.0 # should be ~ 30s in production self.pending_update_callback = None self.username = username self.authenticator = srp.User(username, password, hash_alg=srp.SHA256, ng_type=srp.NG_2048) _, self.seed = self.authenticator.start_authentication() self.request_id = random.getrandbits(32) self.session_id = None # start file dir observer event_handler = FileEventHandler(self.loop, self.path, self) self.observer = Observer() self.observer.schedule(event_handler, self.path, recursive=False) self.observer.start()
async def handle_authenticate(self, dg): # Credentials if not dg.recipient: await self.do_error(constants.ERR_CREDENTIALS) return else: name = dg.recipient # HMAC hmac = self.generate_HMAC(name.encode(), self._hmac_key) await self.send_response(base64.b85encode(hmac).decode()) response = await self.recv() if not response or response.data is not True: await self.do_error(constants.ERR_HMAC) return # Challenge user = srp.User(name.encode(), self._challenge_key) username, auth = user.start_authentication() await self.send_response(auth.hex()) response = await self.recv() if response and response.data: s, B = map(bytes.fromhex, response.data) M = user.process_challenge(s, B) if M is None: await self.do_error(constants.ERR_CHALLENGE) return else: await self.send_response(M.hex()) else: await self.do_error(constants.ERR_CHALLENGE) return # Verification response = await self.recv() if response and response.data: HAMK = bytes.fromhex(response.data) user.verify_session(HAMK) # Generate new hash based off of the session key self.counter_cipher = user.get_session_key() if user.authenticated(): self.name = name else: await self.do_error(constants.ERR_VERIFICATION) return else: await self.do_error(constants.ERR_VERIFICATION) return
def login(self): usr = srp.User(self.username, self.password) response = self.session.get(f'http://{self.ip}:{self.port}{Rio.LOGIN_ENDPOINT}?username={self.username}') if response.status_code == 200: pass elif response.status_code == 403: server_params = response.headers.get('X-NI-AUTH-PARAMS') print(server_params) server_info = self.decode_server_params(server_params) modulus = server_info['modulus'] generator = server_info['generator'] salt = server_info['salt'] server_public_key = server_info['serverPublicKey'] Rio.generate_pub_key_and_proof(modulus, generator, salt, server_public_key, self.username, self.password)
def authenticate(db, client, password): usr = srp.User(client, password) uname, A = usr.start_authentication() s, B = db.authenticate1(uname, A) M = usr.process_challenge(s, B) if M is None: raise TardisDB.AuthenticationFailed() HAMK = db.authenticate2(M) usr.verify_session(HAMK) if not usr.authenticated(): raise TardisDB.AuthenticationFailed()
def login(baseurl, username, password): sess = requests.Session() # Load auth page to get CSRF token token = sess.get(baseurl + "login.lp?action=getcsrf").text # Calculate SRP variables srp_user = srp.User(user, passwd, hash_alg=srp.SHA256, ng_type=srp.NG_2048) if hasattr(srp._mod, "BN_hex2bn"): # _mod == _ctsrp, openssl srp._mod.BN_hex2bn( srp_user.k, b"05b9e8ef059c6b32ea59fc1d322d37f04aa30bae5aa9003b8321e21ddb04e300", ) else: # _mod == _pysrp, pure python srp_user.k = int( "05b9e8ef059c6b32ea59fc1d322d37f04aa30bae5aa9003b8321e21ddb04e300", 16) I, A = srp_user.start_authentication() A = binascii.hexlify(A) req_data = {"I": I, "A": A, "CSRFtoken": token} # First stage auth request authURL = baseurl + "authenticate" response = sess.post(authURL, data=req_data) # Parse response and process challenge j = response.json() s, B = j["s"], j["B"] s = binascii.unhexlify(s) B = binascii.unhexlify(B) M = srp_user.process_challenge(s, B) M = binascii.hexlify(M) req_data = {"M": M, "CSRFtoken": token} # Second stage auth request response = sess.post(authURL, data=req_data) j = response.json() if "error" in j: print("Authentication error. Wrong password? (%s)" % j["error"]) sys.exit() return sess
def login(username, password): usr = srp.User(username, password) uname, A = usr.start_authentication() result = {} result['username'] = username result['clientChallenge'] = binascii.hexlify(A).decode('utf-8') print(result) salt = input("Ender salt: ") print(salt) server_challenge = input("Server challenge: ") print(server_challenge) M = usr.process_challenge(base64.b64decode(salt), binascii.unhexlify(server_challenge)) result = {} result['clientProof'] = binascii.hexlify(M).decode('utf-8') print(result)
#!/usr/bin/env python2 import srp # The salt and verifier returned from srp.create_salted_verification_key() should be # stored on the server. salt, vkey = srp.create_salted_verification_key('testuser', 'testpassword') class AuthenticationFailed(Exception): pass # ~~~ Begin Authentication ~~~ usr = srp.User('testuser', 'testpassword') uname, A = usr.start_authentication() # The authentication process can fail at each step from this # point on. To comply with the SRP protocol, the authentication # process should be aborted on the first failure. # Client => Server: username, A svr = srp.Verifier(uname, salt, vkey, A) s, B = svr.get_challenge() if s is None or B is None: raise AuthenticationFailed() # Server => Client: s, B M = usr.process_challenge(s, B)
def connect(self): """ Authenticates with the modem. Returns a session on success or throws an exception """ import requests session = requests.Session() ### Fetch CSRF csrf_url = '%s/login.lp?action=getcsrf' % self.top_url csrf = session.get(csrf_url).text if len(csrf) != 64: #D("csrf %s", csrf) raise Exception("Bad csrf response") #D("csrf: %s" % csrf) ### Perform SRP srp_user = srp.User(self.config['username'], self.config['password'], hash_alg=srp.SHA256, ng_type=srp.NG_2048) # Bit of a bodge. Seems the router uses a custom k value? Thanks to nbntest if hasattr(srp._mod, 'BN_hex2bn'): # _mod == _ctsrp, openssl srp._mod.BN_hex2bn( srp_user.k, b'05b9e8ef059c6b32ea59fc1d322d37f04aa30bae5aa9003b8321e21ddb04e300' ) else: # _mod == _pysrp, pure python srp_user.k = int( '05b9e8ef059c6b32ea59fc1d322d37f04aa30bae5aa9003b8321e21ddb04e300', 16) I, A = srp_user.start_authentication() A = binascii.hexlify(A) #D("A: %d %s" % (len(A), A)) auth_url = '%s/authenticate' % self.top_url req_data = {'I': I, 'A': A, 'CSRFtoken': csrf} ### Send the first SRP request auth1 = session.post(auth_url, data=req_data) if auth1.status_code != 200: #D(auth1.text) raise Exception("Error authenticating %d" % auth1.status_code) j = auth1.json() s, B = j['s'], j['B'] #D("s: %d %s" % (len(s), s)) #D("B: %d %s" % (len(B), B)) s = binascii.unhexlify(s) B = binascii.unhexlify(B) M = srp_user.process_challenge(s, B) M = binascii.hexlify(M) #D("M: %d %s" % (len(M), M)) req_data = {'M': M, 'CSRFtoken': csrf} ### Send our reponse to the SRP challenge auth2 = session.post(auth_url, data=req_data) if auth2.status_code != 200: #D(auth2.text) raise Exception("Didn't connect, error %d" % auth2.status_code) j = auth2.json() if 'error' in j: #D(j) raise Exception("Authentication error. Wrong password? (%s)" % j['error']) return session
urllib3.disable_warnings() if len (sys.argv) != 3: print ("Usage: " + sys.argv[0] + " router_url user") print ("Example:") print (sys.argv[0] + " http://192.168.1.254 admin") print (sys.argv[0] + " https://10.0.1.2:8443 admin") exit() password = getpass() router = sys.argv[1] username = sys.argv[2] print ("[*] Init SRP authentication") # Technicolor TG389ac expects only SHA256 and uses broken SRP implementation usr = srp.User(username, password, srp.SHA256) usr.k = int("05b9e8ef059c6b32ea59fc1d322d37f04aa30bae5aa9003b8321e21ddb04e300", 16) uname, A = usr.start_authentication() Ahex = binascii.b2a_hex(A).decode("utf-8") print ("[*] Get CSRF token") url = router + "/login.lp?action=getcsrf" session = requests.Session() res = session.get (url, verify=False) if res.status_code != 200: print ("[*] Error: cannot get CSRF token, status code: " + res.status_code) exit() csrf = res.content.decode("utf-8") print ("[*] Send authentication challenge") postdata = {"CSRFtoken": csrf, "I": username, "A": Ahex}
def on_frame(self, frame: str) -> None: """ Processes a frame (JSON Object) :param frame: The JSON Object to process :return: """ #logger.debug("Frame: {}".format(frame)) try: message = json.loads(frame) except: logger.exception("Could not decode the JSON message") self.transport.close() return mtype = message.get('type', None) if mtype == 'CERT_SERVER': self.cert_server = base64.b64decode(message.get('data')).encode() if mtype == 'SIGN_SERVER': self.sign_server = base64.b64decode(message.get('data')).encode() if not self.verifyServer(): return self.text_to_sign = 'eu sou quem digo ser' self._send({'type': 'SERVER_OK', 'data': self.text_to_sign}) self.getCC() c = base64.b16encode(self.cert_client).decode() self._send({'type': 'CERT_CLIENT', 'data': c}) s = base64.b16encode(self.sign_client).decode() self._send({'type': 'SIGN_CLIENT', 'data': s}) if mtype == 'START_LOGIN': self.usr = srp.User('testuser', 'testpassword') uname, A = self.usr.start_authentication() self._send({'type': 'USER', 'uname' : uname,'A':base64.b16encode(A).decode()}) if mtype =='s': self.s = base64.b64decode(message.get('data')).encode() if mtype =='B': self.B = base64.b64decode(message.get('data')).encode() M = self.usr.process_challenge(self.s, self.B) self._send({'type', 'M', 'data', base64.b64encode(M).decode()}) if mtype == 'OKOK': input = 'Salsa20_SHA256' self.algorithms = input.split('_') message = {'type': 'HELLO', 'data': input } logger.info("Hello") self._send(message) if mtype == 'PUBLIC_KEY': pem_public_key = base64.b64decode(message.get('data')) self.server_public_key = serialization.load_pem_public_key( pem_public_key, backend=default_backend() ) self.encryptkey = self.getEncriptKey() logger.info("Send key") self._send({'type': 'SECURE', 'data': base64.b64encode(self.encryptkey).decode()}) if 'AES' in self.algorithms: self.iv = os.urandom(16) if 'Salsa20' in self.algorithms: self.iv = os.urandom(24) logger.info("Send iv") self._send({'type': 'SECURE_IV', 'data': base64.b64encode(self.iv).decode()}) self.encryptFile() message = {'type': 'OPEN', 'file_name': self.file_name_encrypted} self._send(message) self.send_file(self.file_name_encrypted) if mtype == 'OK': # Server replied OK. We can advance the state if self.state == STATE_OPEN: logger.info("Channel open") self.send_file(self.file_name) elif self.state == STATE_DATA: # Got an OK during a message transfer. # Reserved for future use pass else: logger.warning("Ignoring message from server") return elif mtype == 'ERROR': logger.warning("Got error from server: {}".format(message.get('data', None))) else: logger.warning("Invalid message type") self.transport.close() self.loop.stop()