Ejemplo n.º 1
0
 def list(self):
     token = self.client.pin_protocol.get_pin_token(self.pin)
     pin_protocol = 1
     cm = CredentialManagement(self.ctap2, pin_protocol, token)
     meta = cm.get_metadata()
     existing = meta[CredentialManagement.RESULT.EXISTING_CRED_COUNT]
     if existing == 0:
         print("No PGP keys found")
         return
     creds = cm.enumerate_creds(sha256(RP_ID.encode('ascii')))
     for cred in creds:
         user_id = cred[CredentialManagement.RESULT.USER]['id']
         created = int.from_bytes(user_id, 'big', signed=False)
         username = cred[CredentialManagement.RESULT.USER]['name']
         pubkey_x = cred[CredentialManagement.RESULT.PUBLIC_KEY][-2]
         pubkey_y = cred[CredentialManagement.RESULT.PUBLIC_KEY][-3]
         pubkey = (pubkey_x, pubkey_y)
         pubkey_pkt = self._pubkey_packet(pubkey, created)
         fp = self._fingerprint(pubkey_pkt)
         key_id = fp[-8:]
         created_date = datetime.utcfromtimestamp(created).strftime(
             '%Y-%m-%d %H:%M:%S')
         print("Created: {}".format(created_date))
         print("User: {}".format(username))
         print("ID: {}".format(key_id.hex().upper()))
         print("Fingerprint: {}".format(fp.hex().upper()))
         print()
Ejemplo n.º 2
0
    def delete_resident_credential(self, credential_id, pin):
        _credman = CredentialManagement(self.ctap, self.pin.VERSION,
                                        self.pin.get_pin_token(pin))

        for cred in self.get_resident_credentials(pin):
            if credential_id == cred.credential_id:
                _credman.delete_cred(credential_id)
Ejemplo n.º 3
0
 def sign(self, key_id, data):
     key_id = bytes.fromhex(key_id)
     token = self.client.pin_protocol.get_pin_token(self.pin)
     pin_protocol = 1
     cm = CredentialManagement(self.ctap2, pin_protocol, token)
     creds = cm.enumerate_creds(sha256(RP_ID.encode('ascii')))
     for cred in creds:
         user_id = cred[CredentialManagement.RESULT.USER]['id']
         created = int.from_bytes(user_id, 'big', signed=False)
         username = cred[CredentialManagement.RESULT.USER]['name']
         cred_id = cred[CredentialManagement.RESULT.CREDENTIAL_ID]['id']
         pubkey_x = cred[CredentialManagement.RESULT.PUBLIC_KEY][-2]
         pubkey_y = cred[CredentialManagement.RESULT.PUBLIC_KEY][-3]
         pubkey = (pubkey_x, pubkey_y)
         pubkey_pkt = self._pubkey_packet(pubkey, created)
         fp = self._fingerprint(pubkey_pkt)
         curr_key_id = fp[-8:]
         if curr_key_id == key_id:
             break
     else:
         print("Key {} not found".format(key_id))
         return None
     created = int(time.time())
     hashed_subpkts = [
         SubPacket(0x21, b'\x04' + fp),
         SubPacket(0x02, struct.pack('>I', created))
     ]
     unhashed_subpkts = [SubPacket(0x10, key_id)]  # issuer
     sig_pkt = self._signature_packet_data(cred_id, data, hashed_subpkts,
                                           unhashed_subpkts)
     armored = self._ascii_armor(sig_pkt)
     print('\n[GNUPG:] SIG_CREATED ', file=sys.stderr)
     print('-----BEGIN PGP SIGNATURE-----\n\n{}-----END PGP SIGNATURE-----'.
           format(armored))
Ejemplo n.º 4
0
    def get_resident_credentials(self, pin):
        _credman = CredentialManagement(self.ctap, self.pin.VERSION,
                                        self.pin.get_pin_token(pin))

        for rp in _credman.enumerate_rps():
            for cred in _credman.enumerate_creds(
                    rp[CredentialManagement.RESULT.RP_ID_HASH]):
                yield ResidentCredential(cred, rp)
Ejemplo n.º 5
0
    def delete_resident_credential(self, credential_id, pin):
        _credman = CredentialManagement(
            self.ctap,
            self.pin.protocol,
            self.pin.get_pin_token(pin, ClientPin.PERMISSION.CREDENTIAL_MGMT),
        )

        for cred in self.get_resident_credentials(pin):
            if credential_id == cred.credential_id:
                _credman.delete_cred(credential_id)
Ejemplo n.º 6
0
    def get_resident_credentials(self, pin):
        _credman = CredentialManagement(
            self.ctap,
            self.pin.protocol,
            self.pin.get_pin_token(pin, ClientPin.PERMISSION.CREDENTIAL_MGMT),
        )

        for rp in _credman.enumerate_rps():
            for cred in _credman.enumerate_creds(
                    rp[CredentialManagement.RESULT.RP_ID_HASH]):
                yield ResidentCredential(cred, rp)
Ejemplo n.º 7
0
 def export(self, key_id):
     key_id = bytes.fromhex(key_id)
     token = self.client.pin_protocol.get_pin_token(self.pin)
     pin_protocol = 1
     cm = CredentialManagement(self.ctap2, pin_protocol, token)
     meta = cm.get_metadata()
     existing = meta[CredentialManagement.RESULT.EXISTING_CRED_COUNT]
     if existing == 0:
         print("No PGP keys found")
         return
     creds = cm.enumerate_creds(sha256(RP_ID.encode('ascii')))
     for cred in creds:
         user_id = cred[CredentialManagement.RESULT.USER]['id']
         created = int.from_bytes(user_id, 'big', signed=False)
         username = cred[CredentialManagement.RESULT.USER]['name']
         cred_id = cred[CredentialManagement.RESULT.CREDENTIAL_ID]['id']
         pubkey_x = cred[CredentialManagement.RESULT.PUBLIC_KEY][-2]
         pubkey_y = cred[CredentialManagement.RESULT.PUBLIC_KEY][-3]
         pubkey = (pubkey_x, pubkey_y)
         pubkey_pkt = self._pubkey_packet(pubkey, created)
         userid_pkt = self._userid_packet(username)
         fp = self._fingerprint(pubkey_pkt)
         curr_key_id = fp[-8:]
         if curr_key_id == key_id:
             break
     else:
         print("Key not found")
         return
     hashed_prefix = b'\x99\x00\x52' + pubkey_pkt[2:]
     hashed_prefix += b'\xb4' + struct.pack(
         '>I',
         len(userid_pkt) - 2) + userid_pkt[2:]
     hashed_subpkts = [
         SubPacket(0x21, b'\x04' + fp),
         SubPacket(0x1B, b'\x03'),  # key flags
         SubPacket(0x02, struct.pack('>I', created))
     ]
     unhashed_subpkts = [SubPacket(0x10, key_id)]  # issuer
     sig_pkt = self._signature_packet_key(cred_id, hashed_prefix,
                                          hashed_subpkts, unhashed_subpkts)
     armored = self._ascii_armor(pubkey_pkt + userid_pkt + sig_pkt)
     print(
         '-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n{}-----END PGP PUBLIC KEY BLOCK-----'
         .format(armored))
Ejemplo n.º 8
0
def sk_get_resident(application, user, pin):
    """Get keys resident on a security key"""

    app_hash = sha256(application).digest()
    result = []

    for dev in CtapHidDevice.list_devices():
        try:
            ctap2 = CTAP2(dev)

            pin_protocol = PinProtocolV1(ctap2)
            pin_token = pin_protocol.get_pin_token(pin)

            cred_mgmt = CredentialManagement(ctap2, pin_protocol.VERSION,
                                             pin_token)

            for cred in cred_mgmt.enumerate_creds(app_hash):
                name = cred[CredentialManagement.RESULT.USER]['name']

                if user and name != user:
                    continue

                cred_id = cred[CredentialManagement.RESULT.CREDENTIAL_ID]
                key_handle = cred_id['id']

                public_key = cred[CredentialManagement.RESULT.PUBLIC_KEY]
                alg = public_key[3]
                public_value = _decode_public_key(alg, public_key)

                result.append((alg, name, public_value, key_handle))
        except CtapError as exc:
            if exc.code == CtapError.ERR.NO_CREDENTIALS:
                continue
            elif exc.code == CtapError.ERR.PIN_INVALID:
                raise ValueError('Invalid PIN') from None
            elif exc.code == CtapError.ERR.PIN_NOT_SET:
                raise ValueError('PIN not set') from None
            else:
                raise ValueError(str(exc)) from None
        finally:
            dev.close()

    return result
Ejemplo n.º 9
0
def _init_credman(ctx, pin):
    pin = _require_pin(ctx, pin, "Credential Management")

    ctap2 = ctx.obj.get("ctap2")
    client_pin = ClientPin(ctap2)
    try:
        token = client_pin.get_pin_token(pin, ClientPin.PERMISSION.CREDENTIAL_MGMT)
    except CtapError as e:
        logger.error("Ctap error", exc_info=e)
        _fail_pin_error(ctx, e, "PIN error: %s")

    return CredentialManagement(ctap2, client_pin.protocol, token)
Ejemplo n.º 10
0
def _init_credman(ctx, pin):
    ctap2 = ctx.obj.get("ctap2")

    if not ctap2:
        cli_fail("Credential management not supported on this YubiKey.")
    elif not ctap2.info.options.get("clientPin"):
        cli_fail("Credential management requires having a PIN. Set a PIN first.")

    if pin is None:
        pin = _prompt_current_pin(prompt="Enter your PIN")

    client_pin = ClientPin(ctap2)
    try:
        token = client_pin.get_pin_token(pin, ClientPin.PERMISSION.CREDENTIAL_MGMT)
    except CtapError as e:
        logger.error("Ctap error", exc_info=e)
        _fail_pin_error(ctx, e, "PIN error: %s")

    return CredentialManagement(ctap2, client_pin.protocol, token)
Ejemplo n.º 11
0
 def cred_mgmt(self, pin):
     token = self.client.pin_protocol.get_pin_token(pin)
     pin_protocol = 1
     return CredentialManagement(self.ctap2, pin_protocol, token)
Ejemplo n.º 12
0
def CredMgmtWrongPinAuth(device, pin_token):
    pin_protocol = 1
    wrong_pt = bytearray(pin_token)
    wrong_pt[0] = (wrong_pt[0] + 1) % 256
    return CredentialManagement(device.ctap2, pin_protocol, bytes(wrong_pt))
Ejemplo n.º 13
0
def CredMgmt(device, PinToken):
    pin_protocol = 1
    return CredentialManagement(device.ctap2, pin_protocol, PinToken)
Ejemplo n.º 14
0
 def cred_mgmt(self, pin):
     client = self.get_current_fido_client()
     token = client.client_pin.get_pin_token(pin)
     ctap2 = CTAP2(self.get_current_hid_device())
     return CredentialManagement(ctap2, client.client_pin.protocol, token)