CDC Badge OS
Firmware for the CDC Badge v1.0 hardware security key
Loading...
Searching...
No Matches
apdu.h
Go to the documentation of this file.
1/*
2 * ISO 7816 APDU Parser for CDC Badge
3 *
4 * Based on pico-openpgp (https://github.com/polhenarejos/pico-openpgp)
5 * Original: Copyright (c) 2022 Pol Henarejos, AGPLv3
6 */
7
8#pragma once
9#include <stdint.h>
10#include <stdbool.h>
11#include <stddef.h>
12
13#ifdef __cplusplus
14extern "C" {
15#endif
16
17// APDU Classes
18#define CLA_ISO7816 0x00
19#define CLA_CHAIN 0x10 // Command chaining
20
21// APDU Instructions (OpenPGP specific)
22#define INS_SELECT 0xA4
23#define INS_GET_DATA 0xCA
24#define INS_PUT_DATA 0xDA
25#define INS_PUT_DATA_ODD 0xDB // PUT DATA (odd INS) with Extended Header List
26#define INS_VERIFY 0x20
27#define INS_CHANGE_PIN 0x24
28#define INS_RESET_RETRY 0x2C
29#define INS_PSO 0x2A // Perform Security Operation
30#define INS_INTERNAL_AUTH 0x88
31#define INS_GENERATE_KEYPAIR 0x47
32#define INS_GET_CHALLENGE 0x84
33#define INS_GET_RESPONSE 0xC0 // Drain remainder of a chained response (ISO 7816-4 ยง5.3.4)
34#define INS_TERMINATE 0xE6
35#define INS_ACTIVATE 0x44
36#define INS_GET_VERSION 0xF1
37#define INS_MSE 0x22 // Manage Security Environment
38
39// PSO Sub-commands (P1-P2)
40#define PSO_CDS 0x9E9A // Compute Digital Signature
41#define PSO_DEC 0x8086 // Decipher
42#define PSO_ENC 0x8680 // Encipher
43
44#ifdef __DOXYGEN__
46#endif
47
48// Parsed APDU structure
49typedef struct {
50 uint8_t cla; // Class byte
51 uint8_t ins; // Instruction byte
52 uint8_t p1; // Parameter 1
53 uint8_t p2; // Parameter 2
54 uint16_t lc; // Command data length (Nc)
55 const uint8_t *data; // Command data pointer
56 uint32_t le; // Expected response length (Ne)
57 bool extended; // Extended APDU format
58} apdu_t;
59
60#ifdef __DOXYGEN__
61} // namespace cdc::mod_gpg::openpgp
62#endif
63
64// Parse raw APDU bytes into structure
65// Returns true on success
66bool apdu_parse(const uint8_t *raw, size_t raw_len, apdu_t *apdu);
67
68// Build response APDU with status word
69// Returns total response length
70size_t apdu_build_response(uint8_t *buf, size_t buf_max,
71 const uint8_t *data, size_t data_len,
72 uint16_t sw);
73
74// Build error response (SW only)
75static inline size_t apdu_sw(uint8_t *buf, uint16_t sw) {
76 buf[0] = (sw >> 8) & 0xFF;
77 buf[1] = sw & 0xFF;
78 return 2;
79}
80
81#ifdef __cplusplus
82}
83#endif
84
bool apdu_parse(const uint8_t *raw, size_t raw_len, apdu_t *apdu)
ISO 7816 APDU parsing/building helpers for CDC Badge OpenPGP stack.
Definition apdu.cpp:17
size_t apdu_build_response(uint8_t *buf, size_t buf_max, const uint8_t *data, size_t data_len, uint16_t sw)
Builds APDU response payload with status word trailer.
Definition apdu.cpp:99
static size_t apdu_sw(uint8_t *buf, uint16_t sw)
Definition apdu.h:75
const uint8_t * data
Definition apdu.h:55