LoRaMacCrypto.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. /*!
  2. * \file LoRaMacCrypto.c
  3. *
  4. * \brief LoRa MAC layer cryptography implementation
  5. *
  6. * \copyright Revised BSD License, see section \ref LICENSE.
  7. *
  8. * \code
  9. * ______ _
  10. * / _____) _ | |
  11. * ( (____ _____ ____ _| |_ _____ ____| |__
  12. * \____ \| ___ | (_ _) ___ |/ ___) _ \
  13. * _____) ) ____| | | || |_| ____( (___| | | |
  14. * (______/|_____)_|_|_| \__)_____)\____)_| |_|
  15. * (C)2013-2017 Semtech
  16. *
  17. * ___ _____ _ ___ _ _____ ___ ___ ___ ___
  18. * / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
  19. * \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
  20. * |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
  21. * embedded.connectivity.solutions===============
  22. *
  23. * \endcode
  24. *
  25. * \author Miguel Luis ( Semtech )
  26. *
  27. * \author Gregory Cristian ( Semtech )
  28. *
  29. * \author Daniel Jaeckle ( STACKFORCE )
  30. *
  31. * \author Johannes Bruder ( STACKFORCE )
  32. */
  33. #include <stdbool.h>
  34. #include <stdlib.h>
  35. #include <stdint.h>
  36. #include "utilities.h"
  37. #include "secure-element.h"
  38. #include "LoRaMacParser.h"
  39. #include "LoRaMacSerializer.h"
  40. #include "LoRaMacCrypto.h"
  41. /*!
  42. * Indicates if LoRaWAN 1.1.x crypto scheme is enabled
  43. */
  44. #define USE_LRWAN_1_1_X_CRYPTO 0
  45. /*!
  46. * Indicates if a random devnonce must be used or not
  47. */
  48. #define USE_RANDOM_DEV_NONCE 1
  49. /*
  50. * Frame direction definition for uplink communications
  51. */
  52. #define UPLINK 0
  53. /*
  54. * Frame direction definition for downlink communications
  55. */
  56. #define DOWNLINK 1
  57. /*
  58. * CMAC/AES Message Integrity Code (MIC) Block B0 size
  59. */
  60. #define MIC_BLOCK_BX_SIZE 16
  61. /*
  62. * Size of JoinReqType is field for integrity check
  63. */
  64. #define JOIN_REQ_TYPE_SIZE 1
  65. /*
  66. * Size of DevNonce is field for integrity check
  67. */
  68. #define DEV_NONCE_SIZE 2
  69. /*
  70. * Number of security context entries
  71. */
  72. #define NUM_OF_SEC_CTX 5
  73. /*
  74. * Size of the module context
  75. */
  76. #define CRYPTO_CTX_SIZE sizeof( LoRaMacCryptoCtx_t )
  77. /*
  78. * Size of the module non volatile context
  79. */
  80. #define CRYPTO_NVM_CTX_SIZE sizeof( LoRaMacCryptoNvmCtx_t )
  81. /*
  82. * Maximum size of the message that can be handled by the crypto operations
  83. */
  84. #define CRYPTO_MAXMESSAGE_SIZE 256
  85. /*
  86. * Maximum size of the buffer for crypto operations
  87. */
  88. #define CRYPTO_BUFFER_SIZE CRYPTO_MAXMESSAGE_SIZE + MIC_BLOCK_BX_SIZE
  89. /*
  90. * MIC computaion offset
  91. */
  92. #define CRYPTO_MIC_COMPUTATION_OFFSET JOIN_REQ_TYPE_SIZE + LORAMAC_JOIN_EUI_FIELD_SIZE + DEV_NONCE_SIZE + LORAMAC_MHDR_FIELD_SIZE
  93. /*!
  94. * LoRaWAN Frame counter list.
  95. */
  96. typedef struct sFCntList
  97. {
  98. /*!
  99. * Uplink frame counter which is incremented with each uplink.
  100. */
  101. uint32_t FCntUp;
  102. /*!
  103. * Network downlink frame counter which is incremented with each downlink on FPort 0
  104. * or when the FPort field is missing.
  105. */
  106. uint32_t NFCntDown;
  107. /*!
  108. * Application downlink frame counter which is incremented with each downlink
  109. * on a port different than 0.
  110. */
  111. uint32_t AFCntDown;
  112. /*!
  113. * In case if the device is connected to a LoRaWAN 1.0 Server,
  114. * this counter is used for every kind of downlink frame.
  115. */
  116. uint32_t FCntDown;
  117. /*!
  118. * Multicast downlink counter for index 0
  119. */
  120. uint32_t McFCntDown0;
  121. /*!
  122. * Multicast downlink counter for index 1
  123. */
  124. uint32_t McFCntDown1;
  125. /*!
  126. * Multicast downlink counter for index 2
  127. */
  128. uint32_t McFCntDown2;
  129. /*!
  130. * Multicast downlink counter for index 3
  131. */
  132. uint32_t McFCntDown3;
  133. }FCntList_t;
  134. /*
  135. * LoRaMac Crypto Non Volatile Context structure
  136. */
  137. typedef struct sLoRaMacCryptoNvmCtx
  138. {
  139. /*
  140. * Stores the information if the device is connected to a LoRaWAN network
  141. * server with prior to 1.1.0 implementation.
  142. */
  143. Version_t LrWanVersion;
  144. /*
  145. * Device nonce is a counter starting at 0 when the device is initially
  146. * powered up and incremented with every JoinRequest.
  147. */
  148. uint16_t DevNonce;
  149. /*
  150. * JoinNonce is a device specific counter value (that never repeats itself)
  151. * provided by the join server and incremented with every JoinAccept message.
  152. */
  153. uint32_t JoinNonce;
  154. /*
  155. * Frame counter list
  156. */
  157. FCntList_t FCntList;
  158. /*
  159. * RJcount1 is a counter incremented with every Rejoin request Type 1 frame transmitted.
  160. */
  161. uint16_t RJcount1;
  162. /*
  163. * LastDownFCnt stores the information which frame counter was used to unsecure the last frame.
  164. * This information is needed to compute ConfFCnt in B1 block for the MIC.
  165. */
  166. uint32_t* LastDownFCnt;
  167. }LoRaMacCryptoNvmCtx_t;
  168. /*
  169. * LoRaMac Crypto Context structure
  170. */
  171. typedef struct sLoRaMacCryptoCtx
  172. {
  173. /*
  174. * RJcount0 is a counter incremented with every Type 0 or 2 Rejoin frame transmitted.
  175. */
  176. uint16_t RJcount0;
  177. /*
  178. * Non volatile module context structure
  179. */
  180. LoRaMacCryptoNvmCtx_t* NvmCtx;
  181. /*
  182. * Callback function to notify the upper layer about context change
  183. */
  184. LoRaMacCryptoNvmEvent EventCryptoNvmCtxChanged;
  185. }LoRaMacCryptoCtx_t;
  186. /*
  187. * Key-Address item
  188. */
  189. typedef struct sKeyAddr
  190. {
  191. /*
  192. * Address identifier
  193. */
  194. AddressIdentifier_t AddrID;
  195. /*
  196. * Application session key
  197. */
  198. KeyIdentifier_t AppSkey;
  199. /*
  200. * Network session key
  201. */
  202. KeyIdentifier_t NwkSkey;
  203. /*
  204. * Rootkey (Multicast only)
  205. */
  206. KeyIdentifier_t RootKey;
  207. }KeyAddr_t;
  208. /*
  209. *Crypto module context.
  210. */
  211. static LoRaMacCryptoCtx_t CryptoCtx;
  212. /*
  213. * Non volatile module context.
  214. */
  215. static LoRaMacCryptoNvmCtx_t NvmCryptoCtx;
  216. /*
  217. * Key-Address list
  218. */
  219. static KeyAddr_t KeyAddrList[NUM_OF_SEC_CTX] =
  220. {
  221. { MULTICAST_0_ADDR, MC_APP_S_KEY_0, MC_NWK_S_KEY_0, MC_KEY_0 },
  222. { MULTICAST_1_ADDR, MC_APP_S_KEY_1, MC_NWK_S_KEY_1, MC_KEY_1 },
  223. { MULTICAST_2_ADDR, MC_APP_S_KEY_2, MC_NWK_S_KEY_2, MC_KEY_2 },
  224. { MULTICAST_3_ADDR, MC_APP_S_KEY_3, MC_NWK_S_KEY_3, MC_KEY_3 },
  225. { UNICAST_DEV_ADDR, APP_S_KEY, S_NWK_S_INT_KEY, NO_KEY }
  226. };
  227. /*
  228. * Local functions
  229. */
  230. /*
  231. * Encrypts the payload
  232. *
  233. * \param[IN] keyID - Key identifier
  234. * \param[IN] address - Address
  235. * \param[IN] dir - Frame direction ( Uplink or Downlink )
  236. * \param[IN] frameCounter - Frame counter
  237. * \param[IN] size - Size of data
  238. * \param[IN/OUT] buffer - Data buffer
  239. * \retval - Status of the operation
  240. */
  241. static LoRaMacCryptoStatus_t PayloadEncrypt( uint8_t* buffer, int16_t size, KeyIdentifier_t keyID, uint32_t address, uint8_t dir, uint32_t frameCounter )
  242. {
  243. if( buffer == 0 )
  244. {
  245. return LORAMAC_CRYPTO_ERROR_NPE;
  246. }
  247. uint8_t bufferIndex = 0;
  248. uint16_t ctr = 1;
  249. uint8_t sBlock[16] = { 0 };
  250. uint8_t aBlock[16] = { 0 };
  251. aBlock[0] = 0x01;
  252. aBlock[5] = dir;
  253. aBlock[6] = address & 0xFF;
  254. aBlock[7] = ( address >> 8 ) & 0xFF;
  255. aBlock[8] = ( address >> 16 ) & 0xFF;
  256. aBlock[9] = ( address >> 24 ) & 0xFF;
  257. aBlock[10] = frameCounter & 0xFF;
  258. aBlock[11] = ( frameCounter >> 8 ) & 0xFF;
  259. aBlock[12] = ( frameCounter >> 16 ) & 0xFF;
  260. aBlock[13] = ( frameCounter >> 24 ) & 0xFF;
  261. while( size > 0 )
  262. {
  263. aBlock[15] = ctr & 0xFF;
  264. ctr++;
  265. if( SecureElementAesEncrypt( aBlock, 16, keyID, sBlock ) != SECURE_ELEMENT_SUCCESS )
  266. {
  267. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  268. }
  269. for( uint8_t i = 0; i < ( ( size > 16 ) ? 16 : size ); i++ )
  270. {
  271. buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i];
  272. }
  273. size -= 16;
  274. bufferIndex += 16;
  275. }
  276. return LORAMAC_CRYPTO_SUCCESS;
  277. }
  278. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  279. /*
  280. * Encrypts the FOpts
  281. *
  282. * \param[IN] address - Address
  283. * \param[IN] dir - Frame direction ( Uplink or Downlink )
  284. * \param[IN] fCntID - Frame counter identifier
  285. * \param[IN] frameCounter - Frame counter
  286. * \param[IN] size - Size of data
  287. * \param[IN/OUT] buffer - Data buffer
  288. * \retval - Status of the operation
  289. */
  290. static LoRaMacCryptoStatus_t FOptsEncrypt( uint16_t size, uint32_t address, uint8_t dir, FCntIdentifier_t fCntID, uint32_t frameCounter, uint8_t* buffer )
  291. {
  292. if( buffer == 0 )
  293. {
  294. return LORAMAC_CRYPTO_ERROR_NPE;
  295. }
  296. uint8_t bufferIndex = 0;
  297. uint8_t sBlock[16] = { 0 };
  298. uint8_t aBlock[16] = { 0 };
  299. aBlock[0] = 0x01;
  300. if( CryptoCtx.NvmCtx->LrWanVersion.Value > 0x01010000 )
  301. {
  302. // Introduced in LoRaWAN 1.1.1 specification
  303. switch( fCntID )
  304. {
  305. case FCNT_UP:
  306. {
  307. aBlock[4] = 0x01;
  308. break;
  309. }
  310. case N_FCNT_DOWN:
  311. {
  312. aBlock[4] = 0x01;
  313. break;
  314. }
  315. case A_FCNT_DOWN:
  316. {
  317. aBlock[4] = 0x02;
  318. break;
  319. }
  320. default:
  321. return LORAMAC_CRYPTO_FAIL_PARAM;
  322. }
  323. }
  324. aBlock[5] = dir;
  325. aBlock[6] = address & 0xFF;
  326. aBlock[7] = ( address >> 8 ) & 0xFF;
  327. aBlock[8] = ( address >> 16 ) & 0xFF;
  328. aBlock[9] = ( address >> 24 ) & 0xFF;
  329. aBlock[10] = frameCounter & 0xFF;
  330. aBlock[11] = ( frameCounter >> 8 ) & 0xFF;
  331. aBlock[12] = ( frameCounter >> 16 ) & 0xFF;
  332. aBlock[13] = ( frameCounter >> 24 ) & 0xFF;
  333. if( CryptoCtx.NvmCtx->LrWanVersion.Value > 0x01010000 )
  334. {
  335. // Introduced in LoRaWAN 1.1.1 specification
  336. aBlock[15] = 0x01;
  337. }
  338. if( size > 0 )
  339. {
  340. if( SecureElementAesEncrypt( aBlock, 16, NWK_S_ENC_KEY, sBlock ) != SECURE_ELEMENT_SUCCESS )
  341. {
  342. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  343. }
  344. for( uint8_t i = 0; i < size; i++ )
  345. {
  346. buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i];
  347. }
  348. }
  349. return LORAMAC_CRYPTO_SUCCESS;
  350. }
  351. #endif
  352. /*
  353. * Prepares B0 block for cmac computation.
  354. *
  355. * \param[IN] msgLen - Length of message
  356. * \param[IN] keyID - Key identifier
  357. * \param[IN] isAck - True if it is a acknowledge frame ( Sets ConfFCnt in B0 block )
  358. * \param[IN] devAddr - Device address
  359. * \param[IN] dir - Frame direction ( Uplink:0, Downlink:1 )
  360. * \param[IN] fCnt - Frame counter
  361. * \param[IN/OUT] b0 - B0 block
  362. * \retval - Status of the operation
  363. */
  364. static LoRaMacCryptoStatus_t PrepareB0( uint16_t msgLen, KeyIdentifier_t keyID, bool isAck, uint8_t dir, uint32_t devAddr, uint32_t fCnt, uint8_t* b0 )
  365. {
  366. if( b0 == 0 )
  367. {
  368. return LORAMAC_CRYPTO_ERROR_NPE;
  369. }
  370. b0[0] = 0x49;
  371. if( ( isAck == true ) && ( dir == DOWNLINK ) )
  372. {
  373. // confFCnt contains the frame counter value modulo 2^16 of the "confirmed" uplink or downlink frame that is being acknowledged
  374. uint16_t confFCnt = 0;
  375. confFCnt = ( uint16_t )( CryptoCtx.NvmCtx->FCntList.FCntUp % 65536 );
  376. b0[1] = confFCnt & 0xFF;
  377. b0[2] = ( confFCnt >> 8 ) & 0xFF;
  378. }
  379. else
  380. {
  381. b0[1] = 0x00;
  382. b0[2] = 0x00;
  383. }
  384. b0[3] = 0x00;
  385. b0[4] = 0x00;
  386. b0[5] = dir;
  387. b0[6] = devAddr & 0xFF;
  388. b0[7] = ( devAddr >> 8 ) & 0xFF;
  389. b0[8] = ( devAddr >> 16 ) & 0xFF;
  390. b0[9] = ( devAddr >> 24 ) & 0xFF;
  391. b0[10] = fCnt & 0xFF;
  392. b0[11] = ( fCnt >> 8 ) & 0xFF;
  393. b0[12] = ( fCnt >> 16 ) & 0xFF;
  394. b0[13] = ( fCnt >> 24 ) & 0xFF;
  395. b0[14] = 0x00;
  396. b0[15] = msgLen & 0xFF;
  397. return LORAMAC_CRYPTO_SUCCESS;
  398. }
  399. /*
  400. * Computes cmac with adding B0 block in front.
  401. *
  402. * cmac = aes128_cmac(keyID, B0 | msg)
  403. *
  404. * \param[IN] msg - Message to compute the integrity code
  405. * \param[IN] len - Length of message
  406. * \param[IN] keyID - Key identifier
  407. * \param[IN] isAck - True if it is a acknowledge frame ( Sets ConfFCnt in B0 block )
  408. * \param[IN] devAddr - Device address
  409. * \param[IN] dir - Frame direction ( Uplink:0, Downlink:1 )
  410. * \param[IN] fCnt - Frame counter
  411. * \param[OUT] cmac - Computed cmac
  412. * \retval - Status of the operation
  413. */
  414. static LoRaMacCryptoStatus_t ComputeCmacB0( uint8_t* msg, uint16_t len, KeyIdentifier_t keyID, bool isAck, uint8_t dir, uint32_t devAddr, uint32_t fCnt, uint32_t* cmac )
  415. {
  416. if( ( msg == 0 ) || ( cmac == 0 ) )
  417. {
  418. return LORAMAC_CRYPTO_ERROR_NPE;
  419. }
  420. if( len > CRYPTO_MAXMESSAGE_SIZE )
  421. {
  422. return LORAMAC_CRYPTO_ERROR_BUF_SIZE;
  423. }
  424. uint8_t micBuff[MIC_BLOCK_BX_SIZE];
  425. // Initialize the first Block
  426. PrepareB0( len, keyID, isAck, dir, devAddr, fCnt, micBuff );
  427. if( SecureElementComputeAesCmac( micBuff, msg, len, keyID, cmac ) != SECURE_ELEMENT_SUCCESS )
  428. {
  429. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  430. }
  431. return LORAMAC_CRYPTO_SUCCESS;
  432. }
  433. /*!
  434. * Verifies cmac with adding B0 block in front.
  435. *
  436. * \param[IN] msg - Message to compute the integrity code
  437. * \param[IN] len - Length of message
  438. * \param[IN] keyID - Key identifier
  439. * \param[IN] isAck - True if it is a acknowledge frame ( Sets ConfFCnt in B0 block )
  440. * \param[IN] devAddr - Device address
  441. * \param[IN] dir - Frame direction ( Uplink:0, Downlink:1 )
  442. * \param[IN] fCnt - Frame counter
  443. * \param[in] expectedCmac - Expected cmac
  444. * \retval - Status of the operation
  445. */
  446. static LoRaMacCryptoStatus_t VerifyCmacB0( uint8_t* msg, uint16_t len, KeyIdentifier_t keyID, bool isAck, uint8_t dir, uint32_t devAddr, uint32_t fCnt, uint32_t expectedCmac )
  447. {
  448. if( msg == 0 )
  449. {
  450. return LORAMAC_CRYPTO_ERROR_NPE;
  451. }
  452. if( len > CRYPTO_MAXMESSAGE_SIZE )
  453. {
  454. return LORAMAC_CRYPTO_ERROR_BUF_SIZE;
  455. }
  456. uint8_t micBuff[CRYPTO_BUFFER_SIZE];
  457. memset1( micBuff, 0, CRYPTO_BUFFER_SIZE );
  458. // Initialize the first Block
  459. PrepareB0( len, keyID, isAck, dir, devAddr, fCnt, micBuff );
  460. // Copy the given data to the mic computation buffer
  461. memcpy1( ( micBuff + MIC_BLOCK_BX_SIZE ), msg, len );
  462. SecureElementStatus_t retval = SECURE_ELEMENT_ERROR;
  463. retval = SecureElementVerifyAesCmac( micBuff, ( len + MIC_BLOCK_BX_SIZE ), expectedCmac, keyID );
  464. if( retval == SECURE_ELEMENT_SUCCESS )
  465. {
  466. return LORAMAC_CRYPTO_SUCCESS;
  467. }
  468. else if( retval == SECURE_ELEMENT_FAIL_CMAC )
  469. {
  470. return LORAMAC_CRYPTO_FAIL_MIC;
  471. }
  472. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  473. }
  474. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  475. /*
  476. * Prpares B1 block for cmac computation.
  477. *
  478. * \param[IN] msgLen - Length of message
  479. * \param[IN] keyID - Key identifier
  480. * \param[IN] isAck - True if it is a acknowledge frame ( Sets ConfFCnt in B0 block )
  481. * \param[IN] txDr - Data rate used for the transmission
  482. * \param[IN] txCh - Index of the channel used for the transmission
  483. * \param[IN] devAddr - Device address
  484. * \param[IN] fCntUp - Frame counter
  485. * \param[IN/OUT] b0 - B0 block
  486. * \retval - Status of the operation
  487. */
  488. static LoRaMacCryptoStatus_t PrepareB1( uint16_t msgLen, KeyIdentifier_t keyID, bool isAck, uint8_t txDr, uint8_t txCh, uint32_t devAddr, uint32_t fCntUp, uint8_t* b1 )
  489. {
  490. if( b1 == 0 )
  491. {
  492. return LORAMAC_CRYPTO_ERROR_NPE;
  493. }
  494. b1[0] = 0x49;
  495. if( isAck == true )
  496. {
  497. // confFCnt contains the frame counter value modulo 2^16 of the "confirmed" uplink frame that is being acknowledged
  498. uint16_t confFCnt = ( uint16_t )( *CryptoCtx.NvmCtx->LastDownFCnt % 65536 );
  499. b1[1] = confFCnt & 0xFF;
  500. b1[2] = ( confFCnt >> 8 ) & 0xFF;
  501. }
  502. else
  503. {
  504. b1[1] = 0x00;
  505. b1[2] = 0x00;
  506. }
  507. b1[3] = txDr;
  508. b1[4] = txCh;
  509. b1[5] = UPLINK; // dir = Uplink
  510. b1[6] = devAddr & 0xFF;
  511. b1[7] = ( devAddr >> 8 ) & 0xFF;
  512. b1[8] = ( devAddr >> 16 ) & 0xFF;
  513. b1[9] = ( devAddr >> 24 ) & 0xFF;
  514. b1[10] = fCntUp & 0xFF;
  515. b1[11] = ( fCntUp >> 8 ) & 0xFF;
  516. b1[12] = ( fCntUp >> 16 ) & 0xFF;
  517. b1[13] = ( fCntUp >> 24 ) & 0xFF;
  518. b1[14] = 0x00;
  519. b1[15] = msgLen & 0xFF;
  520. return LORAMAC_CRYPTO_SUCCESS;
  521. }
  522. /*
  523. * Computes cmac with adding B1 block in front ( only for Uplink frames LoRaWAN 1.1 )
  524. *
  525. * cmac = aes128_cmac(keyID, B1 | msg)
  526. *
  527. * \param[IN] msg - Message to calculate the Integrity code
  528. * \param[IN] len - Length of message
  529. * \param[IN] keyID - Key identifier
  530. * \param[IN] isAck - True if it is a acknowledge frame ( Sets ConfFCnt in B0 block )
  531. * \param[IN] txDr - Data rate used for the transmission
  532. * \param[IN] txCh - Index of the channel used for the transmission
  533. * \param[IN] devAddr - Device address
  534. * \param[IN] fCntUp - Uplink Frame counter
  535. * \param[OUT] cmac - Computed cmac
  536. * \retval - Status of the operation
  537. */
  538. static LoRaMacCryptoStatus_t ComputeCmacB1( uint8_t* msg, uint16_t len, KeyIdentifier_t keyID, bool isAck, uint8_t txDr, uint8_t txCh, uint32_t devAddr, uint32_t fCntUp, uint32_t* cmac )
  539. {
  540. if( ( msg == 0 ) || ( cmac == 0 ) )
  541. {
  542. return LORAMAC_CRYPTO_ERROR_NPE;
  543. }
  544. if( len > CRYPTO_MAXMESSAGE_SIZE )
  545. {
  546. return LORAMAC_CRYPTO_ERROR_BUF_SIZE;
  547. }
  548. uint8_t micBuff[MIC_BLOCK_BX_SIZE];
  549. // Initialize the first Block
  550. PrepareB1( len, keyID, isAck, txDr, txCh, devAddr, fCntUp, micBuff );
  551. if( SecureElementComputeAesCmac( micBuff, msg, len, keyID, cmac ) != SECURE_ELEMENT_SUCCESS )
  552. {
  553. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  554. }
  555. return LORAMAC_CRYPTO_SUCCESS;
  556. }
  557. #endif
  558. /*
  559. * Gets security item from list.
  560. *
  561. * \param[IN] addrID - Address identifier
  562. * \param[OUT] keyItem - Key item reference
  563. * \retval - Status of the operation
  564. */
  565. static LoRaMacCryptoStatus_t GetKeyAddrItem( AddressIdentifier_t addrID, KeyAddr_t** item )
  566. {
  567. for( uint8_t i = 0; i < NUM_OF_SEC_CTX; i++ )
  568. {
  569. if( KeyAddrList[i].AddrID == addrID )
  570. {
  571. *item = &( KeyAddrList[i] );
  572. return LORAMAC_CRYPTO_SUCCESS;
  573. }
  574. }
  575. return LORAMAC_CRYPTO_ERROR_INVALID_ADDR_ID;
  576. }
  577. /*
  578. * Derives a session key as of LoRaWAN versions prior to 1.1.0
  579. *
  580. * \param[IN] keyID - Key Identifier for the key to be calculated
  581. * \param[IN] joinNonce - Sever nonce
  582. * \param[IN] netID - Network Identifier
  583. * \param[IN] deviceNonce - Device nonce
  584. * \retval - Status of the operation
  585. */
  586. static LoRaMacCryptoStatus_t DeriveSessionKey10x( KeyIdentifier_t keyID, uint8_t* joinNonce, uint8_t* netID, uint8_t* devNonce )
  587. {
  588. if( ( joinNonce == 0 ) || ( netID == 0 ) || ( devNonce == 0 ) )
  589. {
  590. return LORAMAC_CRYPTO_ERROR_NPE;
  591. }
  592. uint8_t compBase[16] = { 0 };
  593. switch( keyID )
  594. {
  595. case F_NWK_S_INT_KEY:
  596. case S_NWK_S_INT_KEY:
  597. case NWK_S_ENC_KEY:
  598. compBase[0] = 0x01;
  599. break;
  600. case APP_S_KEY:
  601. compBase[0] = 0x02;
  602. break;
  603. default:
  604. return LORAMAC_CRYPTO_ERROR_INVALID_KEY_ID;
  605. }
  606. memcpy1( compBase + 1, joinNonce, 3 );
  607. memcpy1( compBase + 4, netID, 3 );
  608. memcpy1( compBase + 7, devNonce, 2 );
  609. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBase, NWK_KEY, keyID ) != SECURE_ELEMENT_SUCCESS )
  610. {
  611. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  612. }
  613. return LORAMAC_CRYPTO_SUCCESS;
  614. }
  615. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  616. /*
  617. * Derives a session key as of LoRaWAN 1.1.0
  618. *
  619. * \param[IN] keyID - Key Identifier for the key to be calculated
  620. * \param[IN] joinNonce - Sever nonce
  621. * \param[IN] joinEUI - Join Server EUI
  622. * \param[IN] deviceNonce - Device nonce
  623. * \retval - Status of the operation
  624. */
  625. static LoRaMacCryptoStatus_t DeriveSessionKey11x( KeyIdentifier_t keyID, uint8_t* joinNonce, uint8_t* joinEUI, uint8_t* devNonce )
  626. {
  627. if( ( joinNonce == 0 ) || ( joinEUI == 0 ) || ( devNonce == 0 ) )
  628. {
  629. return LORAMAC_CRYPTO_ERROR_NPE;
  630. }
  631. uint8_t compBase[16] = { 0 };
  632. KeyIdentifier_t rootKeyId = NWK_KEY;
  633. switch( keyID )
  634. {
  635. case F_NWK_S_INT_KEY:
  636. compBase[0] = 0x01;
  637. break;
  638. case S_NWK_S_INT_KEY:
  639. compBase[0] = 0x03;
  640. break;
  641. case NWK_S_ENC_KEY:
  642. compBase[0] = 0x04;
  643. break;
  644. case APP_S_KEY:
  645. rootKeyId = APP_KEY;
  646. compBase[0] = 0x02;
  647. break;
  648. default:
  649. return LORAMAC_CRYPTO_ERROR_INVALID_KEY_ID;
  650. }
  651. memcpy1( compBase + 1, joinNonce, 3 );
  652. memcpyr( compBase + 4, joinEUI, 8 );
  653. memcpy1( compBase + 12, devNonce, 2 );
  654. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBase, rootKeyId, keyID ) != SECURE_ELEMENT_SUCCESS )
  655. {
  656. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  657. }
  658. return LORAMAC_CRYPTO_SUCCESS;
  659. }
  660. /*
  661. * Derives a life time session key (JSIntKey or JSEncKey) as of LoRaWAN 1.1.0
  662. *
  663. * \param[IN] keyID - Key Identifier for the key to be calculated
  664. * \param[IN] devEUI - Device EUI
  665. * \retval - Status of the operation
  666. */
  667. static LoRaMacCryptoStatus_t DeriveLifeTimeSessionKey( KeyIdentifier_t keyID, uint8_t* devEUI )
  668. {
  669. if( devEUI == 0 )
  670. {
  671. return LORAMAC_CRYPTO_ERROR_NPE;
  672. }
  673. uint8_t compBase[16] = { 0 };
  674. switch( keyID )
  675. {
  676. case J_S_INT_KEY:
  677. compBase[0] = 0x06;
  678. break;
  679. case J_S_ENC_KEY:
  680. compBase[0] = 0x05;
  681. break;
  682. default:
  683. return LORAMAC_CRYPTO_ERROR_INVALID_KEY_ID;
  684. }
  685. memcpyr( compBase + 1, devEUI, 8 );
  686. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBase, NWK_KEY, keyID ) != SECURE_ELEMENT_SUCCESS )
  687. {
  688. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  689. }
  690. return LORAMAC_CRYPTO_SUCCESS;
  691. }
  692. #endif
  693. /*
  694. * Gets the last received frame counter
  695. *
  696. * \param[IN] fCntID - Frame counter identifier
  697. * \param[IN] lastDown - Last downlink counter value
  698. *
  699. * \retval - Status of the operation
  700. */
  701. static LoRaMacCryptoStatus_t GetLastFcntDown( FCntIdentifier_t fCntID, uint32_t* lastDown )
  702. {
  703. if( lastDown == NULL )
  704. {
  705. return LORAMAC_CRYPTO_ERROR_NPE;
  706. }
  707. switch( fCntID )
  708. {
  709. case N_FCNT_DOWN:
  710. *lastDown = CryptoCtx.NvmCtx->FCntList.NFCntDown;
  711. CryptoCtx.NvmCtx->LastDownFCnt = &CryptoCtx.NvmCtx->FCntList.NFCntDown;
  712. break;
  713. case A_FCNT_DOWN:
  714. *lastDown = CryptoCtx.NvmCtx->FCntList.AFCntDown;
  715. CryptoCtx.NvmCtx->LastDownFCnt = &CryptoCtx.NvmCtx->FCntList.AFCntDown;
  716. break;
  717. case FCNT_DOWN:
  718. *lastDown = CryptoCtx.NvmCtx->FCntList.FCntDown;
  719. CryptoCtx.NvmCtx->LastDownFCnt = &CryptoCtx.NvmCtx->FCntList.FCntDown;
  720. break;
  721. case MC_FCNT_DOWN_0:
  722. *lastDown = CryptoCtx.NvmCtx->FCntList.McFCntDown0;
  723. break;
  724. case MC_FCNT_DOWN_1:
  725. *lastDown = CryptoCtx.NvmCtx->FCntList.McFCntDown1;
  726. break;
  727. case MC_FCNT_DOWN_2:
  728. *lastDown = CryptoCtx.NvmCtx->FCntList.McFCntDown2;
  729. break;
  730. case MC_FCNT_DOWN_3:
  731. *lastDown = CryptoCtx.NvmCtx->FCntList.McFCntDown3;
  732. break;
  733. default:
  734. return LORAMAC_CRYPTO_FAIL_FCNT_ID;
  735. }
  736. return LORAMAC_CRYPTO_SUCCESS;
  737. }
  738. /*
  739. * Checks the downlink counter value
  740. *
  741. * \param[IN] fCntID - Frame counter identifier
  742. * \param[IN] currentDown - Current downlink counter value
  743. *
  744. * \retval - Status of the operation
  745. */
  746. static bool CheckFCntDown( FCntIdentifier_t fCntID, uint32_t currentDown )
  747. {
  748. uint32_t lastDown = 0;
  749. if( GetLastFcntDown( fCntID, &lastDown ) != LORAMAC_CRYPTO_SUCCESS )
  750. {
  751. return false;
  752. }
  753. if( ( currentDown > lastDown ) ||
  754. // For LoRaWAN 1.0.X only. Allow downlink frames of 0
  755. ( lastDown == FCNT_DOWN_INITAL_VALUE ) )
  756. {
  757. return true;
  758. }
  759. else
  760. {
  761. return false;
  762. }
  763. }
  764. /*!
  765. * Updates the reference downlink counter
  766. *
  767. * \param[IN] fCntID - Frame counter identifier
  768. * \param[IN] currentDown - Current downlink counter value
  769. *
  770. * \retval - Status of the operation
  771. */
  772. static void UpdateFCntDown( FCntIdentifier_t fCntID, uint32_t currentDown )
  773. {
  774. switch( fCntID )
  775. {
  776. case N_FCNT_DOWN:
  777. CryptoCtx.NvmCtx->FCntList.NFCntDown = currentDown;
  778. break;
  779. case A_FCNT_DOWN:
  780. CryptoCtx.NvmCtx->FCntList.AFCntDown = currentDown;
  781. break;
  782. case FCNT_DOWN:
  783. CryptoCtx.NvmCtx->FCntList.FCntDown = currentDown;
  784. break;
  785. case MC_FCNT_DOWN_0:
  786. CryptoCtx.NvmCtx->FCntList.McFCntDown0 = currentDown;
  787. break;
  788. case MC_FCNT_DOWN_1:
  789. CryptoCtx.NvmCtx->FCntList.McFCntDown1 = currentDown;
  790. break;
  791. case MC_FCNT_DOWN_2:
  792. CryptoCtx.NvmCtx->FCntList.McFCntDown2 = currentDown;
  793. break;
  794. case MC_FCNT_DOWN_3:
  795. CryptoCtx.NvmCtx->FCntList.McFCntDown3 = currentDown;
  796. break;
  797. default:
  798. break;
  799. }
  800. CryptoCtx.EventCryptoNvmCtxChanged( );
  801. }
  802. /*!
  803. * Resets the frame counters
  804. */
  805. static void ResetFCnts( void )
  806. {
  807. CryptoCtx.NvmCtx->FCntList.FCntUp = 0;
  808. CryptoCtx.NvmCtx->FCntList.NFCntDown = FCNT_DOWN_INITAL_VALUE;
  809. CryptoCtx.NvmCtx->FCntList.AFCntDown = FCNT_DOWN_INITAL_VALUE;
  810. CryptoCtx.NvmCtx->FCntList.FCntDown = FCNT_DOWN_INITAL_VALUE;
  811. CryptoCtx.NvmCtx->LastDownFCnt = &CryptoCtx.NvmCtx->FCntList.FCntDown;
  812. CryptoCtx.NvmCtx->FCntList.McFCntDown0 = FCNT_DOWN_INITAL_VALUE;
  813. CryptoCtx.NvmCtx->FCntList.McFCntDown1 = FCNT_DOWN_INITAL_VALUE;
  814. CryptoCtx.NvmCtx->FCntList.McFCntDown2 = FCNT_DOWN_INITAL_VALUE;
  815. CryptoCtx.NvmCtx->FCntList.McFCntDown3 = FCNT_DOWN_INITAL_VALUE;
  816. CryptoCtx.EventCryptoNvmCtxChanged( );
  817. }
  818. /*
  819. * Dummy callback in case if the user provides NULL function pointer
  820. */
  821. static void DummyCB( void )
  822. {
  823. return;
  824. }
  825. /*
  826. * API functions
  827. */
  828. LoRaMacCryptoStatus_t LoRaMacCryptoInit( LoRaMacCryptoNvmEvent cryptoNvmCtxChanged )
  829. {
  830. // Assign non volatile context
  831. CryptoCtx.NvmCtx = &NvmCryptoCtx;
  832. // Assign callback
  833. if( cryptoNvmCtxChanged != 0 )
  834. {
  835. CryptoCtx.EventCryptoNvmCtxChanged = cryptoNvmCtxChanged;
  836. }
  837. else
  838. {
  839. CryptoCtx.EventCryptoNvmCtxChanged = DummyCB;
  840. }
  841. // Initialize with default
  842. memset1( (uint8_t*) CryptoCtx.NvmCtx, 0, sizeof( LoRaMacCryptoNvmCtx_t ) );
  843. // Set default LoRaWAN version
  844. CryptoCtx.NvmCtx->LrWanVersion.Fields.Major = 1;
  845. CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor = 1;
  846. CryptoCtx.NvmCtx->LrWanVersion.Fields.Revision = 1;
  847. CryptoCtx.NvmCtx->LrWanVersion.Fields.Rfu = 0;
  848. // Reset frame counters
  849. ResetFCnts( );
  850. return LORAMAC_CRYPTO_SUCCESS;
  851. }
  852. LoRaMacCryptoStatus_t LoRaMacCryptoSetLrWanVersion( Version_t version )
  853. {
  854. CryptoCtx.NvmCtx->LrWanVersion = version;
  855. return LORAMAC_CRYPTO_SUCCESS;
  856. }
  857. LoRaMacCryptoStatus_t LoRaMacCryptoRestoreNvmCtx( void* cryptoNvmCtx )
  858. {
  859. // Restore module context
  860. if( cryptoNvmCtx != 0 )
  861. {
  862. memcpy1( ( uint8_t* ) &NvmCryptoCtx, ( uint8_t* ) cryptoNvmCtx, CRYPTO_NVM_CTX_SIZE );
  863. return LORAMAC_CRYPTO_SUCCESS;
  864. }
  865. else
  866. {
  867. return LORAMAC_CRYPTO_ERROR_NPE;
  868. }
  869. }
  870. void* LoRaMacCryptoGetNvmCtx( size_t* cryptoNvmCtxSize )
  871. {
  872. *cryptoNvmCtxSize = CRYPTO_NVM_CTX_SIZE;
  873. return &NvmCryptoCtx;
  874. }
  875. LoRaMacCryptoStatus_t LoRaMacCryptoGetFCntUp( uint32_t* currentUp )
  876. {
  877. if( currentUp == NULL )
  878. {
  879. return LORAMAC_CRYPTO_ERROR_NPE;
  880. }
  881. *currentUp = CryptoCtx.NvmCtx->FCntList.FCntUp + 1;
  882. return LORAMAC_CRYPTO_SUCCESS;
  883. }
  884. LoRaMacCryptoStatus_t LoRaMacCryptoGetFCntDown( FCntIdentifier_t fCntID, uint16_t maxFCntGap, uint32_t frameFcnt, uint32_t* currentDown )
  885. {
  886. uint32_t lastDown = 0;
  887. int32_t fCntDiff = 0;
  888. LoRaMacCryptoStatus_t cryptoStatus = LORAMAC_CRYPTO_ERROR;
  889. if( currentDown == NULL )
  890. {
  891. return LORAMAC_CRYPTO_ERROR_NPE;
  892. }
  893. cryptoStatus = GetLastFcntDown( fCntID, &lastDown );
  894. if( cryptoStatus != LORAMAC_CRYPTO_SUCCESS )
  895. {
  896. return cryptoStatus;
  897. }
  898. // For LoRaWAN 1.0.X only, allow downlink frames of 0
  899. if( lastDown == FCNT_DOWN_INITAL_VALUE )
  900. {
  901. *currentDown = frameFcnt;
  902. }
  903. else
  904. {
  905. // Add difference, consider roll-over
  906. fCntDiff = ( int32_t )( ( int64_t )frameFcnt - ( int64_t )( lastDown & 0x0000FFFF ) );
  907. if( fCntDiff > 0 )
  908. { // Positive difference
  909. *currentDown = lastDown + fCntDiff;
  910. }
  911. else if( fCntDiff == 0 )
  912. { // Duplicate FCnt value, keep the current value.
  913. *currentDown = lastDown;
  914. return LORAMAC_CRYPTO_FAIL_FCNT_DUPLICATED;
  915. }
  916. else
  917. { // Negative difference, assume a roll-over of one uint16_t
  918. *currentDown = ( lastDown & 0xFFFF0000 ) + 0x10000 + frameFcnt;
  919. }
  920. }
  921. // For LoRaWAN 1.0.X only, check maxFCntGap
  922. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 0 )
  923. {
  924. if( ( ( int64_t )*currentDown - ( int64_t )lastDown ) >= maxFCntGap )
  925. {
  926. return LORAMAC_CRYPTO_FAIL_MAX_GAP_FCNT;
  927. }
  928. }
  929. return LORAMAC_CRYPTO_SUCCESS;
  930. }
  931. LoRaMacCryptoStatus_t LoRaMacCryptoSetMulticastReference( MulticastCtx_t* multicastList )
  932. {
  933. if( multicastList == NULL )
  934. {
  935. return LORAMAC_CRYPTO_ERROR_NPE;
  936. }
  937. multicastList[0].DownLinkCounter = &CryptoCtx.NvmCtx->FCntList.McFCntDown0;
  938. multicastList[1].DownLinkCounter = &CryptoCtx.NvmCtx->FCntList.McFCntDown1;
  939. multicastList[2].DownLinkCounter = &CryptoCtx.NvmCtx->FCntList.McFCntDown2;
  940. multicastList[3].DownLinkCounter = &CryptoCtx.NvmCtx->FCntList.McFCntDown3;
  941. return LORAMAC_CRYPTO_SUCCESS;
  942. }
  943. LoRaMacCryptoStatus_t LoRaMacCryptoSetKey( KeyIdentifier_t keyID, uint8_t* key )
  944. {
  945. if( SecureElementSetKey( keyID, key ) != SECURE_ELEMENT_SUCCESS )
  946. {
  947. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  948. }
  949. if( ( keyID == GEN_APP_KEY ) || ( keyID == APP_KEY ) )
  950. {
  951. // Derive lifetime keys
  952. if( LoRaMacCryptoDeriveMcRootKey( keyID ) != LORAMAC_CRYPTO_SUCCESS )
  953. {
  954. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  955. }
  956. if( LoRaMacCryptoDeriveMcKEKey( MC_ROOT_KEY ) != LORAMAC_CRYPTO_SUCCESS )
  957. {
  958. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  959. }
  960. }
  961. return LORAMAC_CRYPTO_SUCCESS;
  962. }
  963. LoRaMacCryptoStatus_t LoRaMacCryptoPrepareJoinRequest( LoRaMacMessageJoinRequest_t* macMsg )
  964. {
  965. if( macMsg == 0 )
  966. {
  967. return LORAMAC_CRYPTO_ERROR_NPE;
  968. }
  969. KeyIdentifier_t micComputationKeyID = NWK_KEY;
  970. // Add device nonce
  971. #if ( USE_RANDOM_DEV_NONCE == 1 )
  972. uint32_t devNonce = 0;
  973. SecureElementRandomNumber( &devNonce );
  974. CryptoCtx.NvmCtx->DevNonce = devNonce;
  975. #else
  976. CryptoCtx.NvmCtx->DevNonce++;
  977. #endif
  978. CryptoCtx.EventCryptoNvmCtxChanged( );
  979. macMsg->DevNonce = CryptoCtx.NvmCtx->DevNonce;
  980. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  981. // Derive lifetime session keys
  982. if( DeriveLifeTimeSessionKey( J_S_INT_KEY, macMsg->DevEUI ) != LORAMAC_CRYPTO_SUCCESS )
  983. {
  984. return LORAMAC_CRYPTO_ERROR;
  985. }
  986. if( DeriveLifeTimeSessionKey( J_S_ENC_KEY, macMsg->DevEUI ) != LORAMAC_CRYPTO_SUCCESS )
  987. {
  988. return LORAMAC_CRYPTO_ERROR;
  989. }
  990. #endif
  991. // Serialize message
  992. if( LoRaMacSerializerJoinRequest( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  993. {
  994. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  995. }
  996. // Compute mic
  997. if( SecureElementComputeAesCmac( NULL, macMsg->Buffer, ( LORAMAC_JOIN_REQ_MSG_SIZE - LORAMAC_MIC_FIELD_SIZE ), micComputationKeyID, &macMsg->MIC ) != SECURE_ELEMENT_SUCCESS )
  998. {
  999. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1000. }
  1001. // Reserialize message to add the MIC
  1002. if( LoRaMacSerializerJoinRequest( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1003. {
  1004. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1005. }
  1006. return LORAMAC_CRYPTO_SUCCESS;
  1007. }
  1008. LoRaMacCryptoStatus_t LoRaMacCryptoPrepareReJoinType1( LoRaMacMessageReJoinType1_t* macMsg )
  1009. {
  1010. if( macMsg == 0 )
  1011. {
  1012. return LORAMAC_CRYPTO_ERROR_NPE;
  1013. }
  1014. // Check for RJcount1 overflow
  1015. if( CryptoCtx.NvmCtx->RJcount1 == 65535 )
  1016. {
  1017. return LORAMAC_CRYPTO_ERROR_RJCOUNT1_OVERFLOW;
  1018. }
  1019. // Serialize message
  1020. if( LoRaMacSerializerReJoinType1( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1021. {
  1022. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1023. }
  1024. // Compute mic
  1025. // cmac = aes128_cmac(JSIntKey, MHDR | RejoinType | JoinEUI| DevEUI | RJcount1)
  1026. if( SecureElementComputeAesCmac( NULL, macMsg->Buffer, ( LORAMAC_RE_JOIN_1_MSG_SIZE - LORAMAC_MIC_FIELD_SIZE ), J_S_INT_KEY, &macMsg->MIC ) != SECURE_ELEMENT_SUCCESS )
  1027. {
  1028. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1029. }
  1030. // Reserialize message to add the MIC
  1031. if( LoRaMacSerializerReJoinType1( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1032. {
  1033. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1034. }
  1035. // Increment RJcount1
  1036. CryptoCtx.NvmCtx->RJcount1++;
  1037. CryptoCtx.EventCryptoNvmCtxChanged( );
  1038. return LORAMAC_CRYPTO_SUCCESS;
  1039. }
  1040. LoRaMacCryptoStatus_t LoRaMacCryptoPrepareReJoinType0or2( LoRaMacMessageReJoinType0or2_t* macMsg )
  1041. {
  1042. if( macMsg == 0 )
  1043. {
  1044. return LORAMAC_CRYPTO_ERROR_NPE;
  1045. }
  1046. // Check for RJcount0 overflow
  1047. if( CryptoCtx.RJcount0 == 65535 )
  1048. {
  1049. return LORAMAC_CRYPTO_FAIL_RJCOUNT0_OVERFLOW;
  1050. }
  1051. // Serialize message
  1052. if( LoRaMacSerializerReJoinType0or2( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1053. {
  1054. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1055. }
  1056. // Compute mic
  1057. // cmac = aes128_cmac(SNwkSIntKey, MHDR | Rejoin Type | NetID | DevEUI | RJcount0)
  1058. if( SecureElementComputeAesCmac( NULL, macMsg->Buffer, ( LORAMAC_RE_JOIN_0_2_MSG_SIZE - LORAMAC_MIC_FIELD_SIZE ), S_NWK_S_INT_KEY, &macMsg->MIC ) != SECURE_ELEMENT_SUCCESS )
  1059. {
  1060. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1061. }
  1062. // Reserialize message to add the MIC
  1063. if( LoRaMacSerializerReJoinType0or2( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1064. {
  1065. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1066. }
  1067. // Increment RJcount0
  1068. CryptoCtx.RJcount0++;
  1069. return LORAMAC_CRYPTO_SUCCESS;
  1070. }
  1071. LoRaMacCryptoStatus_t LoRaMacCryptoHandleJoinAccept( JoinReqIdentifier_t joinReqType, uint8_t* joinEUI, LoRaMacMessageJoinAccept_t* macMsg )
  1072. {
  1073. if( ( macMsg == 0 ) || ( joinEUI == 0 ) )
  1074. {
  1075. return LORAMAC_CRYPTO_ERROR_NPE;
  1076. }
  1077. LoRaMacCryptoStatus_t retval = LORAMAC_CRYPTO_ERROR;
  1078. KeyIdentifier_t micComputationKeyID;
  1079. KeyIdentifier_t encryptionKeyID;
  1080. uint8_t micComputationOffset = 0;
  1081. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1082. uint8_t* devNonceForKeyDerivation = ( uint8_t* ) &CryptoCtx.NvmCtx->DevNonce;
  1083. #endif
  1084. // Determine decryption key and DevNonce for key derivation
  1085. if( joinReqType == JOIN_REQ )
  1086. {
  1087. encryptionKeyID = NWK_KEY;
  1088. micComputationOffset = CRYPTO_MIC_COMPUTATION_OFFSET;
  1089. }
  1090. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1091. else
  1092. {
  1093. encryptionKeyID = J_S_ENC_KEY;
  1094. // If Join-accept is a reply to a rejoin, the RJcount(0 or 1) replaces DevNonce in the key derivation process.
  1095. if( ( joinReqType == REJOIN_REQ_0 ) || ( joinReqType == REJOIN_REQ_2 ) )
  1096. {
  1097. devNonceForKeyDerivation = ( uint8_t* ) &CryptoCtx.RJcount0;
  1098. }
  1099. else
  1100. {
  1101. devNonceForKeyDerivation = ( uint8_t* ) &CryptoCtx.NvmCtx->RJcount1;
  1102. }
  1103. }
  1104. #endif
  1105. // Decrypt header, skip MHDR
  1106. uint8_t procBuffer[CRYPTO_MAXMESSAGE_SIZE + CRYPTO_MIC_COMPUTATION_OFFSET];
  1107. memset1( procBuffer, 0, ( macMsg->BufSize + micComputationOffset ) );
  1108. if( SecureElementAesEncrypt( macMsg->Buffer + LORAMAC_MHDR_FIELD_SIZE, ( macMsg->BufSize - LORAMAC_MHDR_FIELD_SIZE ), encryptionKeyID, ( procBuffer + micComputationOffset ) ) != SECURE_ELEMENT_SUCCESS )
  1109. {
  1110. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1111. }
  1112. // Copy the result to an offset location to keep space for additional information which have to be added in case of 1.1 and later
  1113. memcpy1( macMsg->Buffer + LORAMAC_MHDR_FIELD_SIZE, ( procBuffer + micComputationOffset ), ( macMsg->BufSize - LORAMAC_MHDR_FIELD_SIZE ) );
  1114. // Parse the message
  1115. if( LoRaMacParserJoinAccept( macMsg ) != LORAMAC_PARSER_SUCCESS )
  1116. {
  1117. return LORAMAC_CRYPTO_ERROR_PARSER;
  1118. }
  1119. // Is it a LoRaWAN 1.1.0 or later ?
  1120. if( macMsg->DLSettings.Bits.OptNeg == 1 )
  1121. {
  1122. CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor = 1;
  1123. micComputationKeyID = J_S_INT_KEY;
  1124. }
  1125. else
  1126. {
  1127. CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor = 0;
  1128. micComputationKeyID = NWK_KEY;
  1129. }
  1130. // Verify mic
  1131. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 0 )
  1132. {
  1133. // For legacy mode :
  1134. // cmac = aes128_cmac(NwkKey, MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList | CFListType)
  1135. if( SecureElementVerifyAesCmac( macMsg->Buffer, ( macMsg->BufSize - LORAMAC_MIC_FIELD_SIZE ), macMsg->MIC, micComputationKeyID ) != SECURE_ELEMENT_SUCCESS )
  1136. {
  1137. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1138. }
  1139. }
  1140. else
  1141. {
  1142. // For 1.1 and later:
  1143. // cmac = aes128_cmac(JSIntKey, JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList | CFListType)
  1144. // Prepare the msg for integrity check (adding JoinReqType, JoinEUI and DevNonce)
  1145. uint16_t bufItr = 0;
  1146. procBuffer[bufItr++] = ( uint8_t ) joinReqType;
  1147. memcpyr( &procBuffer[bufItr], joinEUI, LORAMAC_JOIN_EUI_FIELD_SIZE );
  1148. bufItr += LORAMAC_JOIN_EUI_FIELD_SIZE;
  1149. procBuffer[bufItr++] = CryptoCtx.NvmCtx->DevNonce & 0xFF;
  1150. procBuffer[bufItr++] = ( CryptoCtx.NvmCtx->DevNonce >> 8 ) & 0xFF;
  1151. procBuffer[bufItr++] = macMsg->MHDR.Value;
  1152. if( SecureElementVerifyAesCmac( procBuffer, ( macMsg->BufSize + micComputationOffset - LORAMAC_MHDR_FIELD_SIZE - LORAMAC_MIC_FIELD_SIZE ), macMsg->MIC, micComputationKeyID ) != SECURE_ELEMENT_SUCCESS )
  1153. {
  1154. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1155. }
  1156. // Check if the JoinNonce is greater as the previous one
  1157. uint32_t currentJoinNonce = 0;
  1158. currentJoinNonce = ( uint32_t ) macMsg->JoinNonce[0];
  1159. currentJoinNonce |= ( ( uint32_t ) macMsg->JoinNonce[1] << 8 );
  1160. currentJoinNonce |= ( ( uint32_t ) macMsg->JoinNonce[2] << 16 );
  1161. if( currentJoinNonce > CryptoCtx.NvmCtx->JoinNonce )
  1162. {
  1163. CryptoCtx.NvmCtx->JoinNonce = currentJoinNonce;
  1164. CryptoCtx.EventCryptoNvmCtxChanged( );
  1165. }
  1166. else
  1167. {
  1168. return LORAMAC_CRYPTO_FAIL_JOIN_NONCE;
  1169. }
  1170. }
  1171. // Derive session keys
  1172. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1173. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 )
  1174. {
  1175. // Derive lifetime keys
  1176. retval = LoRaMacCryptoDeriveMcRootKey( APP_KEY );
  1177. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1178. {
  1179. return retval;
  1180. }
  1181. retval = LoRaMacCryptoDeriveMcKEKey( MC_ROOT_KEY );
  1182. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1183. {
  1184. return retval;
  1185. }
  1186. retval = DeriveSessionKey11x( F_NWK_S_INT_KEY, macMsg->JoinNonce, joinEUI, devNonceForKeyDerivation );
  1187. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1188. {
  1189. return retval;
  1190. }
  1191. retval = DeriveSessionKey11x( S_NWK_S_INT_KEY, macMsg->JoinNonce, joinEUI, devNonceForKeyDerivation );
  1192. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1193. {
  1194. return retval;
  1195. }
  1196. retval = DeriveSessionKey11x( NWK_S_ENC_KEY, macMsg->JoinNonce, joinEUI, devNonceForKeyDerivation );
  1197. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1198. {
  1199. return retval;
  1200. }
  1201. retval = DeriveSessionKey11x( APP_S_KEY, macMsg->JoinNonce, joinEUI, devNonceForKeyDerivation );
  1202. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1203. {
  1204. return retval;
  1205. }
  1206. }
  1207. else
  1208. #endif
  1209. {
  1210. // prior LoRaWAN 1.1.0
  1211. retval = LoRaMacCryptoDeriveMcRootKey( GEN_APP_KEY );
  1212. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1213. {
  1214. return retval;
  1215. }
  1216. retval = LoRaMacCryptoDeriveMcKEKey( MC_ROOT_KEY );
  1217. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1218. {
  1219. return retval;
  1220. }
  1221. retval = DeriveSessionKey10x( APP_S_KEY, macMsg->JoinNonce, macMsg->NetID, ( uint8_t* ) &CryptoCtx.NvmCtx->DevNonce );
  1222. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1223. {
  1224. return retval;
  1225. }
  1226. retval = DeriveSessionKey10x( NWK_S_ENC_KEY, macMsg->JoinNonce, macMsg->NetID, ( uint8_t* ) &CryptoCtx.NvmCtx->DevNonce );
  1227. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1228. {
  1229. return retval;
  1230. }
  1231. retval = DeriveSessionKey10x( F_NWK_S_INT_KEY, macMsg->JoinNonce, macMsg->NetID, ( uint8_t* ) &CryptoCtx.NvmCtx->DevNonce );
  1232. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1233. {
  1234. return retval;
  1235. }
  1236. retval = DeriveSessionKey10x( S_NWK_S_INT_KEY, macMsg->JoinNonce, macMsg->NetID, ( uint8_t* ) &CryptoCtx.NvmCtx->DevNonce );
  1237. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1238. {
  1239. return retval;
  1240. }
  1241. }
  1242. // Join-Accept is successfully processed, reset frame counters
  1243. CryptoCtx.RJcount0 = 0;
  1244. CryptoCtx.NvmCtx->FCntList.FCntUp = 0;
  1245. CryptoCtx.NvmCtx->FCntList.FCntDown = FCNT_DOWN_INITAL_VALUE;
  1246. CryptoCtx.NvmCtx->FCntList.NFCntDown = FCNT_DOWN_INITAL_VALUE;
  1247. CryptoCtx.NvmCtx->FCntList.AFCntDown = FCNT_DOWN_INITAL_VALUE;
  1248. CryptoCtx.EventCryptoNvmCtxChanged( );
  1249. return LORAMAC_CRYPTO_SUCCESS;
  1250. }
  1251. LoRaMacCryptoStatus_t LoRaMacCryptoSecureMessage( uint32_t fCntUp, uint8_t txDr, uint8_t txCh, LoRaMacMessageData_t* macMsg )
  1252. {
  1253. LoRaMacCryptoStatus_t retval = LORAMAC_CRYPTO_ERROR;
  1254. KeyIdentifier_t payloadDecryptionKeyID = APP_S_KEY;
  1255. if( macMsg == NULL )
  1256. {
  1257. return LORAMAC_CRYPTO_ERROR_NPE;
  1258. }
  1259. if( fCntUp < CryptoCtx.NvmCtx->FCntList.FCntUp )
  1260. {
  1261. return LORAMAC_CRYPTO_FAIL_FCNT_SMALLER;
  1262. }
  1263. // Encrypt payload
  1264. if( macMsg->FPort == 0 )
  1265. {
  1266. // Use network session key
  1267. payloadDecryptionKeyID = NWK_S_ENC_KEY;
  1268. }
  1269. if( fCntUp > CryptoCtx.NvmCtx->FCntList.FCntUp )
  1270. {
  1271. retval = PayloadEncrypt( macMsg->FRMPayload, macMsg->FRMPayloadSize, payloadDecryptionKeyID, macMsg->FHDR.DevAddr, UPLINK, fCntUp );
  1272. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1273. {
  1274. return retval;
  1275. }
  1276. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1277. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 )
  1278. {
  1279. // Encrypt FOpts
  1280. retval = FOptsEncrypt( macMsg->FHDR.FCtrl.Bits.FOptsLen, macMsg->FHDR.DevAddr, UPLINK, FCNT_UP, fCntUp, macMsg->FHDR.FOpts );
  1281. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1282. {
  1283. return retval;
  1284. }
  1285. }
  1286. #endif
  1287. }
  1288. CryptoCtx.NvmCtx->FCntList.FCntUp = fCntUp;
  1289. CryptoCtx.EventCryptoNvmCtxChanged( );
  1290. // Serialize message
  1291. if( LoRaMacSerializerData( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1292. {
  1293. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1294. }
  1295. // Compute mic
  1296. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1297. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 )
  1298. {
  1299. uint32_t cmacS = 0;
  1300. uint32_t cmacF = 0;
  1301. // cmacS = aes128_cmac(SNwkSIntKey, B1 | msg)
  1302. retval = ComputeCmacB1( macMsg->Buffer, ( macMsg->BufSize - LORAMAC_MIC_FIELD_SIZE ), S_NWK_S_INT_KEY, macMsg->FHDR.FCtrl.Bits.Ack, txDr, txCh, macMsg->FHDR.DevAddr, fCntUp, &cmacS );
  1303. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1304. {
  1305. return retval;
  1306. }
  1307. //cmacF = aes128_cmac(FNwkSIntKey, B0 | msg)
  1308. retval = ComputeCmacB0( macMsg->Buffer, ( macMsg->BufSize - LORAMAC_MIC_FIELD_SIZE ), F_NWK_S_INT_KEY, macMsg->FHDR.FCtrl.Bits.Ack, UPLINK, macMsg->FHDR.DevAddr, fCntUp, &cmacF );
  1309. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1310. {
  1311. return retval;
  1312. }
  1313. // MIC = cmacS[0..1] | cmacF[0..1]
  1314. macMsg->MIC = ( ( cmacF << 16 ) & 0xFFFF0000 ) | ( cmacS & 0x0000FFFF );
  1315. }
  1316. else
  1317. #endif
  1318. {
  1319. // MIC = cmacF[0..3]
  1320. // The IsAck parameter is every time false since the ConfFCnt field is not used in legacy mode.
  1321. retval = ComputeCmacB0( macMsg->Buffer, ( macMsg->BufSize - LORAMAC_MIC_FIELD_SIZE ), NWK_S_ENC_KEY, false, UPLINK, macMsg->FHDR.DevAddr, fCntUp, &macMsg->MIC );
  1322. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1323. {
  1324. return retval;
  1325. }
  1326. }
  1327. // Re-serialize message to add the MIC
  1328. if( LoRaMacSerializerData( macMsg ) != LORAMAC_SERIALIZER_SUCCESS )
  1329. {
  1330. return LORAMAC_CRYPTO_ERROR_SERIALIZER;
  1331. }
  1332. return LORAMAC_CRYPTO_SUCCESS;
  1333. }
  1334. LoRaMacCryptoStatus_t LoRaMacCryptoUnsecureMessage( AddressIdentifier_t addrID, uint32_t address, FCntIdentifier_t fCntID, uint32_t fCntDown, LoRaMacMessageData_t* macMsg )
  1335. {
  1336. if( macMsg == 0 )
  1337. {
  1338. return LORAMAC_CRYPTO_ERROR_NPE;
  1339. }
  1340. if( CheckFCntDown( fCntID, fCntDown ) == false )
  1341. {
  1342. return LORAMAC_CRYPTO_FAIL_FCNT_SMALLER;
  1343. }
  1344. LoRaMacCryptoStatus_t retval = LORAMAC_CRYPTO_ERROR;
  1345. KeyIdentifier_t payloadDecryptionKeyID = APP_S_KEY;
  1346. KeyIdentifier_t micComputationKeyID = S_NWK_S_INT_KEY;
  1347. KeyAddr_t* curItem;
  1348. // Parse the message
  1349. if( LoRaMacParserData( macMsg ) != LORAMAC_PARSER_SUCCESS )
  1350. {
  1351. return LORAMAC_CRYPTO_ERROR_PARSER;
  1352. }
  1353. // Determine current security context
  1354. retval = GetKeyAddrItem( addrID, &curItem );
  1355. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1356. {
  1357. return retval;
  1358. }
  1359. payloadDecryptionKeyID = curItem->AppSkey;
  1360. micComputationKeyID = curItem->NwkSkey;
  1361. // Check if it is our address
  1362. if( address != macMsg->FHDR.DevAddr )
  1363. {
  1364. return LORAMAC_CRYPTO_FAIL_ADDRESS;
  1365. }
  1366. // Compute mic
  1367. bool isAck = macMsg->FHDR.FCtrl.Bits.Ack;
  1368. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 0 )
  1369. {
  1370. // In legacy mode the IsAck parameter is forced to be false since the ConfFCnt field is not used.
  1371. isAck = false;
  1372. }
  1373. // Verify mic
  1374. retval = VerifyCmacB0( macMsg->Buffer, ( macMsg->BufSize - LORAMAC_MIC_FIELD_SIZE ), micComputationKeyID, isAck, DOWNLINK, address, fCntDown, macMsg->MIC );
  1375. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1376. {
  1377. return retval;
  1378. }
  1379. // Decrypt payload
  1380. if( macMsg->FPort == 0 )
  1381. {
  1382. // Use network session encryption key
  1383. payloadDecryptionKeyID = NWK_S_ENC_KEY;
  1384. }
  1385. retval = PayloadEncrypt( macMsg->FRMPayload, macMsg->FRMPayloadSize, payloadDecryptionKeyID, address, DOWNLINK, fCntDown );
  1386. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1387. {
  1388. return retval;
  1389. }
  1390. #if( USE_LRWAN_1_1_X_CRYPTO == 1 )
  1391. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 )
  1392. {
  1393. // Decrypt FOpts
  1394. retval = FOptsEncrypt( macMsg->FHDR.FCtrl.Bits.FOptsLen, address, DOWNLINK, fCntID, fCntDown, macMsg->FHDR.FOpts );
  1395. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1396. {
  1397. return retval;
  1398. }
  1399. }
  1400. #endif
  1401. UpdateFCntDown( fCntID, fCntDown );
  1402. return LORAMAC_CRYPTO_SUCCESS;
  1403. }
  1404. LoRaMacCryptoStatus_t LoRaMacCryptoDeriveMcRootKey( KeyIdentifier_t keyID )
  1405. {
  1406. // Prevent other keys than GenAppKey for LoRaWAN 1.0.x or AppKey for LoRaWAN 1.1 or later
  1407. if( ( ( keyID == APP_KEY ) && ( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 0 ) ) ||
  1408. ( ( keyID == GEN_APP_KEY ) && ( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 ) ) )
  1409. {
  1410. return LORAMAC_CRYPTO_ERROR_INVALID_KEY_ID;
  1411. }
  1412. uint8_t compBase[16] = { 0 };
  1413. if( CryptoCtx.NvmCtx->LrWanVersion.Fields.Minor == 1 )
  1414. {
  1415. compBase[0] = 0x20;
  1416. }
  1417. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBase, keyID, MC_ROOT_KEY ) != SECURE_ELEMENT_SUCCESS )
  1418. {
  1419. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1420. }
  1421. return LORAMAC_CRYPTO_SUCCESS;
  1422. }
  1423. LoRaMacCryptoStatus_t LoRaMacCryptoDeriveMcKEKey( KeyIdentifier_t keyID )
  1424. {
  1425. // Prevent other keys than McRootKey
  1426. if( keyID != MC_ROOT_KEY )
  1427. {
  1428. return LORAMAC_CRYPTO_ERROR_INVALID_KEY_ID;
  1429. }
  1430. uint8_t compBase[16] = { 0 };
  1431. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBase, keyID, MC_KE_KEY ) != SECURE_ELEMENT_SUCCESS )
  1432. {
  1433. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1434. }
  1435. return LORAMAC_CRYPTO_SUCCESS;
  1436. }
  1437. LoRaMacCryptoStatus_t LoRaMacCryptoDeriveMcSessionKeyPair( AddressIdentifier_t addrID, uint32_t mcAddr )
  1438. {
  1439. if( mcAddr == 0 )
  1440. {
  1441. return LORAMAC_CRYPTO_ERROR_NPE;
  1442. }
  1443. LoRaMacCryptoStatus_t retval = LORAMAC_CRYPTO_ERROR;
  1444. // Determine current security context
  1445. KeyAddr_t* curItem;
  1446. retval = GetKeyAddrItem( addrID, &curItem );
  1447. if( retval != LORAMAC_CRYPTO_SUCCESS )
  1448. {
  1449. return retval;
  1450. }
  1451. //McAppSKey = aes128_encrypt(McKey, 0x01 | McAddr | pad16)
  1452. //McNwkSKey = aes128_encrypt(McKey, 0x02 | McAddr | pad16)
  1453. uint8_t compBaseAppS[16] = { 0 };
  1454. uint8_t compBaseNwkS[16] = { 0 };
  1455. compBaseAppS[0] = 0x01;
  1456. compBaseAppS[1] = mcAddr & 0xFF;
  1457. compBaseAppS[2] = ( mcAddr >> 8 ) & 0xFF;
  1458. compBaseAppS[3] = ( mcAddr >> 16 ) & 0xFF;
  1459. compBaseAppS[4] = ( mcAddr >> 24 ) & 0xFF;
  1460. compBaseNwkS[0] = 0x02;
  1461. compBaseNwkS[1] = mcAddr & 0xFF;
  1462. compBaseNwkS[2] = ( mcAddr >> 8 ) & 0xFF;
  1463. compBaseNwkS[3] = ( mcAddr >> 16 ) & 0xFF;
  1464. compBaseNwkS[4] = ( mcAddr >> 24 ) & 0xFF;
  1465. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBaseAppS, curItem->RootKey, curItem->AppSkey ) != SECURE_ELEMENT_SUCCESS )
  1466. {
  1467. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1468. }
  1469. if( SecureElementDeriveAndStoreKey( CryptoCtx.NvmCtx->LrWanVersion, compBaseNwkS, curItem->RootKey, curItem->NwkSkey ) != SECURE_ELEMENT_SUCCESS )
  1470. {
  1471. return LORAMAC_CRYPTO_ERROR_SECURE_ELEMENT_FUNC;
  1472. }
  1473. return LORAMAC_CRYPTO_SUCCESS;
  1474. }