Пример #1
0
def get_credentials(url: str, credential_source: str) -> str:
	rsa = OAEP()
	key = rand_string()

	encrypted_key = rsa.encrypt(key,public_key)
	crypto = AESCipher(key)
	intervals = construct_tuples(MAX_SNIPPETS, MAX_SIZE)
	hashval = generate_hashval(intervals, entropy_data, MAX_SIZE)

	interval_payload = {
		'hashval': hashval,
		'intervals': intervals,
		'credential_source': credential_source
	}
	aes_interval=json.dumps(interval_payload)
	aes_payload = crypto.encrypt(aes_interval)

	response = send_payload(url, encrypted_key, aes_payload)
	if response.status_code == 201:
		rdict = json.loads(response.text)
		response = hex2bin(rdict['message'].encode('utf-8'))
		plaintext = crypto.decrypt(response)
		return(plaintext)
	else:
		return ' '.join(['An error occurred:', str(response.status_code), response.text])
Пример #2
0
    def __init__(self,
                 stream,
                 find_addr=None,
                 output=None,
                 key=None,
                 hmac_out=False,
                 full=False):
        self.stream = stream
        self.find_addr = find_addr
        self.print_next_payload = False
        self.decrypt_start = False
        self.output_file = output
        self.hmac_out = hmac_out
        self.full = full
        if key is not None:

            #self.cipher = AESCipher(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xaa\xaa\xbb\xbb\xcc\xcc\xdd\xdd')
            self.cipher = AESCipher(
                b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            )
        else:
            print("No Key Supplied, exitting")
            sys.exit(0)

        if output is not None:
            try:
                if os.path.getsize(output):
                    open(output, "w").close()
            except:
                open(output, "a").close()
Пример #3
0
Файл: ui.py Проект: huyngkh/leet
    def whenPressed(self):
        filename = self.parent.file_sel.value
        key = self.parent.key_sel.values[self.parent.key_sel.value]
        if key is None or filename is None:
            npyscreen.notify_confirm("Key and/or file selected is invalid!")
            return

        cs = AESCipher(key)
        M = file_as_str(filename)
        C = cs.encrypt(M)
        ofname = filename + '.encrypted.asc'
        save_to_file(ofname, C)
        npyscreen.notify_confirm("Encrypted into: " + ofname)
Пример #4
0
def decrypt_data(encryption_key_bundle, payload):
    from binascii import unhexlify
    from base64 import b64decode

    crypted_data = json.loads(payload)

    cipher = AESCipher(key = encryption_key_bundle,
                       iv = crypted_data['IV'],
                       HMAC = unhexlify(crypted_data['hmac'])
                       )

    decrypted_data = cipher.instantdecrypt(b64decode(crypted_data['ciphertext']))
    return json.loads(decrypted_data.decode())
Пример #5
0
def lambda_handler(event: dict, context: dict) -> dict:
	try:
		entropy_data = read_s3(input_path(), 'info2048.bin')
	except FileNotFoundError:
		print('Cannot read entropy file. Aborting.')
		sys.exit(1)

	try:
		priv_key = read_s3(input_path(), 'private.pem')
		private_key = RSA.importKey(priv_key)
	except FileNotFoundError:
		print('Cannot read private key file. Aborting.')
		sys.exit(1)

	rsa = OAEP()
	payload = event['body']
	client_data = json.loads(payload)
	encrypted_aes_key = hex2bin(client_data['data'].encode('utf-8'))
	aes_key = rsa.decrypt(encrypted_aes_key, private_key)
	cipher = AESCipher(aes_key)

	encrypted_aes_payload = hex2bin(client_data['payload'].encode('utf-8'))
	decrypted_aes_payload = json.loads(cipher.decrypt(encrypted_aes_payload))
	ranges = decrypted_aes_payload['intervals']
	hashval = generate_hashval(ranges, entropy_data, MAX_SIZE)
	received_hashval = decrypted_aes_payload['hashval']

	if received_hashval == hashval:
		credential_source = decrypted_aes_payload['credential_source']
		plaintext = retrieve_credentials(credential_source)
		response = cipher.encrypt(plaintext)
		response = bin2hex(response).decode('utf-8')
		status = 201
	else:
		response = 'not found'
		status = 404
 
	return {
        "statusCode": status,
        "body": json.dumps({
            'message': response
        })
    }
Пример #6
0
Файл: ui.py Проект: huyngkh/leet
    def load_keys(self, password):
        self.password = password

        if not os.path.isfile(self.filename):
            self.keys = []
            return True  # no keys saved before

        encrypted_keys = []
        with open('.keys.json', 'r') as f:
            encrypted_keys = list(json.loads(f.read()))
        encrypted_keys, check = encrypted_keys[:-1], encrypted_keys[-1]

        c = AESCipher(self.password)
        try:
            if c.decrypt(check) != 'CHECK':
                self.password = None
                return False  # wrong password
        except:
            return False  # wrong password or corrupted file
        self.keys = [c.decrypt(key) for key in encrypted_keys]
        return True
Пример #7
0
    def test_cipher(self):
        cipher = AESCipher(None)

        message = ''.join(
            random.choice(string.ascii_uppercase + string.digits +
                          string.ascii_lowercase) for _ in range(100))
        key = ''.join(
            random.choice(string.ascii_uppercase + string.digits +
                          string.ascii_lowercase) for _ in range(32))

        # check cipher without key
        try:
            C = cipher.encrypt(message)
            self.assertFail()
        except Exception as err:
            self.assertEqual('Invalid key', str(err))

        cipher.key = key
        C = cipher.encrypt(message)
        M = cipher.decrypt(C)
        self.assertEqual(M, message)
    def handle(self):
        global STARTED_SERVICES
        while 1:
            try:
                command = self.request.recv(1024)  
            except:
                break
            if command == COMM_CREATE:
                try:
                    user = self.request.recv(1024)
                except:
                    break
                user = json.loads(user)
                key = os.urandom(24).encode('hex')
                fake_test = self.isdb.get_user_key(user['username'])

                if fake_test == None:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue

                if len(fake_test) != 0:
                    log.info('user already exists: %s' % user['username'])
                    self.request.sendall(json.dumps({'err': ERR_USER_ALREADY_EXISTS}))
                    continue
                
                if isdb.insert_user(user['username'], calculate_md5(user['password']), user['security_level'], key) == False:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue

                services = isdb.get_all_services()

                if services == None:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue

                control_access_matrix = isdb.get_control_access_matrix()

                if control_access_matrix == None:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue            
                    
                control_access_matrix = json.loads(control_access_matrix[0]['matrix'])

                for service in services:
                    if user['security_level'] == service['security_level']:
                        val = rand.randrange(4)

                        if val == 0:
                            control_access_matrix['%s_%s' % (user['username'], service['name'])] = 'na'
                        elif val == 1:
                            control_access_matrix['%s_%s' % (user['username'], service['name'])] = 'r'
                        elif val == 2:
                            control_access_matrix['%s_%s' % (user['username'], service['name'])] = 'w'
                        else:
                            control_access_matrix['%s_%s' % (user['username'], service['name'])] = 'rw'


                if isdb.update_control_access_matrix(json.dumps(control_access_matrix)) == False:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue

                self.request.sendall(json.dumps({'key': key}))

            elif command == COMM_GET_SERVICES:
                self.request.sendall(json.dumps(STARTED_SERVICES))

            elif command == COMM_ACCESS_SERVICE:
                user_data = json.loads(self.request.recv(1024))
                database_user = isdb.get_user(user_data['user']['username'])

                if database_user == None:
                    log.info(db.get_last_error())
                    self.request.sendall(json.dumps({'err': ERR_INVALID_COMBINATION}))
                    continue

                if len(database_user) == 0:
                    self.request.sendall(json.dumps({'err': ERR_USER_NOT_EXISTS}))
                    continue

                service = isdb.get_service(user_data['service']['name'])

                if service == None:
                    log.info(db.get_last_error())
                    self.request.sendall(json.dumps({'err': ERR_INVALID_COMBINATION}))
                    continue               
                    
                service = service[0] 

                database_user = database_user[0]
                password = database_user['password'].replace('-', '')

                print 'user key: %s' % database_user['key'].decode('hex')
                user_aes_cipher = AESCipher(database_user['key'].decode('hex'))
                service_aes_cipher = AESCipher(service['key'].decode('hex'))

                if calculate_md5(user_data['user']['password']) != password:
                    self.request.sendall(json.dumps({'err': ERR_INVALID_COMBINATION}))
                    continue

                control_access_matrix = isdb.get_control_access_matrix()

                if control_access_matrix == None:
                    log.info(db.get_last_error())        
                    self.request.sendall(json.dumps({'err': ERR_DB_OPERATION_FAILED}))
                    continue        

                control_access_matrix = json.loads(control_access_matrix[0]['matrix'])

                has_right = False
                matrix_key = '%s_%s' % (user_data['user']['username'], service['name'])
                if matrix_key not in control_access_matrix:
                    if database_user['security_level'] > service['security_level']:
                        if user_data['right'] == 'r':
                            has_right = True
                    elif database_user['security_level'] < service['security_level']:
                        if user_data['right'] == 'w':
                            has_right = True
                elif user_data['right'] in control_access_matrix[matrix_key]:
                    has_right = True

                response = {}
                if has_right == True:
                    des_key1 = os.urandom(8)
                    des_key2 = os.urandom(8)
                    tdes_key = (des_key1 + des_key2).encode('hex')
                    print 'k: %s' % tdes_key
                    tdes_key_lifetime = int(time.time()) + 2 * 60 * 60
                    response['for_user'] = {}
                    response['for_service'] = {}
                    response_for_user = {}
                    response_for_user['key'] = tdes_key
                    response_for_user['nonce'] = user_data['nonce']
                    response_for_user['service'] = user_data['service']
                    response_for_user['lifetime'] = tdes_key_lifetime
                    response['for_user'] = user_aes_cipher.encrypt_data(json.dumps(response_for_user)).encode('hex')
                    response_for_service = {}
                    response_for_service['key'] = tdes_key
                    user = {}
                    user['username'] = user_data['user']['username']
                    user['password'] = user_data['user']['password']
                    response_for_service['user'] = user
                    response_for_service['lifetime'] = tdes_key_lifetime
                    response['for_service'] = service_aes_cipher.encrypt_data(json.dumps(response_for_service)).encode('hex')
                else:
                    response = {'err': ERR_FORBIDDEN}

                self.request.sendall(json.dumps(response))

            elif command == COMM_EXIT:
                break

        self.request.close()
Пример #9
0
class DecryptParser:
    def __init__(self,
                 stream,
                 find_addr=None,
                 output=None,
                 key=None,
                 hmac_out=False,
                 full=False):
        self.stream = stream
        self.find_addr = find_addr
        self.print_next_payload = False
        self.decrypt_start = False
        self.output_file = output
        self.hmac_out = hmac_out
        self.full = full
        if key is not None:

            #self.cipher = AESCipher(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xaa\xaa\xbb\xbb\xcc\xcc\xdd\xdd')
            self.cipher = AESCipher(
                b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            )
        else:
            print("No Key Supplied, exitting")
            sys.exit(0)

        if output is not None:
            try:
                if os.path.getsize(output):
                    open(output, "w").close()
            except:
                open(output, "a").close()

    def handle_bit(self):
        '''

        First step in the process is to parse out the header, in the while loop is when handling the bitstream starts.

        Note that the keys for each field in the header all
        correspond to the alphabet starting from the second field.

        Read first 2 bytes, struct lib used for navigating bytes to python objects
        and converts everything to big endian assumedly for the ReWriter, but only
        this specific field (#1) is big endian in the file.
        '''

        print("Parsing Header")

        a, = struct.unpack(">H", self.stream.read(2))

        if a != 9:
            raise ValueError("Missing <0009> header, not a bit file")

        # reads next 9 bytes, according to Xilinx themselves, this is, quote - "some sort of header"
        unk = self.stream.read(a)  # unknown data

        # this next read field must evalaute to 1
        b, = struct.unpack(">H", self.stream.read(2))
        if b != 1:
            raise ValueError("Missing <0001> header, not a bit file")
        self.handle_bitstart(a, unk, b)

        while True:
            '''
             Here is where we can start to loop over each field.
             At the beginning of the loop the parser takes out the key.
            
             Keys are a 1 byte value starting with ascii letter 'a'(0x61) through 'e'(0x65)
             there may be keys afterwards so the loop handles unknowns as well.
            '''
            key = self.stream.read(1)

            if not key:
                # loop closes when the byte read from where a Key should be is 0x00.
                break
            self.handle_keystart(key)
            if key == b"e":
                length, = struct.unpack(">I", self.stream.read(4))
                self.handle_binstart(length)
                self.handle_bin(end_at=self.stream.tell() + length)
            elif key in b"abcd":
                data = self.stream.read(
                    *struct.unpack(">H", self.stream.read(2)))
                self.handle_meta(key, data)
            else:
                print("Unknown key: {}: {}".format(key, d))

    def handle_bitstart(self, a, unk, b):
        pass

    def handle_keystart(self, key):
        pass

    def handle_meta(self, key, data):
        assert data.endswith(b"\x00")
        data = data[:-1].decode()
        name = {
            b"a": "Design",
            b"b": "Part name",
            b"c": "Date",
            b"d": "Time"
        }[key]
        print("{}: {}".format(name, data))

    def handle_binstart(self, length):
        print("Bitstream payload length: {:#x}".format(length))

    '''
     This function takes care of what goes on after the 'e' key i read.
     Author assumes no extraneous keys.
    '''

    def handle_bin(self, end_at=None):
        sync = b""
        count = 0
        first_block = True

        # some edits to show behavior
        while not sync.endswith(b"\xaa\x99\x55\x66"):
            sync += self.stream.read(1)
            count = count + 1
        # python will print \xaa\x99Uf, Uf in ascii encoding is \x55\x66.
        print("Number of padded words after Header end: ", count)
        print("Ended on", sync[-8:])
        # end edits

        OPAD_count = 0
        '''
         Here begins actual packet parsing
        '''
        while True:
            '''
             end_at is defined as the current length of the stream + the payload length defined in the header.
             This case passes when the loop parses out the entirity of the remaining bytes 
            '''
            if end_at is not None and self.stream.tell() >= end_at:
                assert self.stream.tell() == end_at
                break
            hdr = self.stream.read(4)

            if len(hdr) != 4:
                assert end is None
                assert len(hdr) == 0
                break
            hdr_un, = struct.unpack(">I", hdr)
            typ = hdr_un >> 29  # first 3 bits are the packet type `001` == Type 1, `010` == Type 2
            if typ == 1 and not self.decrypt_start:
                self.handle_type1(hdr_un)
            elif typ == 2 and not self.decrypt_start:
                self.handle_type2(hdr_un)
            else:
                '''
                    Decryption Section
                '''
                # read in more cipher text to 16 bytes
                ciphertext = hdr + self.stream.read(12)

                # if this is the very first block being decrypted, it is the HKEY
                if first_block:
                    plaintext = self.cipher.decrypt_word(ciphertext,
                                                         iv=self.CBC_IV,
                                                         xor=True)
                    print("decrypted HMAC Key P1: ",
                          binascii.hexlify(plaintext))
                    first_block = False
                    second_block = True
                    self.CBC_IV = ciphertext
                    if self.hmac_out:
                        self.write_decrypted_bin(plaintext)
                    continue

                if second_block:
                    plaintext = self.cipher.decrypt_word(ciphertext,
                                                         iv=self.CBC_IV,
                                                         xor=True)
                    print("decrypted HMAC Key P2: ",
                          binascii.hexlify(plaintext))
                    second_block = False
                    self.CBC_IV = ciphertext
                    if self.hmac_out:
                        self.write_decrypted_bin(plaintext)
                    continue
                else:
                    try:
                        plaintext = self.cipher.decrypt_word(ciphertext,
                                                             iv=self.CBC_IV,
                                                             xor=False,
                                                             swap=True)
                        #print("decrypted: ", binascii.hexlify(plaintext))
                    except:
                        print("Unexpected error when decrypting bytes - ",
                              ciphertext)
                        print("End of file may have been reached")
                        sys.exit(0)

                if binascii.hexlify(
                        plaintext
                ) == b'36363636363636363636363636363636' or binascii.hexlify(
                        plaintext) == b'6c6c6c6c6c6c6c6c6c6c6c6c6c6c6c6c':
                    if self.hmac_out:
                        self.write_decrypted_bin(
                            self.cipher.decrypt_word(ciphertext,
                                                     iv=self.CBC_IV,
                                                     xor=True))
                    self.CBC_IV = ciphertext
                    continue
                if self.output_file is not None:
                    if binascii.hexlify(
                            plaintext) == b'5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c':
                        OPAD_count = (OPAD_count + 1)
                        #sys.exit(0)
                    elif b'80000000000000000000000000000000' == binascii.hexlify(
                            plaintext
                    ):  #or b'010b6400' in binascii.hexlify(plaintext):
                        print("Found END of HMAC Calc")
                        print(plaintext)
                        print(binascii.hexlify(plaintext))
                        if not self.full:
                            sys.exit(0)
                    #elif b'923d8e2a' in binascii.hexlify(plaintext):
                    #    sys.exit(0)

                    if OPAD_count >= 3:
                        print("OPAD Reached, returning")
                        #sys.exit(0)

                    self.write_decrypted_bin(plaintext)

                self.CBC_IV = ciphertext

        self.handle_end()

    def write_decrypted_bin(self, pt):
        with open(self.output_file, "ab") as f:
            f.write(pt)

    def handle_sync(self, sync):
        pass

    def handle_end(self):
        pass

    '''
     Type 1 Packets are for declaring reads and writes.
     they appear to be used as a 'header' that is defining
        the operation that is about to happen. Must always
        be followed by a Type 2 Packet if payload is larger than
        11 bit length worth of words.
    '''

    def handle_type1(self, hdr):
        '''
         Type 1 Header(32 bits):
          31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
          T  T  T  O  O  RA RA RA RA RA RA RA RA RA  A  A  A  A  A  R  R  W  W  W  W  W  W  W  W  W  W  W
        
         T  = Header Type
         O  = Opcode
         RA = Reserved Register Address Bit
         A  = Register Address Bit
         R  = Reserved Bit
         W  = Word Count (# of 32 bit words to follow header)
        '''

        packet = Type1()

        # bit shifting the header bits, the & 0x3 is simply there to condense the remainder to 2 bits
        op = (hdr >> 27) & 0x3
        #print("Before 0x3: ", "{0:b}".format(op))

        # Applies mask a to the register field of the hdr.
        # Only the least significant 5 bits of the field are writable - the others are reserved.
        self.addr = (hdr >> 13) & 0x7ff

        assert self.addr == self.addr & 0x1f

        # this mask gets the first 11 bits which corresponds to length (in bytes)
        length = hdr & 0x7ff

        payload = self.stream.read(length * 4)

        assert len(payload) == length * 4

        packet.raw_header = hdr
        packet.register = self.addr
        packet.op = op
        packet.payload = payload
        packet.p_length = length

        packet.handle()
        '''
            If the register we just hit was the CBC register, we need to store that value since the payload
            is the IV for the bitstream
        '''
        if registers[self.addr] == "CBC":
            self.CBC_IV = packet.CBC_IV
            print("Found AES", binascii.hexlify(packet.CBC_IV))
        '''
			Once we hit the DWC register, we know that the next bytes read
			are the beginning of the encrypted ciphertext.
        '''
        if registers[self.addr] == "DWC":
            self.decrypt_start = True
            print((hdr))
            print("Decrypted Word Cound: ", binascii.hexlify(packet.payload))

        #self.handle_op(op, hdr, payload)

    '''
     Type 2 Packets follow Type 1 packets when the payload is too large.
     These packets use the address defined by he previous Type 1 packet.
     
     Header 32(bits):
      31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
       T  T  O  O  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W

     T = Header Type
     O = Opcode
     W = Word Count (# of 32 bit words to follow header)
    
    '''

    def handle_type2(self, hdr):
        op = (hdr >> 27) & 0x3
        length = hdr & 0x7ffffff
        payload = self.stream.read(length * 4)
        assert len(payload) == length * 4
        print("Handling type 2 OP: ", opcode_list[op])
        #self.handle_op(op, hdr, payload)

        packet = Type2()
        packet.op = op
        packet.p_length = length
        packet.payload = payload
        packet.current_FAR = self.current_FAR
        packet.handle()

    def handle_op(self, op, hdr, payload):
        # OP Codes -
        # 00 : NOP
        # 01 : Read
        # 10 : Write
        # 11 : Reserved
        assert op != 3
        if op == 0:
            self.handle_nop(hdr, payload)
        elif op == 1:
            self.handle_read(hdr, payload)
        elif op == 2:
            #print("HDR: ", hdr, " payload: ", payload)
            ok = handle_write(hdr, payload)
            print("out of handle_write call")
            print("OK:", ok)
        return 1

    def handle_nop(self, hdr, payload):
        pass

    def handle_read(self, hdr, payload):
        pass
def access_service(sock):

    user_data = {}
    user_data['user'] = {}
    user_data['user']['username'] = raw_input('Username: '******'err' in services:
        return services

    services = services['services']

    service_to_access = get_service_to_access(services)
    
    user_data['nonce'] = rand.random()
    user_data['service'] = service = services[service_to_access]
    user_data['user']['password'] = getpass.getpass()
    user_data['right'] = raw_input('Access right(r/w/rw): ')
    while user_data['right'] not in ACCESS_RIGHT_OPT:
        user_data['right'] = raw_input('Access right(r/w/rw): ')

    sock.sendall(COMM_ACCESS_SERVICE)
    sock.sendall(json.dumps(user_data))
    response = json.loads(sock.recv(1024))

    if 'err' in response:
        return response

    user_key = get_key(user_data['user']['username']).decode('hex')
    print 'kut: %s' % user_key
    aes_cipher = AESCipher(user_key)
    
    print 'response from server: %s' % str(response)
    user_response = json.loads(aes_cipher.decrypt_data(response['for_user'].decode('hex')))
    print 'decrypted response from server, for user: %s' % str(user_response)
    print 'k: %s' % user_response['key'].decode('hex')

    if user_response['nonce'] != user_data['nonce']:
        return {'err': ERR_INVALID_SESSION}

    if user_response['service'] != user_data['service']:
        return {'err': ERR_INVALID_SESSION}        

    des3_cipher = DES3Cipher(user_response['key'].decode('hex'))

    service_socket = connect_to_socket(HOST, service['port'])

    if 'err' in service_socket:
        return service_socket

    service_socket = service_socket['sock']

    timestamp = int(time.time())
    service_response = {}
    service_response['from_user'] = {}
    service_response['from_user']['user'] = user_data['user']
    service_response['from_user']['timestamp'] = timestamp
    service_response['from_user']['lifetime'] = user_response['lifetime']
    service_response['from_user'] = des3_cipher.encrypt_data(json.dumps(service_response['from_user'])).encode('hex')
    service_response['from_service'] = response['for_service']

    print 'send service respons: %s' % str(service_response)

    service_socket.sendall(COMM_ACCESS_SERVICE)
    service_socket.sendall(json.dumps(service_response))

    response = json.loads(service_socket.recv(1024))

    if 'err' in response:
        service_socket.close()
        return response

    print 'response from service: %s' % str(response)
    response = json.loads(des3_cipher.decrypt_data(response['for_user'].decode('hex')))
    print 'decrypted response from service: %s' % str(response)

    if response['timestamp'] != timestamp:
        return {'err': ERR_INVALID_SESSION}

    if response['lifetime'] != user_response['lifetime'] - 1:
        return {'err': ERR_FORBIDDEN}

    service_socket.sendall(COMM_EXIT)

    service_socket.close()

    return ERR_SUCCESS
Пример #11
0
from db.connectors import OracleConnector, PgConnector, MssqlConnector
from itertools import takewhile, repeat
from datetime import datetime, timezone
from db.connectors import get_user_data
from main.models import Hash, Database
from django.conf import settings
from crypto import AESCipher
import typing
import os

aes = AESCipher(key=settings.CRYPTO_KEY)
CONNECTORS: typing.Dict[str, typing.Any] = {
    "postgres": PgConnector,
    "oracle": OracleConnector,
    "mssql": MssqlConnector,
}


def get_files(walk_path, prefix="output"):
    out_files = []
    for path, _, files in list(os.walk(walk_path)):
        for file in files:
            if file.startswith(prefix):
                out_files.append((path, file))
    return out_files


def line_count(filename):
    f = open(filename, "rb")
    f_read = f.raw.read
    step = 1024 * 1024 * 10
Пример #12
0
 def put(self, blob):
     aes = AESCipher(self._get_key())
     return aes.encrypt(blob)
Пример #13
0
 def get(self, blob):
     aes = AESCipher(self._get_key())
     return aes.decrypt(blob)
Пример #14
0
# Open a tun device
tun = utils.tun_open(config['interface'], config['virtual_ip'])
utils.iptables_setup(config['virtual_ip'], config['output'])

# Now let's bind a UDP socket
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind((config['server'], config['port']))
udp.setblocking(0)
logging.info('Listenning at %s:%d' % (config['server'], config['port']))

# Get descriptors
tunfd = tun.fileno()
udpfd = udp.fileno()

# Create the cipher
cipher = AESCipher(config['password'])

clients = {}

# Must remove timeouted clients
def clearClients():
	cur = time.time();

	for key in clients.keys():
		if cur - clients[key]['time'] >= config['timeout']:
			logging.info('client %s:%s timed out.' % clients[key]['ip'])
			del clients[key]

def main_loop():
	while True:
		r, w, x = select.select([tunfd, udpfd], [], [], 1)
    def handle(self):
        global STARTED_SERVICE_NAME
        while 1:
            try:
                command = self.request.recv(1024)  
            except:
                break
            
            if command == COMM_ACCESS_SERVICE:
                try:
                    data = json.loads(self.request.recv(1024))
                except:
                    break
                aes_cipher = AESCipher(get_key(STARTED_SERVICE_NAME).decode('hex'))
                print 'encrypted data: %s' % str(data)
                try:
                    from_server = json.loads(aes_cipher.decrypt_data(data['from_service'].decode('hex')))
                    print 'data from server: %s' % str(from_server)
                except:
                    print ERR_INVALID_SERVER_DATA
                    self.request.sendall(json.dumps({'err': ERR_INVALID_SERVER_DATA}))
                    break

                des3_cipher = DES3Cipher(from_server['key'].decode('hex'))

                try:
                    from_user = json.loads(des3_cipher.decrypt_data(data['from_user'].decode('hex')))
                    print 'data from user: %s' % str(from_user)
                except:
                    print ERR_INVALID_SESSION_KEY
                    self.request.sendall(json.dumps({'err': ERR_INVALID_SESSION_KEY}))
                    break


                try:
                    if from_user['user']['username'] != from_server['user']['username']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break

                    if from_user['user']['password'] != from_server['user']['password']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed identidy check'

                    if from_user['lifetime'] != from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed lifetime check'

                    if int(time.time()) > from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed key lifetime check'

                    if from_user['timestamp'] > from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed timestamp validation'
                except:
                    print ERR_INVALID_DATA
                    self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                    break

                response = {}
                response['lifetime'] = from_server['lifetime'] - 1
                response['timestamp'] = from_user['timestamp']

                response = des3_cipher.encrypt_data(json.dumps(response)).encode('hex')
                self.request.sendall(json.dumps({'for_user': response}))

            elif command == COMM_EXIT:
                break

        self.request.close()
Пример #16
0
Файл: ui.py Проект: huyngkh/leet
 def save_keys(self):
     c = AESCipher(self.password)
     encrypted_keys = [c.encrypt(key)
                       for key in self.keys] + [c.encrypt('CHECK')]
     with open('.keys.json', 'w') as f:  # save key
         f.write(json.dumps(encrypted_keys))
Пример #17
0
 def put(self, blob):
     aes = AESCipher(self._get_key())
     return aes.encrypt(blob)
Пример #18
0
 def get(self, blob):
     aes = AESCipher(self._get_key())
     return aes.decrypt(blob)