def testBadSpec(self): try: decoder.decode('', asn1Spec='not an Asn1Item') except PyAsn1Error: pass else: assert 0, 'Invalid asn1Spec accepted'
def getDevicePSKData(mode, psk, nonce, digest, payload_key): crypto_mode = cryptoMode(mode) LOG.debug('Creating PSK data: ') LOG.debug(' mode: {}'.format(crypto_mode.name)) LOG.debug(' iv ({0} bytes): {1}'.format(len(nonce), binascii.b2a_hex(nonce))) LOG.debug(' md ({0} bytes): {1}'.format(len(digest), binascii.b2a_hex(digest))) data = {'hash': digest} if payload_key: data['cek'] = payload_key asnData = native_decoder.decode( data, asn1Spec=manifest_definition.KeyTableEntry()) plainText = der_encoder.encode(asnData) LOG.debug('PSK plaintext ({0} bytes): {1}'.format( len(plainText), binascii.b2a_hex(plainText))) pskSig = { 'none-psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128 // 8]).encrypt(iv, d, b''), 'psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128 // 8]).encrypt(iv, d, b'') }.get(crypto_mode.name, lambda a, b, d: None)(psk, nonce, plainText) LOG.debug('PSK data ({0} bytes): {1}'.format(len(pskSig), binascii.b2a_hex(pskSig))) return pskSig
def testSimple(self): s = self.s.clone() s[0] = univ.Null('') s[1] = univ.OctetString('xx') s[2] = univ.Integer(33) assert decoder.decode( { 'place-holder': None, 'first-name': 'xx', 'age': 33 }, asn1Spec=self.s) == s
def testSimple(self): assert decoder.decode(1.33, asn1Spec=univ.Real()) == univ.Real(1.33)
def testNull(self): assert decoder.decode(None, asn1Spec=univ.Null()) == univ.Null()
def testSimple(self): assert decoder.decode('11111111', asn1Spec=univ.BitString()) == univ.BitString(hexValue='ff')
def testTrue(self): assert decoder.decode(True, asn1Spec=univ.Boolean()) == univ.Boolean(True)
def testPosInt(self): assert decoder.decode(12, asn1Spec=univ.Integer()) == univ.Integer(12)
def testSimple(self): assert decoder.decode('fox', asn1Spec=univ.Any()) == univ.Any('fox')
def profile_kdc(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False): now = datetime.datetime.utcnow() + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) crl_uri = u'file://{}.crl'.format(os.path.join(cert_dir, ca_nick)) builder = builder.add_extension( x509.ExtendedKeyUsage([x509.ObjectIdentifier('1.3.6.1.5.2.3.5')]), critical=False, ) name = { 'realm': realm, 'principalName': { 'name-type': 2, 'name-string': ['krbtgt', realm], }, } name = native_decoder.decode(name, asn1Spec=KRB5PrincipalName()) name = der_encoder.encode(name) names = [x509.OtherName(x509.ObjectIdentifier('1.3.6.1.5.2.2'), name)] if dns_name is not None: names += [x509.DNSName(dns_name)] builder = builder.add_extension( x509.SubjectAlternativeName(names), critical=False, ) builder = builder.add_extension( x509.CRLDistributionPoints([ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl_uri)], relative_name=None, crl_issuer=None, reasons=None, ), ]), critical=False, ) if badusage: builder = builder.add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=True, key_agreement=True, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False), critical=False) return builder
def testSimple(self): s = self.s.clone() s[1] = univ.OctetString('xx') assert decoder.decode({'first-name': 'xx'}, asn1Spec=self.s) == s
def profile_kdc(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False): now = datetime.datetime.utcnow() + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) crl_uri = u'file://{}.crl'.format(os.path.join(cert_dir, ca_nick)) builder = builder.add_extension( x509.ExtendedKeyUsage([x509.ObjectIdentifier('1.3.6.1.5.2.3.5')]), critical=False, ) name = { 'realm': realm, 'principalName': { 'name-type': 2, 'name-string': ['krbtgt', realm], }, } name = native_decoder.decode(name, asn1Spec=KRB5PrincipalName()) name = der_encoder.encode(name) names = [x509.OtherName(x509.ObjectIdentifier('1.3.6.1.5.2.2'), name)] if dns_name is not None: names += [x509.DNSName(dns_name)] builder = builder.add_extension( x509.SubjectAlternativeName(names), critical=False, ) builder = builder.add_extension( x509.CRLDistributionPoints([ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl_uri)], relative_name=None, crl_issuer=None, reasons=None, ), ]), critical=False, ) if badusage: builder = builder.add_extension( x509.KeyUsage( digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=True, key_agreement=True, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False ), critical=False ) return builder
def SHA_1_Scenario(n, e, d, data): # make digest md = hashlib.sha1() md.update(data) md = md.digest() # to asn1 public_key = decode({'n': n, 'e': e}, asn1Spec=RsaKey()) der_public_key = der_encode(public_key) # send public key with open('public_key', 'wb') as key_file: key_file.write(der_public_key) # recieve public key with open('public_key', 'rb') as key_file: public_key = key_file.read() # from asn1 get e,n public_key, _ = der_decode(public_key, asn1Spec=RsaKey()) public_key = encode(public_key) e = public_key['e'] n = public_key['n'] #encrypt hash with RSA hash_as_number = int.from_bytes(md, 'big') rsa_ecnrypted_hash = RSA_encrypt(n, d, hash_as_number) # to asn1 file_with_hash = decode( { 'alg_id': b'0006', 'key_id': b'key_for_sha', 'n': n, 'e': e, 'c': rsa_ecnrypted_hash }, asn1Spec=RsaFile()) der_file_with_hash = der_encode(file_with_hash) # send encrypted 3DES's key with open('file_with_hash', 'wb') as file: file.write(der_file_with_hash) # recieve encrypted 3DES's key with open('file_with_hash', 'rb') as file: encrypted_hash = file.read() # from asn1 get c encrypted_hash, _ = der_decode(encrypted_hash, asn1Spec=RsaFile()) encrypted_hash = encode(encrypted_hash) c = encrypted_hash['c'] # rsa decrypt hash = RSA_decrypt(n, e, c) hash = hash.to_bytes((hash.bit_length() + 7) // 8, 'big') # send file copyfile("data", "accepted_data") input("Continue?\n") # compare hashes path = "accepted_data" file = open(path, "rb") data = file.read() file.close() md = hashlib.sha1() md.update(data) md = md.digest() if (hash == md): print('Hashes matches\n') else: print('File corrupted\n')
def main(): parser = argparse.ArgumentParser( description='Prepare a device identity blob for a Toluene device') parser.add_argument('-v', '--verbose', help='verbose output', action='store_true') parser.add_argument('-E', '--wifi-essid', help='access point ESSID', required=True, dest='essid') parser.add_argument('-u', '--wifi-username', help='username for WPA authentication', required=False, default='username') parser.add_argument('-P', '--wifi-password', help='access point password', required=True, dest='password') parser.add_argument('-a', '--wifi-auth', help='wifi authentication scheme to use', default='psk') parser.add_argument('-A', '--wifi-cert', help='wifi certificate authority', default='', type=str) parser.add_argument('-H', '--service-host', help='host name for the service host', required=True, dest='host') parser.add_argument('-p', '--service-port', help='service port number to connect to', required=True, dest='port') parser.add_argument('-I', '--device-id', help='device identifier used during submission', required=True, type=lambda x: int(x, 0)) parser.add_argument('-K', '--private-key', help='private key file name', required=True, dest='private_key') parser.add_argument('-o', '--output-file', help='output file', dest='out_file', default='') parser.add_argument('-U', '--uart', help='UART to write the identity blob out to', dest='uart', default='', required=True) parser.add_argument('-B', '--baud', help='The baud rate', dest='baud_rate', default=115200) parser.add_argument( '-S', '--server-ca', help='The trusted server CA (a DER-encoded certificate)', dest='server_ca', required=True) parser.add_argument('-C', '--ca-signing-key', help='The CA signing private key', required=True) parser.add_argument( '-c', '--ca-chain', help= 'The certificate chain that attests the CA signing key (as a PEM file)', required=True) parser.add_argument( '-L', '--valid-length', help= 'The length of time (in days) the certificate is valid for, starting from this moment', required=False, default=1024, type=int) args = parser.parse_args() # Set verbosity, globally. if args.verbose: log_level = logging.DEBUG else: log_level = logging.INFO logging.basicConfig( format='%(asctime)s - %(name)s:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=log_level) if not args.uart: raise Exception( 'Need to specify a valid UART to connect to for provisioning') if args.wifi_auth not in ['psk', 'peap', 'open']: raise Exception('Unknown wifi auth type: {}'.format(args.wifi_auth)) logging.info('Loading key from file {}'.format(args.private_key)) # Read in the key with open(args.private_key, 'rb') as fp: raw_key = fp.read() pk = load_pem_private_key(raw_key, password=None, backend=default_backend()) with open(args.server_ca, 'rb') as fp: server_cert = fp.read() # If required, read in the wifi auth certificate wifi_auth_cert = b'none' if args.wifi_cert: logging.info('Using authentication CA certificate from file {}'.format( args.wifi_cert)) with open(args.wifi_cert, 'rb') as fp: wifi_auth_cert = fp.read() # Load the CA signing key with open(args.ca_signing_key, 'rb') as fp: ca_signing_key_pem = fp.read() ca_signing_key = load_pem_private_key(ca_signing_key_pem, password=None, backend=default_backend()) # Load the CA chain of certificates logging.debug('Loading CA chain') with open(args.ca_chain, 'rb') as fp: ca_certificates = [] cur_crt = b'' for line in fp: if b'BEGIN' in line: logging.debug('Starting new certificate') cur_crt = line elif b'END' in line: cur_crt += line logging.debug('Parsing certificate') if cur_crt: ca_certificates.append( load_pem_x509_certificate(cur_crt, default_backend())) cur_crt = '' else: cur_crt += line logging.info('Using UART {} ({},8n1)'.format(args.uart, args.baud_rate)) ser = serial.Serial(args.uart, args.baud_rate, timeout=1, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, rtscts=0) logging.info('Reading CSR from device...') csr = uart_read_csr(ser) logging.debug('Got csr {}'.format(csr)) ident_certs = generate_identity_certificate(csr, ca_signing_key, ca_certificates, args.valid_length, args.device_id) identity = { 'wifiESSID': args.essid, 'wifiUsername': args.wifi_username, 'wifiPassword': args.password, 'wifiAuthType': args.wifi_auth, 'wifiAuthCert': wifi_auth_cert, 'targetHost': args.host, 'targetPort': args.port, 'deviceId': args.device_id, 'serverCaRoot': server_cert, 'identityCertChain': ident_certs, } di_raw = decode(identity, asn1Spec=device_identity.DeviceIdentityInfo()) logging.info('Device information: {}'.format(di_raw)) di = der_encoder(di_raw) r, s = decode_dss_signature(pk.sign(di, ec.ECDSA(hashes.SHA256()))) """ hexdump.hexdump(di) hashctx = hashes.Hash(hashes.SHA256(), default_backend()) hashctx.update(di) logging.debug('Digest:') hexdump.hexdump(hashctx.finalize()) """ logging.debug('Device Identity Blob length: {}'.format(len(di))) logging.debug('Signature = ({}, {})'.format(r, s)) bundle = { 'identityInfo': di_raw, 'identityInfoSignature': { 'r': r, 's': s, }, } bundle_raw = decode(bundle, asn1Spec=device_identity.DeviceIdentityBundle()) bundle_encoded = der_encoder(bundle_raw) if args.out_file: logging.debug('Writing to {}'.format(args.out_file)) with open(args.out_file, 'wb+') as fp: fp.write(bundle_encoded) ser = serial.Serial(args.uart, args.baud_rate, timeout=1, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, rtscts=0) logging.info('Writing identity to device') uart_write_identity(ser, bundle_encoded)
def testNegInt(self): assert decoder.decode(-12, asn1Spec=univ.Integer()) == univ.Integer(-12)
def testTrueNeg(self): assert decoder.decode(False, asn1Spec=univ.Boolean()) == univ.Boolean(False)
def testSimple(self): assert decoder.decode('Quick brown fox', asn1Spec=univ.OctetString()) == univ.OctetString('Quick brown fox')
def testNull(self): assert decoder.decode(None, asn1Spec=univ.Null()) == univ.Null('')
def testOne(self): assert decoder.decode('1.3.6.11', asn1Spec=univ.ObjectIdentifier()) == univ.ObjectIdentifier('1.3.6.11')
def testSimple(self): s = self.s.clone() s[0] = univ.Null() s[1] = univ.OctetString('xx') s[2] = univ.Integer(33) assert decoder.decode({'place-holder': None, 'first-name': 'xx', 'age': 33}, asn1Spec=self.s) == s
def TRI_DES_Scenario(n, e, d, data): # to asn1 public_key = decode({'n': n, 'e': e}, asn1Spec=RsaKey()) der_public_key = der_encode(public_key) # send public key with open('public_key', 'wb') as key_file: key_file.write(der_public_key) # recieve public key with open('public_key', 'rb') as key_file: public_key = key_file.read() # from asn1 get e,n public_key, _ = der_decode(public_key, asn1Spec=RsaKey()) public_key = encode(public_key) e = public_key['e'] n = public_key['n'] # encrypt 3DES's key by RSA key_as_number = int.from_bytes(KEY_FOR_3DES, 'big') rsa_ecnrypted_key = RSA_encrypt(n, e, key_as_number) #print(rsa_ecnrypted_key) # to asn1 open_key = decode( { 'alg_id': b'0001', 'key_id': b'key_for_3des', 'n': n, 'e': e, 'c': rsa_ecnrypted_key }, asn1Spec=RsaFile()) der_file_with_3DES_key = der_encode(open_key) # send encrypted 3DES's key with open('file_with_3des_key', 'wb') as file: file.write(der_file_with_3DES_key) # recieve encrypted 3DES's key with open('file_with_3des_key', 'rb') as file: encrypted_3DES_key = file.read() # from asn1 get c encrypted_3DES_key, _ = der_decode(encrypted_3DES_key, asn1Spec=RsaFile()) encrypted_3DES_key = encode(encrypted_3DES_key) c = encrypted_3DES_key['c'] # rsa decrypt tri_des_key = RSA_decrypt(n, d, c) # encrypt data with 3DES tri_des_key = tri_des_key.to_bytes((tri_des_key.bit_length() + 7) // 8, 'big') tri_des = triple_des(tri_des_key, CBC, b"AWDADADA", pad=None, padmode=PAD_PKCS5) encrypted = tri_des.encrypt(data) #print(encrypted) # send encrypted data with open('ciphertext', 'wb') as ciphertext_file: ciphertext_file.write(encrypted) # recieve encrypted data with open('ciphertext', 'rb') as ciphertext_file: ciphertext = ciphertext_file.read() # decrypt data tri_des = triple_des(KEY_FOR_3DES, CBC, b"AWDADADA", pad=None, padmode=PAD_PKCS5) opentext = tri_des.decrypt(ciphertext) with open('decrypted_data', 'wb') as data: data.write(opentext)