atmel.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. /* atmel.c
  2. *
  3. * Copyright (C) 2006-2022 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A) || \
  26. defined(WOLFSSL_ATECC608A) || defined(WOLFSSL_ATECC_PKCB)
  27. #include <wolfssl/wolfcrypt/memory.h>
  28. #include <wolfssl/wolfcrypt/error-crypt.h>
  29. #include <wolfssl/ssl.h>
  30. #include <wolfssl/internal.h>
  31. #ifdef WOLFSSL_ATECC_TNGTLS
  32. #include "tng/tng_atcacert_client.h"
  33. #endif
  34. #ifdef WOLFSSL_ATECC_TFLXTLS
  35. #include "atcacert/atcacert_client.h"
  36. #include "tng/cust_def_device.h"
  37. #include "tng/cust_def_signer.h"
  38. #endif
  39. #ifdef NO_INLINE
  40. #include <wolfssl/wolfcrypt/misc.h>
  41. #else
  42. #define WOLFSSL_MISC_INCLUDED
  43. #include <wolfcrypt/src/misc.c>
  44. #endif
  45. #ifdef WOLFSSL_ATMEL
  46. /* remap name conflicts */
  47. #define Aes Aes_Remap
  48. #define Gmac Gmac_Remap
  49. #include "asf.h"
  50. #undef Aes
  51. #undef Gmac
  52. #endif /* WOLFSSL_ATMEL */
  53. #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
  54. #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
  55. #ifdef WOLFSSL_ATECC508A_TLS
  56. extern ATCA_STATUS device_init_default(void);
  57. #endif
  58. static int mAtcaInitDone = 0;
  59. /* ATECC slotId handling */
  60. static atmel_slot_alloc_cb mSlotAlloc;
  61. static atmel_slot_dealloc_cb mSlotDealloc;
  62. static byte mSlotList[ATECC_MAX_SLOT];
  63. #ifndef SINGLE_THREADED
  64. static wolfSSL_Mutex mSlotMutex;
  65. #endif
  66. /* Raspberry Pi uses /dev/i2c-1 */
  67. #ifndef ATECC_I2C_ADDR
  68. #ifdef WOLFSSL_ATECC_TNGTLS
  69. #define ATECC_I2C_ADDR 0x6A
  70. #else
  71. #define ATECC_I2C_ADDR 0xC0
  72. #endif
  73. #endif
  74. #ifndef ATECC_I2C_BUS
  75. #define ATECC_I2C_BUS 1
  76. #endif
  77. #ifndef ATECC_DEV_TYPE
  78. #ifdef WOLFSSL_ATECC508A
  79. #define ATECC_DEV_TYPE ATECC508A
  80. #else
  81. #define ATECC_DEV_TYPE ATECC608A
  82. #endif
  83. #endif
  84. static int ateccx08a_cfg_initialized = 0;
  85. static ATCAIfaceCfg cfg_ateccx08a_i2c_pi;
  86. #endif /* WOLFSSL_ATECC508A */
  87. /**
  88. * \brief Generate random number to be used for hash.
  89. */
  90. int atmel_get_random_number(uint32_t count, uint8_t* rand_out)
  91. {
  92. int ret = 0;
  93. #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
  94. uint8_t i = 0;
  95. uint32_t copy_count = 0;
  96. uint8_t rng_buffer[RANDOM_NUM_SIZE];
  97. if (rand_out == NULL) {
  98. return -1;
  99. }
  100. while (i < count) {
  101. ret = atcab_random(rng_buffer);
  102. if (ret != ATCA_SUCCESS) {
  103. WOLFSSL_MSG("Failed to create random number!");
  104. return -1;
  105. }
  106. copy_count =
  107. (count - i > RANDOM_NUM_SIZE) ? RANDOM_NUM_SIZE : count - i;
  108. XMEMCPY(&rand_out[i], rng_buffer, copy_count);
  109. i += copy_count;
  110. }
  111. #ifdef ATCAPRINTF
  112. atcab_printbin_label((const char*)"\r\nRandom Number", rand_out, count);
  113. #endif
  114. #else
  115. /* TODO: Use on-board TRNG */
  116. #endif
  117. return ret;
  118. }
  119. int atmel_get_random_block(unsigned char* output, unsigned int sz)
  120. {
  121. return atmel_get_random_number((uint32_t)sz, (uint8_t*)output);
  122. }
  123. #if defined(WOLFSSL_ATMEL) && defined(WOLFSSL_ATMEL_TIME)
  124. #include "asf.h"
  125. #include "rtc_calendar.h"
  126. extern struct rtc_module *_rtc_instance[RTC_INST_NUM];
  127. long atmel_get_curr_time_and_date(long* tm)
  128. {
  129. long rt = 0;
  130. /* Get current time */
  131. struct rtc_calendar_time rtcTime;
  132. const int monthDay[] = {0,31,59,90,120,151,181,212,243,273,304,334};
  133. int month, year, yearLeap;
  134. rtc_calendar_get_time(_rtc_instance[0], &rtcTime);
  135. /* Convert rtc_calendar_time to seconds since UTC */
  136. month = rtcTime.month % 12;
  137. year = rtcTime.year + rtcTime.month / 12;
  138. if (month < 0) {
  139. month += 12;
  140. year--;
  141. }
  142. yearLeap = (month > 1) ? year + 1 : year;
  143. rt = rtcTime.second
  144. + 60 * (rtcTime.minute
  145. + 60 * (rtcTime.hour
  146. + 24 * (monthDay[month] + rtcTime.day - 1
  147. + 365 * (year - 70)
  148. + (yearLeap - 69) / 4
  149. - (yearLeap - 1) / 100
  150. + (yearLeap + 299) / 400
  151. )
  152. )
  153. );
  154. (void)tm;
  155. return rt;
  156. }
  157. #endif
  158. #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
  159. /* Set the ATECC configuration for wolfSSL to use.
  160. *
  161. * Return 0 on success, negative upon error */
  162. int wolfCrypt_ATECC_SetConfig(ATCAIfaceCfg* cfg)
  163. {
  164. WOLFSSL_MSG("Setting ATECC ATCAIfaceCfg configuration");
  165. if (cfg == NULL) {
  166. return -1;
  167. }
  168. /* copy configuration into our local struct */
  169. XMEMSET(&cfg_ateccx08a_i2c_pi, 0, sizeof(cfg_ateccx08a_i2c_pi));
  170. cfg_ateccx08a_i2c_pi.iface_type = cfg->iface_type;
  171. cfg_ateccx08a_i2c_pi.devtype = cfg->devtype;
  172. #ifdef ATCA_ENABLE_DEPRECATED
  173. cfg_ateccx08a_i2c_pi.atcai2c.slave_address = cfg->atcai2c.slave_address;
  174. #else
  175. cfg_ateccx08a_i2c_pi.atcai2c.address = cfg->atcai2c.address;
  176. #endif
  177. cfg_ateccx08a_i2c_pi.atcai2c.bus = cfg->atcai2c.bus;
  178. cfg_ateccx08a_i2c_pi.atcai2c.baud = cfg->atcai2c.baud;
  179. cfg_ateccx08a_i2c_pi.wake_delay = cfg->wake_delay;
  180. cfg_ateccx08a_i2c_pi.rx_retries = cfg->rx_retries;
  181. cfg_ateccx08a_i2c_pi.cfg_data = cfg->cfg_data;
  182. ateccx08a_cfg_initialized = 1;
  183. return 0;
  184. }
  185. int atmel_ecc_translate_err(int status)
  186. {
  187. switch (status) {
  188. case ATCA_SUCCESS:
  189. return 0;
  190. case ATCA_BAD_PARAM:
  191. return BAD_FUNC_ARG;
  192. case ATCA_ALLOC_FAILURE:
  193. return MEMORY_E;
  194. default:
  195. #ifdef WOLFSSL_ATECC_DEBUG
  196. printf("ATECC Failure: %x\n", (word32)status);
  197. #endif
  198. break;
  199. }
  200. return WC_HW_E;
  201. }
  202. /* Function to set the slotId allocator and deallocator */
  203. int atmel_set_slot_allocator(atmel_slot_alloc_cb alloc,
  204. atmel_slot_dealloc_cb dealloc)
  205. {
  206. #ifndef SINGLE_THREADED
  207. wc_LockMutex(&mSlotMutex);
  208. #endif
  209. mSlotAlloc = alloc;
  210. mSlotDealloc = dealloc;
  211. #ifndef SINGLE_THREADED
  212. wc_UnLockMutex(&mSlotMutex);
  213. #endif
  214. return 0;
  215. }
  216. /* Function to allocate new slotId number */
  217. int atmel_ecc_alloc(int slotType)
  218. {
  219. int slotId = ATECC_INVALID_SLOT, i;
  220. #ifndef SINGLE_THREADED
  221. wc_LockMutex(&mSlotMutex);
  222. #endif
  223. if (mSlotAlloc) {
  224. slotId = mSlotAlloc(slotType);
  225. }
  226. else {
  227. switch (slotType) {
  228. case ATMEL_SLOT_ENCKEY:
  229. /* not reserved in mSlotList, so return */
  230. slotId = ATECC_SLOT_I2C_ENC;
  231. goto exit;
  232. case ATMEL_SLOT_DEVICE:
  233. /* not reserved in mSlotList, so return */
  234. slotId = ATECC_SLOT_AUTH_PRIV;
  235. goto exit;
  236. case ATMEL_SLOT_ECDHE:
  237. slotId = ATECC_SLOT_ECDHE_PRIV;
  238. #ifdef WOLFSSL_ATECC_TNGTLS
  239. /* not reserved in mSlotList, so return */
  240. goto exit;
  241. #else
  242. break;
  243. #endif
  244. case ATMEL_SLOT_ECDHE_ENC:
  245. slotId = ATECC_SLOT_ENC_PARENT;
  246. #ifdef WOLFSSL_ATECC_TNGTLS
  247. /* not reserved in mSlotList, so return */
  248. goto exit;
  249. #else
  250. break;
  251. #endif
  252. case ATMEL_SLOT_ANY:
  253. for (i=0; i < ATECC_MAX_SLOT; i++) {
  254. /* Find free slotId */
  255. if (mSlotList[i] == ATECC_INVALID_SLOT) {
  256. slotId = i;
  257. break;
  258. }
  259. }
  260. break;
  261. }
  262. /* is slot available */
  263. if (mSlotList[slotId] != ATECC_INVALID_SLOT) {
  264. slotId = ATECC_INVALID_SLOT;
  265. }
  266. else {
  267. mSlotList[slotId] = slotId;
  268. }
  269. }
  270. exit:
  271. #ifndef SINGLE_THREADED
  272. wc_UnLockMutex(&mSlotMutex);
  273. #endif
  274. return slotId;
  275. }
  276. /* Function to return slotId number to available list */
  277. void atmel_ecc_free(int slotId)
  278. {
  279. #ifndef SINGLE_THREADED
  280. wc_LockMutex(&mSlotMutex);
  281. #endif
  282. if (mSlotDealloc) {
  283. mSlotDealloc(slotId);
  284. }
  285. else if (slotId >= 0 && slotId < ATECC_MAX_SLOT) {
  286. if (slotId != ATECC_SLOT_AUTH_PRIV && slotId != ATECC_SLOT_I2C_ENC
  287. #ifdef WOLFSSL_ATECC_TNGTLS
  288. && slotId != ATMEL_SLOT_ECDHE_ENC
  289. #endif
  290. ) {
  291. /* Mark slotId free */
  292. mSlotList[slotId] = ATECC_INVALID_SLOT;
  293. }
  294. }
  295. #ifndef SINGLE_THREADED
  296. wc_UnLockMutex(&mSlotMutex);
  297. #endif
  298. }
  299. /**
  300. * \brief Callback function for getting the current encryption key
  301. */
  302. int atmel_get_enc_key_default(byte* enckey, word16 keysize)
  303. {
  304. if (enckey == NULL || keysize != ATECC_KEY_SIZE) {
  305. return BAD_FUNC_ARG;
  306. }
  307. XMEMSET(enckey, 0xFF, keysize); /* use default value */
  308. return 0;
  309. }
  310. /**
  311. * \brief Write enc key before.
  312. */
  313. #if defined(WOLFSSL_ATECC_ECDH_ENC) || defined(WOLFSSL_ATECC_ECDH_IOENC)
  314. static int atmel_init_enc_key(void)
  315. {
  316. int ret;
  317. uint8_t read_key[ATECC_KEY_SIZE];
  318. uint8_t writeBlock = 0;
  319. uint8_t writeOffset = 0;
  320. int slotId;
  321. bool isLocked = false;
  322. slotId = atmel_ecc_alloc(ATMEL_SLOT_ENCKEY);
  323. /* check for encryption key slotId */
  324. if (slotId == ATECC_INVALID_SLOT)
  325. return BAD_FUNC_ARG;
  326. /* skip if slot has already been locked */
  327. ret = atcab_is_slot_locked(slotId, &isLocked);
  328. if (ret != ATCA_SUCCESS) {
  329. return atmel_ecc_translate_err(ret);
  330. } else if (isLocked) {
  331. return 0;
  332. }
  333. /* get encryption key */
  334. ATECC_GET_ENC_KEY(read_key, sizeof(read_key));
  335. ret = atcab_write_zone(ATCA_ZONE_DATA, slotId, writeBlock, writeOffset,
  336. read_key, ATCA_BLOCK_SIZE);
  337. ForceZero(read_key, sizeof(read_key));
  338. ret = atmel_ecc_translate_err(ret);
  339. return ret;
  340. }
  341. #endif
  342. int atmel_get_rev_info(word32* revision)
  343. {
  344. int ret;
  345. ret = atcab_info((uint8_t*)revision);
  346. ret = atmel_ecc_translate_err(ret);
  347. return ret;
  348. }
  349. void atmel_show_rev_info(void)
  350. {
  351. #ifdef WOLFSSL_ATECC_DEBUG
  352. word32 revision = 0;
  353. atmel_get_rev_info(&revision);
  354. printf("ATECC608 Revision: %x\n", (word32)revision);
  355. #endif
  356. }
  357. int atmel_ecc_create_pms(int slotId, const uint8_t* peerKey, uint8_t* pms)
  358. {
  359. int ret;
  360. uint8_t read_key[ATECC_KEY_SIZE];
  361. #ifdef WOLFSSL_ATECC_ECDH_ENC
  362. int slotIdEnc;
  363. slotIdEnc = atmel_ecc_alloc(ATMEL_SLOT_ECDHE_ENC);
  364. if (slotIdEnc == ATECC_INVALID_SLOT)
  365. return BAD_FUNC_ARG;
  366. #endif
  367. /* get encryption key */
  368. ATECC_GET_ENC_KEY(read_key, sizeof(read_key));
  369. #ifdef WOLFSSL_ATECC_ECDH_ENC
  370. /* send the encrypted version of the ECDH command */
  371. ret = atcab_ecdh_enc(slotId, peerKey, pms, read_key, slotIdEnc);
  372. #elif defined(WOLFSSL_ATECC_ECDH_IOENC)
  373. /* encrypted ECDH command, using I/O protection key */
  374. ret = atcab_ecdh_ioenc(slotId, peerKey, pms, read_key);
  375. #else
  376. ret = atcab_ecdh(slotId, peerKey, pms);
  377. #endif
  378. ret = atmel_ecc_translate_err(ret);
  379. ForceZero(read_key, sizeof(read_key));
  380. #ifdef WOLFSSL_ATECC_ECDH_ENC
  381. /* free the ECDHE slot */
  382. atmel_ecc_free(slotIdEnc);
  383. #endif
  384. return ret;
  385. }
  386. int atmel_ecc_create_key(int slotId, byte* peerKey)
  387. {
  388. int ret;
  389. /* verify provided slotId */
  390. if (slotId == ATECC_INVALID_SLOT) {
  391. return WC_HW_WAIT_E;
  392. }
  393. /* generate new ephemeral key on device */
  394. ret = atcab_genkey(slotId, peerKey);
  395. ret = atmel_ecc_translate_err(ret);
  396. return ret;
  397. }
  398. int atmel_ecc_sign(int slotId, const byte* message, byte* signature)
  399. {
  400. int ret;
  401. ret = atcab_sign(slotId, message, signature);
  402. ret = atmel_ecc_translate_err(ret);
  403. return ret;
  404. }
  405. int atmel_ecc_verify(const byte* message, const byte* signature,
  406. const byte* pubkey, int* pVerified)
  407. {
  408. int ret;
  409. bool verified = false;
  410. ret = atcab_verify_extern(message, signature, pubkey, &verified);
  411. ret = atmel_ecc_translate_err(ret);
  412. if (pVerified)
  413. *pVerified = (int)verified;
  414. return ret;
  415. }
  416. #endif /* WOLFSSL_ATECC508A */
  417. int atmel_init(void)
  418. {
  419. int ret = 0;
  420. #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
  421. #if defined(WOLFSSL_ATECC608A)
  422. /*Harmony3 will generate configuration based on user inputs*/
  423. #ifdef MICROCHIP_MPLAB_HARMONY_3
  424. extern ATCAIfaceCfg atecc608_0_init_data;
  425. #endif
  426. #endif
  427. if (!mAtcaInitDone) {
  428. ATCA_STATUS status;
  429. int i;
  430. #ifndef SINGLE_THREADED
  431. wc_InitMutex(&mSlotMutex);
  432. #endif
  433. /* Init the free slotId list */
  434. for (i=0; i<ATECC_MAX_SLOT; i++) {
  435. if (i == ATECC_SLOT_AUTH_PRIV || i == ATECC_SLOT_I2C_ENC
  436. #ifdef WOLFSSL_ATECC_TNGTLS
  437. || i == ATECC_SLOT_ENC_PARENT
  438. #endif
  439. ) {
  440. mSlotList[i] = i;
  441. }
  442. else {
  443. /* ECC Slots (mark avail) */
  444. mSlotList[i] = ATECC_INVALID_SLOT;
  445. }
  446. }
  447. #ifdef MICROCHIP_MPLAB_HARMONY_3
  448. atcab_release();
  449. atcab_wakeup();
  450. #ifdef WOLFSSL_ATECC608A
  451. wolfCrypt_ATECC_SetConfig(&atecc608_0_init_data);
  452. #endif
  453. #endif
  454. if (ateccx08a_cfg_initialized == 0) {
  455. /* Setup the hardware interface using defaults */
  456. XMEMSET(&cfg_ateccx08a_i2c_pi, 0, sizeof(cfg_ateccx08a_i2c_pi));
  457. cfg_ateccx08a_i2c_pi.iface_type = ATCA_I2C_IFACE;
  458. cfg_ateccx08a_i2c_pi.devtype = ATECC_DEV_TYPE;
  459. #ifdef ATCA_ENABLE_DEPRECATED
  460. cfg_ateccx08a_i2c_pi.atcai2c.slave_address = ATECC_I2C_ADDR;
  461. #else
  462. cfg_ateccx08a_i2c_pi.atcai2c.address = ATECC_I2C_ADDR;
  463. #endif
  464. cfg_ateccx08a_i2c_pi.atcai2c.bus = ATECC_I2C_BUS;
  465. cfg_ateccx08a_i2c_pi.atcai2c.baud = 400000;
  466. cfg_ateccx08a_i2c_pi.wake_delay = 1500;
  467. cfg_ateccx08a_i2c_pi.rx_retries = 20;
  468. }
  469. /* Initialize the CryptoAuthLib to communicate with ATECC508A */
  470. status = atcab_init(&cfg_ateccx08a_i2c_pi);
  471. if (status != ATCA_SUCCESS) {
  472. WOLFSSL_MSG("Failed to initialize atcab");
  473. return WC_HW_E;
  474. }
  475. /* show revision information */
  476. atmel_show_rev_info();
  477. #ifdef WOLFSSL_ATECC508A_TLS
  478. /* Configure the ECC508 for use with TLS API functions */
  479. device_init_default();
  480. #endif
  481. #if defined(WOLFSSL_ATECC_ECDH_ENC) || defined(WOLFSSL_ATECC_ECDH_IOENC)
  482. /* Init the I2C pipe encryption key. */
  483. /* Value is generated/stored during pair for the ATECC508A and stored
  484. on micro flash */
  485. /* For this example its a fixed value */
  486. if (atmel_init_enc_key() != 0) {
  487. WOLFSSL_MSG("Failed to initialize transport key");
  488. return WC_HW_E;
  489. }
  490. #endif
  491. mAtcaInitDone = 1;
  492. }
  493. #endif /* WOLFSSL_ATECC508A */
  494. return ret;
  495. }
  496. void atmel_finish(void)
  497. {
  498. #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
  499. if (mAtcaInitDone) {
  500. atcab_release();
  501. #ifndef SINGLE_THREADED
  502. wc_FreeMutex(&mSlotMutex);
  503. #endif
  504. mAtcaInitDone = 0;
  505. }
  506. #endif
  507. }
  508. /* Reference PK Callbacks */
  509. #ifdef HAVE_PK_CALLBACKS
  510. /**
  511. * \brief Used on the server-side only for creating the ephemeral key for ECDH
  512. */
  513. int atcatls_create_key_cb(WOLFSSL* ssl, ecc_key* key, unsigned int keySz,
  514. int ecc_curve, void* ctx)
  515. {
  516. int ret;
  517. uint8_t peerKey[ATECC_PUBKEY_SIZE];
  518. uint8_t* qx = &peerKey[0];
  519. uint8_t* qy = &peerKey[ATECC_PUBKEY_SIZE/2];
  520. int slotId;
  521. (void)ssl;
  522. (void)ctx;
  523. /* ATECC508A only supports P-256 */
  524. if (ecc_curve == ECC_SECP256R1) {
  525. slotId = atmel_ecc_alloc(ATMEL_SLOT_ECDHE);
  526. if (slotId == ATECC_INVALID_SLOT)
  527. return WC_HW_WAIT_E;
  528. /* generate new ephemeral key on device */
  529. ret = atmel_ecc_create_key(slotId, peerKey);
  530. /* load generated ECC508A public key into key, used by wolfSSL */
  531. if (ret == 0) {
  532. ret = wc_ecc_import_unsigned(key, qx, qy, NULL, ECC_SECP256R1);
  533. }
  534. if (ret == 0) {
  535. key->slot = slotId;
  536. }
  537. else {
  538. atmel_ecc_free(slotId);
  539. #ifdef WOLFSSL_ATECC_DEBUG
  540. printf("atcatls_create_key_cb: ret %d\n", ret);
  541. #endif
  542. }
  543. }
  544. else {
  545. #ifndef WOLFSSL_ATECC508A_NOSOFTECC
  546. /* use software for non P-256 cases */
  547. WC_RNG rng;
  548. ret = wc_InitRng(&rng);
  549. if (ret == 0) {
  550. ret = wc_ecc_make_key_ex(&rng, keySz, key, ecc_curve);
  551. wc_FreeRng(&rng);
  552. }
  553. #else
  554. ret = NOT_COMPILED_IN;
  555. #endif /* !WOLFSSL_ATECC508A_NOSOFTECC */
  556. }
  557. return ret;
  558. }
  559. /**
  560. * \brief Creates a shared secret using a peer public key and a device key
  561. */
  562. int atcatls_create_pms_cb(WOLFSSL* ssl, ecc_key* otherKey,
  563. unsigned char* pubKeyDer, word32* pubKeySz,
  564. unsigned char* out, word32* outlen,
  565. int side, void* ctx)
  566. {
  567. int ret;
  568. ecc_key tmpKey;
  569. uint8_t peerKeyBuf[ATECC_PUBKEY_SIZE];
  570. uint8_t* peerKey = peerKeyBuf;
  571. uint8_t* qx = &peerKey[0];
  572. uint8_t* qy = &peerKey[ATECC_PUBKEY_SIZE/2];
  573. word32 qxLen = ATECC_PUBKEY_SIZE/2, qyLen = ATECC_PUBKEY_SIZE/2;
  574. if (pubKeyDer == NULL || pubKeySz == NULL ||
  575. out == NULL || outlen == NULL) {
  576. return BAD_FUNC_ARG;
  577. }
  578. (void)ssl;
  579. (void)ctx;
  580. (void)otherKey;
  581. ret = wc_ecc_init(&tmpKey);
  582. if (ret != 0) {
  583. return ret;
  584. }
  585. /* ATECC508A only supports P-256 */
  586. if (otherKey->dp->id == ECC_SECP256R1) {
  587. XMEMSET(peerKey, 0, ATECC_PUBKEY_SIZE);
  588. /* for client: create and export public key */
  589. if (side == WOLFSSL_CLIENT_END) {
  590. int slotId = atmel_ecc_alloc(ATMEL_SLOT_ECDHE);
  591. if (slotId == ATECC_INVALID_SLOT)
  592. return WC_HW_WAIT_E;
  593. tmpKey.slot = slotId;
  594. /* generate new ephemeral key on device */
  595. ret = atmel_ecc_create_key(slotId, peerKey);
  596. if (ret != ATCA_SUCCESS) {
  597. goto exit;
  598. }
  599. /* convert raw unsigned public key to X.963 format for TLS */
  600. ret = wc_ecc_import_unsigned(&tmpKey, qx, qy, NULL, ECC_SECP256R1);
  601. if (ret == 0) {
  602. ret = wc_ecc_export_x963(&tmpKey, pubKeyDer, pubKeySz);
  603. }
  604. /* export peer's key as raw unsigned for hardware */
  605. if (ret == 0) {
  606. ret = wc_ecc_export_public_raw(otherKey, qx, &qxLen,
  607. qy, &qyLen);
  608. }
  609. }
  610. /* for server: import public key */
  611. else if (side == WOLFSSL_SERVER_END) {
  612. tmpKey.slot = otherKey->slot;
  613. /* import peer's key and export as raw unsigned for hardware */
  614. ret = wc_ecc_import_x963_ex(pubKeyDer, *pubKeySz, &tmpKey,
  615. ECC_SECP256R1);
  616. if (ret == 0) {
  617. ret = wc_ecc_export_public_raw(&tmpKey, qx, &qxLen, qy, &qyLen);
  618. }
  619. }
  620. else {
  621. ret = BAD_FUNC_ARG;
  622. }
  623. if (ret != 0) {
  624. goto exit;
  625. }
  626. ret = atmel_ecc_create_pms(tmpKey.slot, peerKey, out);
  627. *outlen = ATECC_KEY_SIZE;
  628. #ifndef WOLFSSL_ATECC508A_NOIDLE
  629. /* put chip into idle to prevent watchdog situation on chip */
  630. atcab_idle();
  631. #endif
  632. (void)qxLen;
  633. (void)qyLen;
  634. }
  635. else {
  636. #ifndef WOLFSSL_ATECC508A_NOSOFTECC
  637. /* use software for non P-256 cases */
  638. ecc_key* privKey = NULL;
  639. ecc_key* pubKey = NULL;
  640. /* for client: create and export public key */
  641. if (side == WOLFSSL_CLIENT_END)
  642. {
  643. WC_RNG rng;
  644. privKey = &tmpKey;
  645. pubKey = otherKey;
  646. ret = wc_InitRng(&rng);
  647. if (ret == 0) {
  648. ret = wc_ecc_make_key_ex(&rng, 0, privKey, otherKey->dp->id);
  649. if (ret == 0) {
  650. ret = wc_ecc_export_x963(privKey, pubKeyDer, pubKeySz);
  651. }
  652. wc_FreeRng(&rng);
  653. }
  654. }
  655. /* for server: import public key */
  656. else if (side == WOLFSSL_SERVER_END) {
  657. privKey = otherKey;
  658. pubKey = &tmpKey;
  659. ret = wc_ecc_import_x963_ex(pubKeyDer, *pubKeySz, pubKey,
  660. otherKey->dp->id);
  661. }
  662. else {
  663. ret = BAD_FUNC_ARG;
  664. }
  665. /* generate shared secret and return it */
  666. if (ret == 0) {
  667. ret = wc_ecc_shared_secret(privKey, pubKey, out, outlen);
  668. }
  669. #else
  670. ret = NOT_COMPILED_IN;
  671. #endif /* !WOLFSSL_ATECC508A_NOSOFTECC */
  672. }
  673. exit:
  674. wc_ecc_free(&tmpKey);
  675. #ifdef WOLFSSL_ATECC_DEBUG
  676. if (ret != 0) {
  677. printf("atcab_ecdh_enc: ret %d\n", ret);
  678. }
  679. #endif
  680. return ret;
  681. }
  682. /**
  683. * \brief Sign received digest using private key on device
  684. */
  685. int atcatls_sign_certificate_cb(WOLFSSL* ssl, const byte* in, unsigned int inSz,
  686. byte* out, word32* outSz, const byte* key, unsigned int keySz, void* ctx)
  687. {
  688. int ret;
  689. byte sigRs[ATECC_SIG_SIZE];
  690. int slotId;
  691. (void)ssl;
  692. (void)inSz;
  693. (void)key;
  694. (void)keySz;
  695. (void)ctx;
  696. if (in == NULL || out == NULL || outSz == NULL) {
  697. return BAD_FUNC_ARG;
  698. }
  699. slotId = atmel_ecc_alloc(ATMEL_SLOT_DEVICE);
  700. if (slotId == ATECC_INVALID_SLOT)
  701. return WC_HW_WAIT_E;
  702. /* We can only sign with P-256 */
  703. ret = atmel_ecc_sign(slotId, in, sigRs);
  704. if (ret != ATCA_SUCCESS) {
  705. ret = WC_HW_E; goto exit;
  706. }
  707. #ifndef WOLFSSL_ATECC508A_NOIDLE
  708. /* put chip into idle to prevent watchdog situation on chip */
  709. atcab_idle();
  710. #endif
  711. /* Encode with ECDSA signature */
  712. ret = wc_ecc_rs_raw_to_sig(
  713. &sigRs[0], ATECC_SIG_SIZE/2,
  714. &sigRs[ATECC_SIG_SIZE/2], ATECC_SIG_SIZE/2,
  715. out, outSz);
  716. if (ret != 0) {
  717. goto exit;
  718. }
  719. exit:
  720. atmel_ecc_free(slotId);
  721. #ifdef WOLFSSL_ATECC_DEBUG
  722. if (ret != 0) {
  723. printf("atcatls_sign_certificate_cb: ret %d\n", ret);
  724. }
  725. #endif
  726. return ret;
  727. }
  728. /**
  729. * \brief Verify signature received from peers to prove peer's private key.
  730. */
  731. int atcatls_verify_signature_cb(WOLFSSL* ssl, const byte* sig,
  732. unsigned int sigSz, const byte* hash, unsigned int hashSz, const byte* key,
  733. unsigned int keySz, int* result, void* ctx)
  734. {
  735. int ret;
  736. ecc_key tmpKey;
  737. word32 idx = 0;
  738. uint8_t peerKey[ATECC_PUBKEY_SIZE];
  739. uint8_t* qx = &peerKey[0];
  740. uint8_t* qy = &peerKey[ATECC_PUBKEY_SIZE/2];
  741. word32 qxLen = ATECC_PUBKEY_SIZE/2, qyLen = ATECC_PUBKEY_SIZE/2;
  742. byte sigRs[ATECC_SIG_SIZE];
  743. word32 rSz = ATECC_SIG_SIZE/2;
  744. word32 sSz = ATECC_SIG_SIZE/2;
  745. (void)sigSz;
  746. (void)hashSz;
  747. (void)ctx;
  748. if (ssl == NULL || key == NULL || sig == NULL ||
  749. hash == NULL || result == NULL) {
  750. return BAD_FUNC_ARG;
  751. }
  752. /* import public key */
  753. ret = wc_ecc_init(&tmpKey);
  754. if (ret == 0) {
  755. ret = wc_EccPublicKeyDecode(key, &idx, &tmpKey, keySz);
  756. }
  757. if (ret != 0) {
  758. goto exit;
  759. }
  760. if (tmpKey.dp->id == ECC_SECP256R1) {
  761. /* export public as unsigned bin for hardware */
  762. ret = wc_ecc_export_public_raw(&tmpKey, qx, &qxLen, qy, &qyLen);
  763. wc_ecc_free(&tmpKey);
  764. if (ret != 0) {
  765. goto exit;
  766. }
  767. /* decode the ECDSA signature */
  768. ret = wc_ecc_sig_to_rs(sig, sigSz,
  769. &sigRs[0], &rSz,
  770. &sigRs[ATECC_SIG_SIZE/2], &sSz);
  771. if (ret != 0) {
  772. goto exit;
  773. }
  774. ret = atmel_ecc_verify(hash, sigRs, peerKey, result);
  775. if (ret != ATCA_SUCCESS || !*result) {
  776. ret = WC_HW_E; goto exit;
  777. }
  778. #ifndef WOLFSSL_ATECC508A_NOIDLE
  779. /* put chip into idle to prevent watchdog situation on chip */
  780. atcab_idle();
  781. #endif
  782. }
  783. else {
  784. #ifndef WOLFSSL_ATECC508A_NOSOFTECC
  785. ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, result, &tmpKey);
  786. #else
  787. ret = NOT_COMPILED_IN;
  788. #endif /* !WOLFSSL_ATECC508A_NOSOFTECC */
  789. }
  790. (void)rSz;
  791. (void)sSz;
  792. (void)qxLen;
  793. (void)qyLen;
  794. ret = 0; /* success */
  795. exit:
  796. #ifdef WOLFSSL_ATECC_DEBUG
  797. if (ret != 0) {
  798. printf("atcatls_verify_signature_cb: ret %d\n", ret);
  799. }
  800. #endif
  801. return ret;
  802. }
  803. static int atcatls_set_certificates(WOLFSSL_CTX *ctx)
  804. {
  805. #ifndef ATCATLS_SIGNER_CERT_MAX_SIZE
  806. #define ATCATLS_SIGNER_CERT_MAX_SIZE 0x250
  807. #endif
  808. #ifndef ATCATLS_DEVICE_CERT_MAX_SIZE
  809. #define ATCATLS_DEVICE_CERT_MAX_SIZE 0x250
  810. #endif
  811. #ifndef ATCATLS_CERT_BUFF_MAX_SIZE
  812. #define ATCATLS_CERT_BUFF_MAX_SIZE (ATCATLS_SIGNER_CERT_MAX_SIZE +\
  813. ATCATLS_DEVICE_CERT_MAX_SIZE)
  814. #endif
  815. #ifndef ATCATLS_PUBKEY_BUFF_MAX_SIZE
  816. #define ATCATLS_PUBKEY_BUFF_MAX_SIZE 65
  817. #endif
  818. int ret = 0;
  819. ATCA_STATUS status;
  820. size_t signerCertSize = ATCATLS_SIGNER_CERT_MAX_SIZE;
  821. size_t deviceCertSize = ATCATLS_DEVICE_CERT_MAX_SIZE;
  822. uint8_t certBuffer[ATCATLS_CERT_BUFF_MAX_SIZE];
  823. uint8_t signerBuffer[ATCATLS_SIGNER_CERT_MAX_SIZE];
  824. #ifdef WOLFSSL_ATECC_TFLXTLS
  825. uint8_t signerPubKeyBuffer[ATCATLS_PUBKEY_BUFF_MAX_SIZE];
  826. #endif
  827. #ifdef WOLFSSL_ATECC_TNGTLS
  828. ret = tng_atcacert_max_signer_cert_size(&signerCertSize);
  829. if (ret != ATCACERT_E_SUCCESS) {
  830. #ifdef WOLFSSL_ATECC_DEBUG
  831. printf("Failed to get max signer cert size\r\n");
  832. #endif
  833. return ret;
  834. }
  835. else if (signerCertSize > ATCATLS_SIGNER_CERT_MAX_SIZE) {
  836. #ifdef WOLFSSL_ATECC_DEBUG
  837. printf("Signer CA cert buffer too small, need to increase at least"
  838. " to %d\r\n", signerCertSize);
  839. #endif
  840. return -1;
  841. }
  842. /* Read TNGTLS signer cert */
  843. status = tng_atcacert_read_signer_cert(signerBuffer, &signerCertSize);
  844. if (ATCA_SUCCESS != status) {
  845. ret = atmel_ecc_translate_err(status);
  846. return ret;
  847. }
  848. /* Read device cert signed by the signer above */
  849. status = tng_atcacert_read_device_cert(certBuffer, &deviceCertSize,
  850. signerBuffer);
  851. if (ATCA_SUCCESS != status) {
  852. ret = atmel_ecc_translate_err(status);
  853. return ret;
  854. }
  855. else if (deviceCertSize > ATCATLS_DEVICE_CERT_MAX_SIZE) {
  856. #ifdef WOLFSSL_ATECC_DEBUG
  857. printf("Device cert buffer too small, need to increase at least"
  858. " to %d\r\n", deviceCertSize);
  859. #endif
  860. return -1;
  861. }
  862. #endif
  863. #ifdef WOLFSSL_ATECC_TFLXTLS
  864. /* MAKE SURE TO COPY YOUR CUSTOM CERTIFICATE FILES UNDER CAL/tng
  865. * Verify variable names, here below the code uses typical tflxtls
  866. * proto example.
  867. *
  868. * g_cert_def_1_signer
  869. * g_cert_ca_public_key_1_signer
  870. * g_cert_def_3_device
  871. */
  872. status = atcacert_read_cert(&g_cert_def_1_signer,
  873. (const uint8_t*)g_cert_ca_public_key_1_signer,
  874. signerBuffer, &signerCertSize);
  875. if (status != ATCA_SUCCESS) {
  876. #ifdef WOLFSSL_ATECC_DEBUG
  877. printf("Failed to read TFLXTLS signer cert!\r\n");
  878. #endif
  879. return (int)status;
  880. }
  881. else if (signerCertSize > ATCATLS_SIGNER_CERT_MAX_SIZE) {
  882. #ifdef WOLFSSL_ATECC_DEBUG
  883. printf("Signer TFLXTLS CA cert buffer too small, need to increase"
  884. " at least to %d\r\n", signerCertSize);
  885. #endif
  886. return -1;
  887. }
  888. status = atcacert_get_subj_public_key(&g_cert_def_1_signer, signerBuffer,
  889. signerCertSize, signerPubKeyBuffer);
  890. if (status != ATCA_SUCCESS) {
  891. #ifdef WOLFSSL_ATECC_DEBUG
  892. printf("Failed to read TFLXTLS signer public key!\r\n");
  893. #endif
  894. return (int)status;
  895. }
  896. status = atcacert_read_cert(&g_cert_def_3_device, signerPubKeyBuffer,
  897. certBuffer, &deviceCertSize);
  898. if (status != ATCA_SUCCESS) {
  899. #ifdef WOLFSSL_ATECC_DEBUG
  900. printf("Failed to read device cert!\r\n");
  901. #endif
  902. return (int)status;
  903. }
  904. #endif
  905. /* Prepare the full buffer adding the signer certificate */
  906. XMEMCPY(&certBuffer[deviceCertSize], signerBuffer, signerCertSize);
  907. ret = wolfSSL_CTX_use_certificate_chain_buffer_format(ctx,
  908. (const unsigned char*)certBuffer, (signerCertSize + deviceCertSize),
  909. WOLFSSL_FILETYPE_ASN1);
  910. if (ret != WOLFSSL_SUCCESS) {
  911. #ifdef WOLFSSL_ATECC_DEBUG
  912. printf("Error registering certificate chain\r\n");
  913. #endif
  914. ret = -1;
  915. }
  916. else {
  917. ret = 0;
  918. }
  919. return ret;
  920. }
  921. int atcatls_set_callbacks(WOLFSSL_CTX* ctx)
  922. {
  923. int ret = 0;
  924. wolfSSL_CTX_SetEccKeyGenCb(ctx, atcatls_create_key_cb);
  925. wolfSSL_CTX_SetEccVerifyCb(ctx, atcatls_verify_signature_cb);
  926. wolfSSL_CTX_SetEccSignCb(ctx, atcatls_sign_certificate_cb);
  927. wolfSSL_CTX_SetEccSharedSecretCb(ctx, atcatls_create_pms_cb);
  928. #if defined(WOLFSSL_ATECC_TNGTLS) || defined(WOLFSSL_ATECC_TFLXTLS)
  929. ret = atcatls_set_certificates(ctx);
  930. if (ret != 0) {
  931. #ifdef WOLFSSL_ATECC_DEBUG
  932. printf("atcatls_set_certificates failed. (%d)\r\n", ret);
  933. #endif
  934. }
  935. #endif
  936. return ret;
  937. }
  938. int atcatls_set_callback_ctx(WOLFSSL* ssl, void* user_ctx)
  939. {
  940. wolfSSL_SetEccKeyGenCtx(ssl, user_ctx);
  941. wolfSSL_SetEccVerifyCtx(ssl, user_ctx);
  942. wolfSSL_SetEccSignCtx(ssl, user_ctx);
  943. wolfSSL_SetEccSharedSecretCtx(ssl, user_ctx);
  944. return 0;
  945. }
  946. #endif /* HAVE_PK_CALLBACKS */
  947. #endif /* WOLFSSL_ATMEL || WOLFSSL_ATECC508A || WOLFSSL_ATECC_PKCB */