1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
use std::mem::MaybeUninit; use cryptoauthlib_sys::atca_aes_ctr_ctx_t; use cryptoauthlib_sys::atca_aes_cmac_ctx_t; /// An ATECC/ATSHA device buffer to load #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] pub enum NonceTarget { TempKey = 0x00, MsgDigBuf = 0x40, AltKeyBuf = 0x80, } /// Designates the source of the data to hash with TempKey for Generate Digest #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] pub enum GenDigZone { Data = 0x02, SharedNonce = 0x03, } /// Modes of calling the info_cmd() function #[allow(dead_code)] #[repr(u8)] pub enum InfoCmdType { Revision = 0x00, KeyValid = 0x01, State = 0x02, Gpio = 0x03, VolKeyPermit = 0x04, } /// The mode of calling the ECDSA signature function pub enum SignMode { /// The input parameter is hash to be signed External(Vec<u8>), Internal(SignEcdsaParam), } /// The mode of calling the ECDSA verification function pub enum VerifyMode { /// The input parameter is public key External(Vec<u8>), ExternalMac(VerifyEcdsaParam), /// The input parameter is slot number Internal(u8), InternalMac(VerifyEcdsaParam), } /// Detailed parameters of calling the ECDSA signature function pub struct SignEcdsaParam { /// Set to true if the signature will be used with /// the Verify(Invalidate) command. false for all other cases. pub is_invalidate: bool, /// Set to true if the message should incorporate /// the device's full serial number. pub is_full_sn: bool, } /// Detailed parameters of calling the ECDSA verification function pub struct VerifyEcdsaParam { /// Public key for ExternalMac mode pub public_key: Option<Vec<u8>>, /// Slot number for InternalMac mode pub slot_number: Option<u8>, /// System nonce (32 byte) used for the verification MAC pub num_in: Vec<u8>, /// IO protection key for verifying the validation MAC pub io_key: u8, } impl Default for VerifyEcdsaParam { fn default() -> VerifyEcdsaParam { VerifyEcdsaParam { public_key: None, slot_number: None, num_in: Vec::new(), io_key: 0x00, } } } /// Type of AEAD algorithm #[derive(Clone, Debug, PartialEq)] pub enum AeadAlgorithm { Ccm(AeadParam), Gcm(AeadParam), } /// AEAD algorithm parameters for compute #[derive(Clone, Debug, PartialEq)] pub struct AeadParam { /// Nonce [number used once aka IV] (default length is 12 bytes) pub nonce: Vec<u8>, /// external encryption/decryption key needed when an AES key stored in the cryptochip is not used pub key: Option<[u8; ATCA_AES_KEY_SIZE]>, /// tag to verify authenticity of decrypted data (16 bytes) pub tag: Option<Vec<u8>>, /// tag length generated during encryption pub tag_length: Option<u8>, /// Additional data that will be authenticated but not encrypted pub additional_data: Option<Vec<u8>>, } impl Default for AeadParam { fn default() -> AeadParam { AeadParam { nonce: Vec::new(), key: None, tag: None, tag_length: None, additional_data: None, } } } /// Data context structure for AEAD encryption in CCM mode #[derive(Copy, Clone, Debug)]//, PartialEq)] pub struct AtcaAesCcmCtx { pub cbc_mac_ctx: atca_aes_cmac_ctx_t, // CBC_MAC context pub ctr_ctx: atca_aes_ctr_ctx_t, // CTR context pub iv_size: u8, // iv size pub m: u8, // Tag size pub counter: [u8; ATCA_AES_DATA_SIZE], // Initial counter value pub partial_aad: [u8; ATCA_AES_DATA_SIZE], // Partial blocks of data waiting to be processed pub partial_aad_size: usize, // Amount of data in the partial block buffer pub text_size: usize, // Size of data to be processed pub enc_cb: [u8; ATCA_AES_DATA_SIZE], // Last encrypted counter block pub data_size: u32, // Size of the data being encrypted/decrypted in bytes. pub ciphertext_block: [u8; ATCA_AES_DATA_SIZE] // Last ciphertext block } impl Default for AtcaAesCcmCtx { fn default() -> AtcaAesCcmCtx { AtcaAesCcmCtx { cbc_mac_ctx: { let ctx = MaybeUninit::<atca_aes_cmac_ctx_t>::zeroed(); unsafe { ctx.assume_init() } }, ctr_ctx: { let ctx = MaybeUninit::<atca_aes_ctr_ctx_t>::zeroed(); unsafe { ctx.assume_init() } }, iv_size: ATCA_AES_DATA_SIZE as u8, m: ATCA_AES_DATA_SIZE as u8, counter: [0x00; ATCA_AES_DATA_SIZE], partial_aad: [0x00; ATCA_AES_DATA_SIZE], partial_aad_size: 0, text_size: 0, enc_cb: [0x00; ATCA_AES_DATA_SIZE], data_size: 0, ciphertext_block: [0x00; ATCA_AES_DATA_SIZE], } } } /// structure that stores data for options supported by the chip #[derive(Copy, Clone, Debug, PartialEq)] pub struct ChipOptions { /// If true, then the protection functions are enabled via the secret key /// stored in the slot indicated by io_key_in_slot. /// If false, the security functions are disabled and fields 'io_key_in_slot', /// 'ecdh_output_protection' and 'kdf_output_protection' are irrelevant /// (only relevant for the ATECC608x chip) pub io_key_enabled: bool, /// slot number where the key for encrypting transmission between chip and host is placed pub io_key_in_slot: u8, /// pub aes_enabled: bool, /// pub kdf_aes_enabled: bool, /// pub ecdh_output_protection: OutputProtectionState, /// pub kdf_output_protection: OutputProtectionState, } impl Default for ChipOptions { fn default() -> ChipOptions { ChipOptions { io_key_enabled: false, io_key_in_slot: 0x00, aes_enabled: false, kdf_aes_enabled: false, ecdh_output_protection: OutputProtectionState::Invalid, kdf_output_protection: OutputProtectionState::Invalid, } } } /// Allowed IO transmission states between chip and host MCU /// for ECDH, KDF, Verify and SecureBoot commands. #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] pub enum OutputProtectionState { /// Output in the clear is OK, though encryption can still be indicated in the mode parameter ClearTextAllowed = 0x00, /// Output is OK, but the result must be encrypted. /// The state of the encryption bit in the mode parameter will be ignored by the ECDH command. EncryptedOutputOnly = 0x01, /// Result must be stored in TempKey or and key slot, output outside the chip is forbidden ForbiddenOutputOutsideChip = 0x02, /// Invalid state Invalid = 0x03, } impl From<u8> for OutputProtectionState { fn from(orig: u8) -> Self { match orig { 0x0 => OutputProtectionState::ClearTextAllowed, 0x1 => OutputProtectionState::EncryptedOutputOnly, 0x2 => OutputProtectionState::ForbiddenOutputOutsideChip, _ => OutputProtectionState::Invalid, } } } /// An ATECC slot #[derive(Copy, Clone, Debug)] pub struct AtcaSlot { /// ATECC slot id (for diagnostic) pub id: u8, /// Lock status of slot (locked or not). If is_locked is true, /// slot cannot be written pub is_locked: bool, /// Slot configuration as can be read from configuration zone pub config: SlotConfig, } impl Default for AtcaSlot { fn default() -> Self { AtcaSlot { id: 0u8, is_locked: false, config: SlotConfig::default(), } } } /// An ATECC slot capacity #[derive(Copy, Clone, Debug)] pub struct AtcaSlotCapacity { pub blocks: u8, pub last_block_bytes: u8, pub bytes: u16, } impl Default for AtcaSlotCapacity { fn default() -> Self { AtcaSlotCapacity { blocks: 0u8, last_block_bytes: 0u8, bytes: 0u16, } } } /// Detailed ATECC key slot configuration #[derive(Copy, Clone, Debug)] pub struct SlotConfig { /// Controls the ability to modify the data in this slot. pub write_config: WriteConfig, pub key_type: KeyType, pub read_key: ReadKey, pub ecc_key_attr: EccKeyAttr, /// The index into the X509format array within the Configuration zone /// which corresponds to this slot. /// If the corresponding format byte is zero, then the public key /// can be validated by any format signature by the parent. /// If the corresponding format byte is non-zero, then the validating /// certificate must be of a certain length; /// the stored public key must be locateindicates this slot contains /// an ECC private key at a certain place within the message and the SHA() /// commands must be used to generate the digest of the message. /// Must be zero if the slot does not contain a public key. /// Valid range from 0 to 3. pub x509id: u8, /// If 'req_auth' is true, this field points to the key that must be used /// for authorization before the key associated with this slot may be used. /// Must be zero if 'req_auth' is false. /// Valid range from 0 to 15. pub auth_key: u8, /// Use this key to validate and encrypt data written to the slot /// indicated by this variable. /// Valid range from 0 to 15. pub write_key: u8, /// true = The contents of this slot are secret – Clear text reads are prohibited /// and both 4-byte reads and writes are prohibited. /// This variable must be true if 'encrypt_read' is a true or if 'write_config' /// has any value other than 'Always' to ensure proper operation of the device. /// false = The contents of this slot should contain neither confidential data nor keys. /// The GenKey and Sign commands will fail if 'is_secret' /// is set to false for any ECC private key. pub is_secret: bool, /// true = The key stored in the slot is "Limited Use". /// The number of uses of this key is limited by a in chip monotonic counter. /// false = There are no usage limitations. pub limited_use: bool, /// true = The key stored in the slot is intended for verification usage /// and cannot be used by the MAC or HMAC commands. /// When this key is used to generate or modify TempKey, /// then that value may not be used by the MAC and HMAC commands. /// Also cannot be used with the SHA command in HMAC mode. /// false = The key stored in the slot can be used by all commands. pub no_mac: bool, /// true = Use of this key is prohibited for all commands other than /// GenKey if the PersistentLatch is zero. /// GenKey is permitted regardless of the state of the latch. /// false = Use of this key is independent of the state of the PersistentLatch. pub persistent_disable: bool, /// true = Before this key must be used, a prior authorization using /// the key pointed to by AuthKey must be completed successfully /// prior to cryptographic use of the key. /// Applies to all key types, both public, secret, and private. /// false = No prior authorization is required. pub req_auth: bool, /// If true then a random nonce is required for /// GenKey, MAC, CheckMac, Verify, DeriveKey, and GenDig commands. pub req_random: bool, /// If true then this slot can be individually locked using the Lock command. pub lockable: bool, /// If 'is_private' indicates this slot contains an ECC private key: /// false = The public version of this key can never be generated. /// Use this mode for the highest security. /// true = The public version of this key can always be generated. /// If 'is_private' indicates that this slot does not contain an ECC private key, /// then this bit may be used to control validity of public keys. /// If so configured, the Verify command will only use a stored public key /// to verify a signature if it has been validated. /// The Sign and Info commands are used to report the validity state. /// The public key validity feature is ignored by all other commands /// and applies only to Slots 8 - 15. /// false = The public key in this slot can be used by the Verify command /// without being validated. /// true = The public key in this slot can be used by the Verify command /// only if the public key in the slot has been validated. /// When this slot is written for any reason, the most significant four bits /// of byte 0 of block 0 will be set to 0xA to invalidate the slot. /// The Verify command can be used to write those bits to 0x05 to validate the slot. /// If this slot contains a key of type Data or AES, then the 'pub_info' bit /// controls whether or not the KDF command write data into this slot. /// If true, then writes by KDF are allowed. /// If false, KDF may not write to this slot. pub pub_info: bool, } impl Default for SlotConfig { fn default() -> Self { SlotConfig { write_config: WriteConfig::Rfu, key_type: KeyType::Rfu, read_key: ReadKey::default(), ecc_key_attr: EccKeyAttr::default(), x509id: 0u8, auth_key: 0u8, write_key: 0u8, is_secret: false, limited_use: false, no_mac: false, persistent_disable: false, req_auth: false, req_random: false, lockable: false, pub_info: false, } } } /// Detailed ECC key attributes as stored in slot configuration #[derive(Copy, Clone, Debug)] pub struct EccKeyAttr { /// true = The key slot contains an ECC private key and /// can be accessed only with the Sign, GenKey, and PrivWrite commands. /// false = The key slot does not contain an ECC private key and /// cannot be accessed with the Sign, GenKey, and PrivWrite commands. /// It may contain an ECC public key, a SHA key, or data. pub is_private: bool, /// Slots containing private keys can never be read /// so the fields below are only valid if 'is_private' is true. /// false = External signatures of arbitrary messages are not enabled. /// true = External signatures of arbitrary messages are enabled. pub ext_sign: bool, /// false = Internal signatures of messages are not enabled. /// true = Internal signatures of messages generated by /// GenDig or GenKey are enabled. pub int_sign: bool, /// false = ECDH operation is not permitted for this key. /// true = ECDH operation is permitted for this key. pub ecdh_operation: bool, /// false = ECDH master secret will be output in the clear. /// true = Master secret will be written into slot N+1. /// (Can only be set to true for even number slots and /// should always be false for odd number slots) /// This bit is ignored if 'ecdh_operation' is false. pub ecdh_secret_out: bool, } impl Default for EccKeyAttr { fn default() -> Self { EccKeyAttr { is_private: false, ext_sign: false, int_sign: false, ecdh_operation: false, ecdh_secret_out: false, } } } /// Detailed ATECC key slot read attributes #[derive(Copy, Clone, Debug)] pub struct ReadKey { /// true = Reads from this slot will be encrypted using the procedure /// specified in the Read command using value of 'slot_number' /// to generate the encryption key. No input MAC is required. /// If this bit is true, then 'is_secret' /// from 'SlotConfig' struct must also be set. /// false = Clear text reads may be permitted, /// and the 'slot_number' field is irrelevant. pub encrypt_read: bool, /// Valid range from 0 to 15. /// If 0 then this slot can be the source for the CheckMac copy operation. /// Do not use zero as a default. Do not set this field to zero /// unless the CheckMac copy operation is explicitly desired, /// regardless of any other read/write restrictions. pub slot_number: u8, } impl Default for ReadKey { fn default() -> Self { ReadKey { encrypt_read: false, slot_number: 0u8, } } } /// Detailed ATECC key slot write configuration #[derive(Copy, Clone, Debug, PartialEq)] pub enum WriteConfig { Rfu, // do not use /// Clear text writes are always permitted on this slot. /// Slots set to always should never be used as key storage. /// Either 4 or 32 bytes may be written to this slot. Always, /// If a validated public key is stored in the slot, writes are prohibited. /// Use Verify(Invalidate) to invalidate prior to writing. /// Do not use this mode unless slot contains a public key. PubInvalid, /// Writes are never permitted on this slot using the Write command. /// Slots set to never can still be used as key storage. Never, /// Writes to this slot require a properly computed MAC, /// and the input data must be encrypted by the system with WriteKey /// using the encryption algorithm documented in the Write command description. /// 4-byte writes to this slot are prohibited. Encrypt, } /// ATECC key slot types #[derive(Copy, Clone, Debug, PartialEq)] pub enum KeyType { /// Do not use (Reserved for Future Use) Rfu, /// Slot may contain ECC key P256EccKey, /// Slot may contain AES key Aes, /// Slot may contain hash value or a raw text ShaOrText, } /// ATECC interface configuration #[derive(Copy, Clone)] pub struct AtcaIfaceCfg { /// ATECC interface type iface_type: AtcaIfaceType, /// ATECC device type devtype: AtcaDeviceType, /// ATECC interface details (contents depend on interface type). /// Not needed at all for "test-interface" iface: Option<AtcaIface>, wake_delay: u16, rx_retries: i32, } // pub struct AtcaIfaceCfg /// ATECC interface // Only one can be instantiated at a time #[derive(Copy, Clone)] pub union AtcaIface { /// ATECC I2C interface settings pub atcai2c: AtcaIfaceI2c, // pub atcaswi: AtcaIfaceSwi, // pub atcauart: AtcaIfaceUart, // pub atcahid: AtcaIfaceHid, } // pub union AtcaIface /// ATECC I2C interface details #[derive(Copy, Clone)] pub struct AtcaIfaceI2c { /// ATECC I2C bus address slave_address: u8, /// ATECC I2C bus number bus: u8, /// ATECC I2C bus baud rate baud: u32, } // pub struct AtcaIfaceI2c /// Supported ATECC interfaces #[derive(PartialEq, Copy, Clone, Display)] pub enum AtcaIfaceType { AtcaI2cIface, AtcaSwiIface, AtcaUartIface, AtcaSpiIface, AtcaHidIface, AtcaCustomIface, AtcaTestIface, AtcaUnknownIface, } // pub enum AtcaIfaceType /// ATECC/ATSHA device types supported by CryptoAuth library #[derive(PartialEq, Debug, Display, Copy, Clone)] pub enum AtcaDeviceType { ATSHA204A, ATECC108A, ATECC508A, ATECC608A, ATSHA206A, AtcaTestDevFail, AtcaTestDevSuccess, AtcaTestDevNone, AtcaTestDevFailUnimplemented, AtcaDevUnknown, } // pub enum AtcaDeviceType /// Return status for device accessing functions #[derive(Debug, Copy, Clone, Display, PartialEq)] pub enum AtcaStatus { /// Function succeeded. AtcaSuccess, AtcaConfigZoneLocked, AtcaDataZoneLocked, /// response status byte indicates CheckMac failure (status byte = 0x01) AtcaWakeFailed, /// response status byte indicates CheckMac failure (status byte = 0x01) AtcaCheckMacVerifyFailed, /// response status byte indicates parsing error (status byte = 0x03) AtcaParseError, /// response status byte indicates DEVICE did not receive data properly (status byte = 0xFF) AtcaStatusCrc, /// response status byte is unknown AtcaStatusUnknown, /// response status byte is ECC fault (status byte = 0x05) AtcaStatusEcc, /// response status byte is Self Test Error, chip in failure mode (status byte = 0x07) AtcaStatusSelftestError, /// Function could not execute due to incorrect condition / state. AtcaFuncFail, /// unspecified error AtcaGenFail, /// bad argument (out of range, null pointer, etc.) AtcaBadParam, /// invalid device id, id not set AtcaInvalidId, /// Count value is out of range or greater than buffer size. AtcaInvalidSize, /// CRC error in data received from device AtcaRxCrcError, /// Timed out while waiting for response. Number of bytes received is > 0. AtcaRxFail, /// Not an error while the Command layer is polling for a command response. AtcaRxNoResponse, /// Re-synchronization succeeded, but only after generating a Wake-up AtcaResyncWithWakeup, /// for protocols needing parity AtcaParityError, /// for Microchip PHY protocol, timeout on transmission waiting for master AtcaTxTimeout, /// for Microchip PHY protocol, timeout on receipt waiting for master AtcaRxTimeout, /// Device did not respond too many times during a transmission. Could indicate no device present. AtcaTooManyCommRetries, /// Supplied buffer is too small for data required AtcaSmallBuffer, /// Communication with device failed. Same as in hardware dependent modules. AtcaCommFail, /// Timed out while waiting for response. Number of bytes received is 0. AtcaTimeout, /// opcode is not supported by the device AtcaBadOpcode, /// received proper wake token AtcaWakeSuccess, /// chip was in a state where it could not execute the command, response status byte indicates command execution error (status byte = 0x0F) AtcaExecutionError, /// Function or some element of it hasn't been implemented yet AtcaUnimplemented, /// Code failed run-time consistency check AtcaAssertFailure, /// Failed to write AtcaTxFail, /// required zone was not locked AtcaNotLocked, /// For protocols that support device discovery (kit protocol), no devices were found AtcaNoDevices, /// random number generator health test error AtcaHealthTestError, /// Couldn't allocate required memory AtcaAllocFailure, /// Use flags on the device indicates its consumed fully AtcaUseFlagsConsumed, /// Unknown error occured AtcaUnknown, } // pub enum AtcaStatus #[derive(Debug)] struct AtcaIfaceCfgPtrWrapper { ptr: *mut cryptoauthlib_sys::ATCAIfaceCfg, } unsafe impl Send for AtcaIfaceCfgPtrWrapper {} unsafe impl Sync for AtcaIfaceCfgPtrWrapper {}