def decrypt_check(self, decrypted_U, decrypted_V): """Decrypt the Cloud init script with the passed U and V values. This method will access the received auth tag, and may fail if decoy U and V values were received. Do not call directly unless you acquire uvLock. Returns None if decryption unsuccessful, else returns the decrypted agent UUID. """ if self.auth_tag is None: return None if len(decrypted_U) != len(decrypted_V): logger.warning("Invalid U len %d or V len %d. skipping...", len(decrypted_U), len(decrypted_V)) return None candidate_key = crypto.strbitxor(decrypted_U, decrypted_V) # be very careful printing K, U, or V as they leak in logs stored on unprotected disks if config.INSECURE_DEBUG: logger.debug("U: %s", base64.b64encode(decrypted_U)) logger.debug("V: %s", base64.b64encode(decrypted_V)) logger.debug("K: %s", base64.b64encode(candidate_key)) logger.debug("auth_tag: %s", self.auth_tag) ex_mac = crypto.do_hmac(candidate_key, self.agent_uuid) if ex_mac == self.auth_tag: logger.info("Successfully derived K for UUID %s", self.agent_uuid) self.final_U = decrypted_U self.K = candidate_key return True logger.error("Failed to derive K for UUID %s", self.agent_uuid) return False
def encrypt(contents): k = crypto.generate_random_key(32) v = crypto.generate_random_key(32) u = crypto.strbitxor(k, v) ciphertext = crypto.encrypt(contents, k) try: recovered = crypto.decrypt(ciphertext, k).decode('utf-8') except UnicodeDecodeError: recovered = crypto.decrypt(ciphertext, k) if recovered != contents: raise Exception("Test decryption failed") return {'u': u, 'v': v, 'k': k, 'ciphertext': ciphertext}
def encrypt(contents): k = crypto.generate_random_key(32) v = crypto.generate_random_key(32) u = crypto.strbitxor(k, v) ciphertext = crypto.encrypt(contents, k) try: recovered = crypto.decrypt(ciphertext, k).decode("utf-8") except UnicodeDecodeError: recovered = crypto.decrypt(ciphertext, k) if recovered != contents: raise Exception("Test decryption failed") return {"u": u, "v": v, "k": k, "ciphertext": ciphertext}
def test_xor(self): k = get_random_bytes(32) s1 = generate_random_key(32) s2 = strbitxor(s1, k) self.assertEqual(strbitxor(s1, s2), k)