zcl_key_establish.c 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. /******************************************************************************
  2. Filename: zcl_key_establish.c
  3. Revised: $Date: 2012-04-02 17:02:19 -0700 (Mon, 02 Apr 2012) $
  4. Revision: $Revision: 29996 $
  5. Description: Zigbee Cluster Library - General Function Domain - key
  6. establishment cluster.
  7. This application receives ZCL messages and handles them
  8. within the ZCL layer, without passing to application.
  9. Copyright 2007-2012 Texas Instruments Incorporated. All rights reserved.
  10. IMPORTANT: Your use of this Software is limited to those specific rights
  11. granted under the terms of a software license agreement between the user
  12. who downloaded the software, his/her employer (which must be your employer)
  13. and Texas Instruments Incorporated (the "License"). You may not use this
  14. Software unless you agree to abide by the terms of the License. The License
  15. limits your use, and you acknowledge, that the Software may not be modified,
  16. copied or distributed unless embedded on a Texas Instruments microcontroller
  17. or used solely and exclusively in conjunction with a Texas Instruments radio
  18. frequency transceiver, which is integrated into your product. Other than for
  19. the foregoing purpose, you may not use, reproduce, copy, prepare derivative
  20. works of, modify, distribute, perform, display or sell this Software and/or
  21. its documentation for any purpose.
  22. YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
  23. PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  24. INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
  25. NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
  26. TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
  27. NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
  28. LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
  29. INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
  30. OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
  31. OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
  32. (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
  33. Should you have any questions regarding your right to use this Software,
  34. contact Texas Instruments Incorporated at www.TI.com.
  35. ******************************************************************************/
  36. /*********************************************************************
  37. * INCLUDES
  38. */
  39. #include "ZComDef.h"
  40. #include "OSAL.h"
  41. #include "OSAL_Nv.h"
  42. #include "zcl.h"
  43. #include "ZDApp.h"
  44. #include "ssp_hash.h"
  45. #include "AddrMgr.h"
  46. #include "ZDSecMgr.h"
  47. #include "APSMEDE.h"
  48. #include "eccapi.h"
  49. #include "zcl_key_establish.h"
  50. #include "DebugTrace.h"
  51. #include "se.h"
  52. #if defined ( INTER_PAN )
  53. #include "stub_aps.h"
  54. #endif
  55. /*********************************************************************
  56. * MACROS
  57. */
  58. /*********************************************************************
  59. * CONSTANTS
  60. */
  61. #define KEY_ESTABLISHMENT_DEVICE_VERSION 0
  62. #define KEY_ESTABLISHMENT_FLAGS 0
  63. #define KEY_ESTABLISHMENT_SUITE 1 // For CBKE with ECMQV
  64. #define KEY_ESTABLISHMENT_AVG_TIMEOUT ( 2 * ( ZCL_KEY_ESTABLISHMENT_KEY_GENERATE_TIMEOUT + \
  65. ZCL_KEY_ESTABLISHMENT_MAC_GENERATE_TIMEOUT ) )
  66. #define ZCL_KEY_ESTABLISH_DEVICE_VERSION 0
  67. #define ZCL_KEY_ESTABLISH_FLAGS 0
  68. #define INVALID_TASK_ID 0xFF
  69. /*********************************************************************
  70. * TYPEDEFS
  71. */
  72. /*********************************************************************
  73. * GLOBAL VARIABLES
  74. */
  75. // For debug and testing purpose, use a fixed ephermeral key pair instead
  76. // of the randomly generated one.
  77. #if defined (DEBUG_STATIC_ECC)
  78. uint8 public1[22] = {
  79. 0x03, 0x06, 0xAB, 0x52, 0x06, 0x22, 0x01, 0xD9,
  80. 0x95, 0xB8, 0xB8, 0x59, 0x1F, 0x3F, 0x08, 0x6A,
  81. 0x3A, 0x2E, 0x21, 0x4D, 0x84, 0x5E
  82. };
  83. uint8 private1[21] = {
  84. 0x03, 0xD4, 0x8C, 0x72, 0x10, 0xDD, 0xBC, 0xC4,
  85. 0xFB, 0x2E, 0x5E, 0x7A, 0x0A, 0xA1, 0x6A, 0x0D,
  86. 0xB8, 0x95, 0x40, 0x82, 0x0B
  87. };
  88. uint8 public2[22] = {
  89. 0x03, 0x00, 0xE1, 0x17, 0xC8, 0x6D, 0x0E, 0x7C,
  90. 0xD1, 0x28, 0xB2, 0xF3, 0x4E, 0x90, 0x76, 0xCF,
  91. 0xF2, 0x4A, 0xF4, 0x6D, 0x72, 0x88
  92. };
  93. uint8 private2[21] = {
  94. 0x00, 0x13, 0xD3, 0x6D, 0xE4, 0xB1, 0xEA, 0x8E,
  95. 0x22, 0x73, 0x9C, 0x38, 0x13, 0x70, 0x82, 0x3F,
  96. 0x40, 0x4B, 0xFF, 0x88, 0x62
  97. };
  98. #endif
  99. zclOptionRec_t zclKeyEstablish_Options[1] =
  100. {
  101. {
  102. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  103. ( AF_ACK_REQUEST ),
  104. },
  105. };
  106. YieldFunc *zclKeyEstablish_YieldFunc = NULL;
  107. uint8 zclKeyEstablish_YieldLevel = 0;
  108. #if defined (NWK_AUTO_POLL)
  109. uint16 zclSavedPollRate = POLL_RATE;
  110. #endif
  111. /*********************************************************************
  112. * GLOBAL FUNCTIONS
  113. */
  114. extern uint8* SSP_MemCpyReverse( uint8* dst, uint8* src, unsigned int len );
  115. /*********************************************************************
  116. * LOCAL VARIABLES
  117. */
  118. #if defined(ZCL_KEY_ESTABLISH)
  119. static uint8 zcl_KeyEstablishment_TaskID; // Task ID of the key Establishment cluster
  120. #endif
  121. /*********************************************************************
  122. * SIMPLE DESCRIPTOR
  123. */
  124. // This is the Cluster ID List and should be filled with Application
  125. // specific cluster IDs.
  126. #define ZCL_KEY_ESTABLISH_MAX_INCLUSTERS 1
  127. const cId_t zclKeyEstablish_InClusterList[ZCL_KEY_ESTABLISH_MAX_INCLUSTERS] =
  128. {
  129. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  130. };
  131. #define ZCL_KEY_ESTABLISH_MAX_OUTCLUSTERS 1
  132. const cId_t zclKeyEstablish_OutClusterList[ZCL_KEY_ESTABLISH_MAX_OUTCLUSTERS] =
  133. {
  134. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  135. };
  136. SimpleDescriptionFormat_t zclKeyEstablish_SimpleDesc =
  137. {
  138. ZCL_KEY_ESTABLISHMENT_ENDPOINT, // int Endpoint;
  139. ZCL_SE_PROFILE_ID, // uint16 AppProfId[2];
  140. ZCL_SE_DEVICEID_PHYSICAL, // uint16 AppDeviceId[2];
  141. ZCL_KEY_ESTABLISH_DEVICE_VERSION, // int AppDevVer:4;
  142. ZCL_KEY_ESTABLISH_FLAGS, // int AppFlags:4;
  143. ZCL_KEY_ESTABLISH_MAX_INCLUSTERS, // byte AppNumInClusters;
  144. (cId_t *)zclKeyEstablish_InClusterList, // byte *pAppInClusterList;
  145. ZCL_KEY_ESTABLISH_MAX_OUTCLUSTERS, // byte AppNumInClusters;
  146. (cId_t *)zclKeyEstablish_OutClusterList // byte *pAppInClusterList;
  147. };
  148. #if defined (ZCL_KEY_ESTABLISH)
  149. // Endpoint for Key Establishment Cluster
  150. static endPointDesc_t zclKeyEstablish_Ep =
  151. {
  152. ZCL_KEY_ESTABLISHMENT_ENDPOINT, // Test endpoint
  153. &zcl_TaskID,
  154. (SimpleDescriptionFormat_t *)&zclKeyEstablish_SimpleDesc,
  155. (afNetworkLatencyReq_t)0 // No Network Latency req
  156. };
  157. #endif
  158. // Pointer to the application sequence number for ZCL commands
  159. #if defined ( ZCL_KEY_ESTABLISH)
  160. static uint8 zclKeyEstablishPluginRegisted = FALSE;
  161. static zclKeyEstablishRec_t keyEstablishRec[MAX_KEY_ESTABLISHMENT_REC_ENTRY];
  162. /*********************************************************************
  163. * LOCAL FUNCTIONS
  164. */
  165. static ZStatus_t zclGeneral_KeyEstablish_HdlIncoming( zclIncoming_t *pInMsg );
  166. static ZStatus_t zclGeneral_KeyEstablish_HdlInSpecificCommands( zclIncoming_t *pInMsg );
  167. // Key Establish Cluster Command Processing functions
  168. static ZStatus_t zclGeneral_ProcessInCmd_InitiateKeyEstablish( zclIncoming_t *pInMsg );
  169. static ZStatus_t zclGeneral_ProcessInCmd_InitiateKeyEstablishRsp( zclIncoming_t *pInMsg );
  170. static ZStatus_t zclGeneral_ProcessInCmd_EphemeralDataReq( zclIncoming_t *pInMsg );
  171. static ZStatus_t zclGeneral_ProcessInCmd_EphemeralDataRsp( zclIncoming_t *pInMsg );
  172. static ZStatus_t zclGeneral_ProcessInCmd_ConfirmKey( zclIncoming_t *pInMsg );
  173. static ZStatus_t zclGeneral_ProcessInCmd_ConfirmKeyRsp( zclIncoming_t *pInMsg );
  174. static ZStatus_t zclGeneral_ProcessInCmd_TerminateKeyEstablish( zclIncoming_t *pInMsg );
  175. // Event driven key calculation function
  176. static ZStatus_t zclGeneral_InitiateKeyEstablish_Cmd_CalculateKey(void);
  177. static ZStatus_t zclGeneral_InitiateKeyEstablish_Rsp_CalculateKey(void);
  178. // Key establishment rec table management function
  179. static void zclGeneral_InitKeyEstablishRecTable( void );
  180. static uint8 zclGeneral_GetKeyEstablishRecIndex( uint16 partnerAddress );
  181. static uint8 zclGeneral_GetKeyEstablishRecIndex_State( KeyEstablishState_t state );
  182. static uint8 zclGeneral_AddKeyEstablishRec( afAddrType_t *addr );
  183. static void zclGeneral_AgeKeyEstablishRec( void );
  184. static void zclGeneral_ResetKeyEstablishRec( uint8 index );
  185. // Call back function supplying to ECC library
  186. static int zclGeneral_KeyEstablishment_GetRandom(unsigned char *buffer, unsigned long len);
  187. static int zclGeneral_KeyEstablishment_HashFunc(unsigned char *digest, unsigned long len, unsigned char *data);
  188. // Security related functions
  189. static void zclGeneral_KeyEstablishment_KeyDeriveFunction( uint8 *zData,
  190. uint8 keyBitLen,
  191. uint8 *keyBit );
  192. static ZStatus_t zclGeneral_KeyEstablishment_GenerateMAC(uint8 recIndex,
  193. uint8 ifMACu,
  194. uint8 *MAC);
  195. /*********************************************************************
  196. * @fn zclGeneral_KeyEstablish_Init
  197. *
  198. * @brief Call to initialize the Key Establishment Task
  199. *
  200. * @param task_id
  201. *
  202. * @return none
  203. */
  204. void zclGeneral_KeyEstablish_Init( uint8 task_id )
  205. {
  206. zcl_KeyEstablishment_TaskID = task_id;
  207. // Register for the key establishment cluster endpoint
  208. afRegister( &zclKeyEstablish_Ep );
  209. zcl_registerClusterOptionList( ZCL_KEY_ESTABLISHMENT_ENDPOINT, 1,
  210. zclKeyEstablish_Options );
  211. // Register as a ZCL Plugin
  212. if ( !zclKeyEstablishPluginRegisted )
  213. {
  214. zcl_registerPlugin( ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  215. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  216. zclGeneral_KeyEstablish_HdlIncoming );
  217. zclKeyEstablishPluginRegisted = TRUE;
  218. }
  219. // Initialize the keyEstablishRec table
  220. zclGeneral_InitKeyEstablishRecTable();
  221. }
  222. /*********************************************************************
  223. * @fn zclKeyEstablish_event_loop
  224. *
  225. * @brief Event Loop Processor for Key establish task.
  226. *
  227. * @param task_id - TaskId
  228. * events - events
  229. *
  230. * @return none
  231. */
  232. uint16 zclKeyEstablish_event_loop( uint8 task_id, uint16 events )
  233. {
  234. afIncomingMSGPacket_t *MSGpkt;
  235. if ( events & SYS_EVENT_MSG )
  236. {
  237. while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( task_id )) )
  238. {
  239. switch ( MSGpkt->hdr.event )
  240. {
  241. default:
  242. break;
  243. }
  244. // Release the memory
  245. osal_msg_deallocate( (uint8 *)MSGpkt );
  246. }
  247. // return unprocessed events
  248. return (events ^ SYS_EVENT_MSG);
  249. }
  250. if ( events & KEY_ESTABLISHMENT_REC_AGING_EVT )
  251. {
  252. zclGeneral_AgeKeyEstablishRec();
  253. return ( events ^ KEY_ESTABLISHMENT_REC_AGING_EVT );
  254. }
  255. if ( events & KEY_ESTABLISHMENT_CMD_PROCESS_EVT )
  256. {
  257. zclGeneral_InitiateKeyEstablish_Cmd_CalculateKey();
  258. return ( events ^ KEY_ESTABLISHMENT_CMD_PROCESS_EVT );
  259. }
  260. if ( events & KEY_ESTABLISHMENT_RSP_PROCESS_EVT )
  261. {
  262. zclGeneral_InitiateKeyEstablish_Rsp_CalculateKey();
  263. return ( events ^ KEY_ESTABLISHMENT_RSP_PROCESS_EVT );
  264. }
  265. // Discard unknown events
  266. return 0;
  267. }
  268. /*********************************************************************
  269. * @fn zclGeneral_KeyEstablish_InitiateKeyEstablishment
  270. *
  271. * @brief Call to initiate key establishment with partner device
  272. *
  273. * @param appTaskID - task ID of the application that initates the key establish
  274. * @param partnerAddr - short address and endpoint of the partner to establish key with
  275. * @param seqNum - pointer to the sequence number of application (ZCL)
  276. *
  277. * @return ZStatus_t ZSuccess or ZFailure
  278. */
  279. ZStatus_t zclGeneral_KeyEstablish_InitiateKeyEstablishment(uint8 appTaskID,
  280. afAddrType_t *partnerAddr,
  281. uint8 seqNum)
  282. {
  283. uint8 *implicitCert, index;
  284. // Assign the app seqnum pointer
  285. zcl_SeqNum = seqNum;
  286. // Start a new key establishment rec entry
  287. index = zclGeneral_AddKeyEstablishRec( partnerAddr );
  288. if( index < MAX_KEY_ESTABLISHMENT_REC_ENTRY ) // valid entry
  289. {
  290. keyEstablishRec[index].role = KEY_ESTABLISHMENT_INITIATOR;
  291. // Assign the application task ID that initiates the key establishment
  292. keyEstablishRec[index].appTaskID = appTaskID;
  293. }
  294. else
  295. {
  296. return ZFailure;
  297. }
  298. // Generate Ephemeral Public/Private Key Pair
  299. ZSE_ECCGenerateKey( ( unsigned char *)keyEstablishRec[index].pLocalEPrivateKey,
  300. ( unsigned char *)keyEstablishRec[index].pLocalEPublicKey,
  301. zclGeneral_KeyEstablishment_GetRandom,
  302. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel);
  303. #if defined (DEBUG_STATIC_ECC)
  304. // For debug and testing purpose, use a fixed ephermeral key pair instead
  305. // of the randomly generated one.
  306. osal_memcpy( keyEstablishRec[index].pLocalEPrivateKey, private1, 21 );
  307. osal_memcpy( keyEstablishRec[index].pLocalEPublicKey, public1, 22 );
  308. #endif
  309. keyEstablishRec[index].state = KeyEstablishState_InitiatePending;
  310. if ((implicitCert = osal_mem_alloc(ZCL_KE_IMPLICIT_CERTIFICATE_LEN)) == NULL)
  311. {
  312. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  313. }
  314. osal_nv_read(ZCD_NV_IMPLICIT_CERTIFICATE, 0, ZCL_KE_IMPLICIT_CERTIFICATE_LEN, implicitCert);
  315. // Send Initiate Key Establishment Command
  316. zclGeneral_KeyEstablish_Send_InitiateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  317. partnerAddr,
  318. KEY_ESTABLISHMENT_SUITE,
  319. ZCL_KEY_ESTABLISHMENT_EKEY_GENERATE_TIMEOUT,
  320. ZCL_KEY_ESTABLISHMENT_MAC_GENERATE_TIMEOUT + ZCL_KEY_ESTABLISHMENT_KEY_GENERATE_TIMEOUT,
  321. implicitCert, TRUE, zcl_SeqNum++ );
  322. // Start the Key Establishment aging timer, this has to be started to make sure the record
  323. // is going to be deleted in the event that "Key Establishment Response" is not received for
  324. // any reason. This way we do not have hanging records in the table and memory leak issues.
  325. osal_start_reload_timer( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT,
  326. KEY_ESTABLISHMENT_REC_AGING_INTERVAL );
  327. osal_mem_free(implicitCert);
  328. #if defined (NWK_AUTO_POLL)
  329. // Start the key establishment process and set the Key Establish poll rate
  330. zclSavedPollRate = zgPollRate;
  331. NLME_SetPollRate(ZCL_KEY_ESTABLISH_POLL_RATE);
  332. #endif
  333. return ZSuccess;
  334. }
  335. /*********************************************************************
  336. * @fn zclGeneral_KeyEstablish_Send_InitiateKeyEstablishment
  337. *
  338. * @brief Call to send out a Initiate Key Establishment Command
  339. *
  340. * @param srcEP - Sending application's endpoint
  341. * @param dstAddr - where you want the message to go
  342. * @param keyEstablishmentSuite - key establishment suite bitmap
  343. * @param keyGenerateTime - how long it takes to generate key
  344. * @param macGenerateTime - how long it takes to generate mac
  345. * @param certificate - identity. For CBKE, it's the implicit certificate.
  346. * @param disableDefaultRsp - disable default response
  347. * @param seqNum - ZCL sequence number
  348. *
  349. * @return ZStatus_t
  350. */
  351. ZStatus_t zclGeneral_KeyEstablish_Send_InitiateKeyEstablishment( uint8 srcEP, afAddrType_t *dstAddr,
  352. uint16 keyEstablishmentSuite,
  353. uint8 keyGenerateTime,
  354. uint8 macGenerateTime,
  355. uint8 *certificate,
  356. uint8 disableDefaultRsp, uint8 seqNum )
  357. {
  358. uint8 *buf;
  359. uint8 *pBuf;
  360. uint8 status;
  361. uint8 bufLen;
  362. (void)srcEP; // Intentionally unreferenced parameter
  363. // keyEstablishmentSuite + eDataGenerateTime + macGenerateTime + certificate
  364. bufLen = 2 + 1 + 1 + ZCL_KE_IMPLICIT_CERTIFICATE_LEN;
  365. if ((buf = osal_mem_alloc(bufLen)) == NULL)
  366. {
  367. return ZMemError;
  368. }
  369. pBuf = buf;
  370. *pBuf++ = LO_UINT16( keyEstablishmentSuite );
  371. *pBuf++ = HI_UINT16( keyEstablishmentSuite );
  372. *pBuf++ = keyGenerateTime;
  373. *pBuf++ = macGenerateTime;
  374. osal_memcpy( pBuf, certificate, ZCL_KE_IMPLICIT_CERTIFICATE_LEN );
  375. status = zcl_SendCommand( ZCL_KEY_ESTABLISHMENT_ENDPOINT, dstAddr,
  376. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  377. COMMAND_INITIATE_KEY_ESTABLISHMENT, TRUE,
  378. ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp,
  379. 0, seqNum, bufLen, buf );
  380. osal_mem_free(buf);
  381. return status;
  382. }
  383. /*********************************************************************
  384. * @fn zclGeneral_KeyEstablish_Send_EphemeralDataReq
  385. *
  386. * @brief Call to send out a Ephemeral Data Request Command
  387. *
  388. * @param srcEP - Sending application's endpoint
  389. * @param dstAddr - where you want the message to go
  390. * @param eData - ephemeral data.
  391. * @param disableDefaultRsp - disable default response
  392. * @param seqNum - ZCL sequence number
  393. *
  394. * @return ZStatus_t
  395. */
  396. ZStatus_t zclGeneral_KeyEstablish_Send_EphemeralDataReq( uint8 srcEP, afAddrType_t *dstAddr,
  397. uint8 *eData,
  398. uint8 disableDefaultRsp, uint8 seqNum )
  399. {
  400. return zcl_SendCommand( srcEP, dstAddr,
  401. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  402. COMMAND_EPHEMERAL_DATA_REQUEST, TRUE,
  403. ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp,
  404. 0, seqNum, ZCL_KE_CA_PUBLIC_KEY_LEN, eData );
  405. }
  406. /*********************************************************************
  407. * @fn zclGeneral_KeyEstablish_Send_ConfirmKey
  408. *
  409. * @brief Call to send out a Confirm Key Command
  410. *
  411. * @param srcEP - Sending application's endpoint
  412. * @param dstAddr - where you want the message to go
  413. * @param mac - MAC.
  414. * @param disableDefaultRsp - disable default response
  415. * @param seqNum - ZCL sequence number
  416. *
  417. * @return ZStatus_t
  418. */
  419. ZStatus_t zclGeneral_KeyEstablish_Send_ConfirmKey( uint8 srcEP, afAddrType_t *dstAddr,
  420. uint8 *mac,
  421. uint8 disableDefaultRsp, uint8 seqNum )
  422. {
  423. return (zcl_SendCommand(srcEP, dstAddr,
  424. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  425. COMMAND_CONFIRM_KEY, TRUE,
  426. ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp,
  427. 0, seqNum, KEY_ESTABLISH_MAC_LENGTH, mac ));
  428. }
  429. /*********************************************************************
  430. * @fn zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment
  431. *
  432. * @brief Call to send out a Terminate Key Establishment Command
  433. *
  434. * @param srcEP - Sending application's endpoint
  435. * @param dstAddr - where you want the message to go
  436. * @param status - status of the key establishment procedure.
  437. * @param direction - client/server direction of the command
  438. * @param disableDefaultRsp - disable default response
  439. * @param seqNum - ZCL sequence number
  440. *
  441. * @return ZStatus_t
  442. */
  443. ZStatus_t zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( uint8 srcEP,
  444. afAddrType_t *dstAddr,
  445. TermKeyStatus_t status,
  446. uint8 waitTime,
  447. uint16 keyEstablishmentSuite, uint8 direction,
  448. uint8 disableDefaultRsp, uint8 seqNum )
  449. {
  450. uint8 buf[4];
  451. buf[0] = status;
  452. buf[1] = waitTime;
  453. buf[2] = LO_UINT16(keyEstablishmentSuite);
  454. buf[3] = HI_UINT16(keyEstablishmentSuite);
  455. return zcl_SendCommand(srcEP, dstAddr,
  456. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  457. COMMAND_TERMINATE_KEY_ESTABLISHMENT, TRUE,
  458. direction, disableDefaultRsp,
  459. 0, seqNum, 4, buf );
  460. }
  461. /*********************************************************************
  462. * @fn zclGeneral_KeyEstablish_Send_InitiateKeyEstablishmentRsp
  463. *
  464. * @brief Call to send out a Initiate Key Establishment Response
  465. *
  466. * @param srcEP - Sending application's endpoint
  467. * @param dstAddr - where you want the message to go
  468. * @param status - status of the key establishment response.
  469. * @param keyEstablishmentSuite - requested key establishment suite bitmap
  470. * @param keyGenerateTime - how long it takes to generate key
  471. * @param macGenerateTime - how long it takes to generate mac
  472. * @param certificate - identity. For CBKE, it's the implicit certificate.
  473. * @param disableDefaultRsp - disable default response
  474. * @param seqNum - ZCL sequence number
  475. *
  476. * @return ZStatus_t
  477. */
  478. ZStatus_t zclGeneral_KeyEstablish_Send_InitiateKeyEstablishmentRsp( uint8 srcEP, afAddrType_t *dstAddr,
  479. uint16 keyEstablishmentSuite,
  480. uint8 keyGenerateTime,
  481. uint8 macGenerateTime,
  482. uint8 *certificate,
  483. uint8 disableDefaultRsp, uint8 seqNum )
  484. {
  485. uint8 *buf;
  486. uint8 bufLen;
  487. uint8 ret;
  488. uint8 *pBuf;
  489. bufLen = 2 + 1 + 1 + ZCL_KE_IMPLICIT_CERTIFICATE_LEN;
  490. if ((buf = osal_mem_alloc(bufLen)) == NULL)
  491. {
  492. return ZMemError;
  493. }
  494. pBuf = buf;
  495. *pBuf++ = LO_UINT16( keyEstablishmentSuite );
  496. *pBuf++ = HI_UINT16( keyEstablishmentSuite );
  497. *pBuf++ = keyGenerateTime;
  498. *pBuf++ = macGenerateTime;
  499. osal_memcpy( pBuf, certificate, ZCL_KE_IMPLICIT_CERTIFICATE_LEN );
  500. ret = zcl_SendCommand( srcEP, dstAddr,
  501. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  502. COMMAND_INITIATE_KEY_ESTABLISHMENT_RESPONSE, TRUE,
  503. ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp,
  504. 0, seqNum, bufLen, buf );
  505. osal_mem_free(buf);
  506. return ret;
  507. }
  508. /*********************************************************************
  509. * @fn zclGeneral_KeyEstablish_Send_EphemeralDataRsp
  510. *
  511. * @brief Call to send out a Ephemeral Data Response Command
  512. *
  513. * @param srcEP - Sending application's endpoint
  514. * @param dstAddr - where you want the message to go
  515. * @param eData - ephemeral data.
  516. * @param disableDefaultRsp - disable default response
  517. * @param seqNum - ZCL sequence number
  518. *
  519. * @return ZStatus_t
  520. */
  521. ZStatus_t zclGeneral_KeyEstablish_Send_EphemeralDataRsp( uint8 srcEP, afAddrType_t *dstAddr,
  522. uint8 *eData,
  523. uint8 disableDefaultRsp, uint8 seqNum )
  524. {
  525. return (zcl_SendCommand( srcEP, dstAddr,
  526. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  527. COMMAND_EPHEMERAL_DATA_RESPONSE, TRUE,
  528. ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp,
  529. 0, seqNum, ZCL_KE_CA_PUBLIC_KEY_LEN, eData ));
  530. }
  531. /*********************************************************************
  532. * @fn zclGeneral_KeyEstablish_Send_ConfirmKeyRsp
  533. *
  534. * @brief Call to send out a Confirm Key Response
  535. *
  536. * @param srcEP - Sending application's endpoint
  537. * @param dstAddr - where you want the message to go
  538. * @param mac - MAC
  539. * @param disableDefaultRsp - disable default response
  540. * @param seqNum - ZCL sequence number
  541. *
  542. * @return ZStatus_t
  543. */
  544. ZStatus_t zclGeneral_KeyEstablish_Send_ConfirmKeyRsp( uint8 srcEP, afAddrType_t *dstAddr,
  545. uint8 *mac,
  546. uint8 disableDefaultRsp, uint8 seqNum )
  547. {
  548. return (zcl_SendCommand(srcEP, dstAddr,
  549. ZCL_CLUSTER_ID_GEN_KEY_ESTABLISHMENT,
  550. COMMAND_CONFIRM_KEY_RESPONSE, TRUE,
  551. ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp,
  552. 0, seqNum, KEY_ESTABLISH_MAC_LENGTH, mac ));
  553. }
  554. /*********************************************************************
  555. * @fn zclGeneral_KeyEstablish_Send_ConfirmKeyRsp
  556. *
  557. * @brief Register the user defined yielding function
  558. *
  559. * @param yield - Pointer to a function to allow user defined yielding.
  560. * YieldFunc may be NULL if yieldLevel is 0
  561. * @param yieldLevel - The yield level determines how often the user defined
  562. * yield function will be called. This is a number from 0 to 10.
  563. * 0 will never yield. 1 will yield the most often. 10 will yield the
  564. * least often.
  565. */
  566. void zclGeneral_KeyEstablishment_RegYieldCB( YieldFunc *pFnYield,
  567. uint8 yieldLevel )
  568. {
  569. if( pFnYield == NULL )
  570. {
  571. zclKeyEstablish_YieldLevel = 0;
  572. }
  573. else
  574. {
  575. zclKeyEstablish_YieldFunc = pFnYield;
  576. zclKeyEstablish_YieldLevel = yieldLevel;
  577. }
  578. }
  579. /*********************************************************************
  580. * @fn zclGeneral_KeyEstablish_HdlIncoming
  581. *
  582. * @brief Callback from ZCL to process incoming Commands specific
  583. * to this cluster library or Profile commands
  584. *
  585. * @param pInMsg - pointer to the incoming message
  586. *
  587. * @return ZStatus_t
  588. */
  589. static ZStatus_t zclGeneral_KeyEstablish_HdlIncoming( zclIncoming_t *pInMsg )
  590. {
  591. ZStatus_t stat = ZSuccess;
  592. #if defined ( INTER_PAN )
  593. if ( StubAPS_InterPan( pInMsg->msg->srcAddr.panId, pInMsg->msg->srcAddr.endPoint ) )
  594. return ( stat ); // Cluster not supported thru Inter-PAN
  595. #endif
  596. if ( zcl_ClusterCmd( pInMsg->hdr.fc.type ) )
  597. {
  598. // Is this a manufacturer specific command?
  599. if ( pInMsg->hdr.fc.manuSpecific == 0 )
  600. {
  601. stat = zclGeneral_KeyEstablish_HdlInSpecificCommands( pInMsg );
  602. }
  603. else
  604. {
  605. // We don't support any manufacturer specific command.
  606. stat = ZFailure;
  607. }
  608. }
  609. else
  610. {
  611. // Handle all the normal (Read, Write...) commands -- should never get here
  612. stat = ZFailure;
  613. }
  614. return ( stat );
  615. }
  616. /*********************************************************************
  617. * @fn zclGeneral_KeyEstablish_HdlInSpecificCommands
  618. *
  619. * @brief Callback from ZCL to process incoming Commands specific
  620. * to this cluster library
  621. * @param pInMsg - pointer to the incoming message
  622. *
  623. * @return ZStatus_t
  624. */
  625. static ZStatus_t zclGeneral_KeyEstablish_HdlInSpecificCommands( zclIncoming_t *pInMsg )
  626. {
  627. ZStatus_t stat;
  628. if ( zcl_ServerCmd( pInMsg->hdr.fc.direction ) )
  629. {
  630. // Commands received by Server
  631. switch ( pInMsg->hdr.commandID )
  632. {
  633. case COMMAND_INITIATE_KEY_ESTABLISHMENT:
  634. stat = zclGeneral_ProcessInCmd_InitiateKeyEstablish( pInMsg );
  635. break;
  636. case COMMAND_EPHEMERAL_DATA_REQUEST:
  637. stat = zclGeneral_ProcessInCmd_EphemeralDataReq( pInMsg );
  638. break;
  639. case COMMAND_CONFIRM_KEY:
  640. stat = zclGeneral_ProcessInCmd_ConfirmKey( pInMsg );
  641. break;
  642. case COMMAND_TERMINATE_KEY_ESTABLISHMENT:
  643. stat = zclGeneral_ProcessInCmd_TerminateKeyEstablish( pInMsg );
  644. break;
  645. default:
  646. stat = ZFailure;
  647. break;
  648. }
  649. }
  650. else
  651. {
  652. // Commands received by Client
  653. switch ( pInMsg->hdr.commandID )
  654. {
  655. case COMMAND_INITIATE_KEY_ESTABLISHMENT_RESPONSE:
  656. stat = zclGeneral_ProcessInCmd_InitiateKeyEstablishRsp( pInMsg );
  657. break;
  658. case COMMAND_EPHEMERAL_DATA_RESPONSE:
  659. stat = zclGeneral_ProcessInCmd_EphemeralDataRsp( pInMsg );
  660. break;
  661. case COMMAND_CONFIRM_KEY_RESPONSE:
  662. stat = zclGeneral_ProcessInCmd_ConfirmKeyRsp( pInMsg );
  663. break;
  664. case COMMAND_TERMINATE_KEY_ESTABLISHMENT:
  665. stat = zclGeneral_ProcessInCmd_TerminateKeyEstablish( pInMsg );
  666. break;
  667. default:
  668. stat = ZFailure;
  669. break;
  670. }
  671. }
  672. return ( stat );
  673. }
  674. /*********************************************************************
  675. * @fn zclGeneral_ProcessInCmd_InitiateKeyEstablish
  676. *
  677. * @brief Process the received Initiate Key Establishment Request.
  678. *
  679. * @param pInMsg - pointer to the incoming message
  680. *
  681. * @return ZStatus_t - ZFailure @ Unsupported
  682. * ZCL_STATUS_MALFORMED_COMMAND
  683. * ZCL_STATUS_CMD_HAS_RSP
  684. * ZCL_STATUS_SOFTWARE_FAILURE
  685. */
  686. static ZStatus_t zclGeneral_ProcessInCmd_InitiateKeyEstablish( zclIncoming_t *pInMsg )
  687. {
  688. TermKeyStatus_t status = TermKeyStatus_Success;
  689. uint16 remoteKeyEstablishmentSuite;
  690. uint8 *implicitCert = NULL;
  691. uint8 index = MAX_KEY_ESTABLISHMENT_REC_ENTRY; // set to non valid value
  692. // Check the incoming packet length
  693. if ( pInMsg->pDataLen < PACKET_LEN_INITIATE_KEY_EST_REQ )
  694. {
  695. status = TermKeyStatus_BadMessage;
  696. }
  697. else
  698. {
  699. // Start a new key establishment rec entry
  700. index = zclGeneral_AddKeyEstablishRec( &pInMsg->msg->srcAddr );
  701. if( index >= MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  702. {
  703. // Failed to add an entry
  704. status = TermKeyStatus_NoResources;
  705. }
  706. else
  707. {
  708. // Parse the incoming message
  709. // Copy the remote device certificate
  710. osal_memcpy(keyEstablishRec[index].pRemoteCertificate, &(pInMsg->pData[KEY_ESTABLISH_CERT_IDX]),
  711. ZCL_KE_IMPLICIT_CERTIFICATE_LEN );
  712. // Verify the certificate issuer and key establishment suite
  713. remoteKeyEstablishmentSuite = BUILD_UINT16( pInMsg->pData[0], pInMsg->pData[1] );
  714. if ( remoteKeyEstablishmentSuite != KEY_ESTABLISHMENT_SUITE )
  715. {
  716. status = TermKeyStatus_UnSupportedSuite;
  717. }
  718. else
  719. {
  720. // continue parsing message
  721. // Save Ephemeral Data Generate Key and Confirm Key Time
  722. if (pInMsg->pData[2] >= KEY_ESTABLISHMENT_EPH_DATA_GEN_INVALID_TIME)
  723. {
  724. status = TermKeyStatus_BadMessage;
  725. }
  726. else
  727. {
  728. // continue parsing message
  729. keyEstablishRec[index].remoteEphDataGenTime = pInMsg->pData[2];
  730. if (pInMsg->pData[3] >= KEY_ESTABLISHMENT_CONF_KEY_GEN_INVALID_TIME)
  731. {
  732. status = TermKeyStatus_BadMessage;
  733. }
  734. else
  735. {
  736. // continue parsing message
  737. keyEstablishRec[index].remoteConfKeyGenTime = pInMsg->pData[3];
  738. if ((implicitCert = osal_mem_alloc(ZCL_KE_IMPLICIT_CERTIFICATE_LEN)) == NULL)
  739. {
  740. // Reset the entry
  741. zclGeneral_ResetKeyEstablishRec( index );
  742. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  743. }
  744. osal_nv_read(ZCD_NV_IMPLICIT_CERTIFICATE, 0, ZCL_KE_IMPLICIT_CERTIFICATE_LEN, implicitCert);
  745. if ( !osal_memcmp( &(keyEstablishRec[index].pRemoteCertificate[KEY_ESTABLISH_CERT_ISSUER_IDX]),
  746. &(implicitCert[KEY_ESTABLISH_CERT_ISSUER_IDX]),
  747. KEY_ESTABLISH_CERT_ISSUER_LENTGH ) )
  748. {
  749. status = TermKeyStatus_UnknowIssuer;
  750. }
  751. }
  752. }
  753. }
  754. } // end of parsing of the message
  755. }
  756. if ( status != TermKeyStatus_Success )
  757. {
  758. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  759. &pInMsg->msg->srcAddr,
  760. status,
  761. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  762. KEY_ESTABLISHMENT_SUITE,
  763. ZCL_FRAME_SERVER_CLIENT_DIR,
  764. FALSE, zcl_SeqNum++ );
  765. if ( implicitCert != NULL )
  766. {
  767. osal_mem_free(implicitCert);
  768. }
  769. // Reset the entry
  770. if ( index < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  771. {
  772. zclGeneral_ResetKeyEstablishRec( index );
  773. }
  774. return ZCL_STATUS_CMD_HAS_RSP;
  775. }
  776. // Fill in partner's extended address
  777. SSP_MemCpyReverse( keyEstablishRec[index].partnerExtAddr,
  778. &(keyEstablishRec[index].pRemoteCertificate[KEY_ESTABLISH_CERT_EXT_ADDR_IDX]),
  779. Z_EXTADDR_LEN); // ID(L)
  780. // Change the state and wait for the Ephemeral Data Request
  781. keyEstablishRec[index].lastSeqNum = pInMsg->hdr.transSeqNum;
  782. keyEstablishRec[index].state = KeyEstablishState_EDataPending;
  783. keyEstablishRec[index].role = KEY_ESTABLISHMENT_RESPONDER;
  784. zclGeneral_KeyEstablish_Send_InitiateKeyEstablishmentRsp( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  785. &pInMsg->msg->srcAddr,
  786. KEY_ESTABLISHMENT_SUITE,
  787. ZCL_KEY_ESTABLISHMENT_EKEY_GENERATE_TIMEOUT + ZCL_KEY_ESTABLISHMENT_KEY_GENERATE_TIMEOUT,
  788. ZCL_KEY_ESTABLISHMENT_MAC_GENERATE_TIMEOUT * 2 ,
  789. implicitCert, FALSE, pInMsg->hdr.transSeqNum );
  790. // The Request was processed successfuly, now the age timer needs to start based on the
  791. // remote Ephemeral Data Generate Time
  792. keyEstablishRec[index].age = keyEstablishRec[index].remoteEphDataGenTime;
  793. // Start the Ephemeral Data Generate aging timer
  794. osal_start_reload_timer( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT,
  795. KEY_ESTABLISHMENT_REC_AGING_INTERVAL );
  796. osal_mem_free(implicitCert);
  797. #if defined (NWK_AUTO_POLL)
  798. // For polling end device, set the Key Establishment poll rate
  799. zclSavedPollRate = zgPollRate;
  800. NLME_SetPollRate(ZCL_KEY_ESTABLISH_POLL_RATE);
  801. #endif
  802. return ZCL_STATUS_CMD_HAS_RSP;
  803. }
  804. /*********************************************************************
  805. * @fn zclGeneral_ProcessInCmd_EphemeralDataReq
  806. *
  807. * @brief Process the received Ephemeral Data Request.
  808. *
  809. * @param pInMsg - pointer to the incoming message
  810. *
  811. * @return ZStatus_t - ZFailure @ Unsupported
  812. * ZCL_STATUS_MALFORMED_COMMAND
  813. * ZCL_STATUS_CMD_HAS_RSP
  814. */
  815. static ZStatus_t zclGeneral_ProcessInCmd_EphemeralDataReq( zclIncoming_t *pInMsg )
  816. {
  817. uint8 index;
  818. uint8 status = ZFailure;
  819. // Omit checking the incoming packet length
  820. // Stop the Ephemeral Data Generate timer because the message has been received
  821. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  822. // Check state of the key establishment record. If not match, terminate the procedure
  823. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  824. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  825. {
  826. if ( keyEstablishRec[index].role == KEY_ESTABLISHMENT_RESPONDER &&
  827. keyEstablishRec[index].state == KeyEstablishState_EDataPending )
  828. {
  829. status = ZSuccess;
  830. // Copy the remote device Ephemeral Public key
  831. osal_memcpy( keyEstablishRec[index].pRemotePublicKey,
  832. &(pInMsg->pData[0]),
  833. ZCL_KE_CA_PUBLIC_KEY_LEN );
  834. }
  835. else
  836. {
  837. // Reset the entry
  838. zclGeneral_ResetKeyEstablishRec( index );
  839. }
  840. }
  841. if( status != ZSuccess )
  842. {
  843. // Either the entry doesn't exist or in the wrong state, send termination back
  844. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  845. &pInMsg->msg->srcAddr,
  846. TermKeyStatus_BadMessage,
  847. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  848. KEY_ESTABLISHMENT_SUITE,
  849. ZCL_FRAME_SERVER_CLIENT_DIR,
  850. FALSE, zcl_SeqNum++ );
  851. #if defined (NWK_AUTO_POLL)
  852. // Restore the saved poll rate for end device
  853. NLME_SetPollRate(zclSavedPollRate);
  854. #endif
  855. return ZCL_STATUS_CMD_HAS_RSP;
  856. }
  857. // Generate Ephemeral Public/Private Key Pair
  858. ZSE_ECCGenerateKey( (unsigned char *)keyEstablishRec[index].pLocalEPrivateKey,
  859. (unsigned char *)keyEstablishRec[index].pLocalEPublicKey,
  860. zclGeneral_KeyEstablishment_GetRandom,
  861. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel );
  862. #if defined (DEBUG_STATIC_ECC)
  863. // For debug and testing purpose, use a fixed ephermeral key pair instead
  864. // of the randomly generated one.
  865. osal_memcpy( keyEstablishRec[index].pLocalEPrivateKey, private2, 21 );
  866. osal_memcpy( keyEstablishRec[index].pLocalEPublicKey, public2, 22 );
  867. #endif
  868. // Update Sequence Number
  869. keyEstablishRec[index].lastSeqNum = pInMsg->hdr.transSeqNum;
  870. // Change the state and wait for the Key to be calculated
  871. keyEstablishRec[index].state = KeyEstablishState_KeyCalculatePending;
  872. osal_start_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_CMD_PROCESS_EVT,
  873. KEY_ESTABLISHMENT_WAIT_PERIOD );
  874. return ZCL_STATUS_CMD_HAS_RSP;
  875. }
  876. /*********************************************************************
  877. * @fn zclGeneral_ProcessInCmd_InitiateKeyEstablishRsp
  878. *
  879. * @brief Process the received Initiate Key Establishment Response.
  880. *
  881. * @param pInMsg - pointer to the incoming message
  882. *
  883. * @return ZStatus_t - ZFailure @ Unsupported
  884. * ZCL_STATUS_MALFORMED_COMMAND
  885. * ZCL_STATUS_CMD_HAS_RSP
  886. * ZCL_STATUS_SOFTWARE_FAILURE
  887. */
  888. static ZStatus_t zclGeneral_ProcessInCmd_InitiateKeyEstablishRsp( zclIncoming_t *pInMsg )
  889. {
  890. TermKeyStatus_t keyStatus = TermKeyStatus_Success;
  891. uint16 remoteKeyEstablishmentSuite;
  892. uint8 index = MAX_KEY_ESTABLISHMENT_REC_ENTRY; // set to non valid value
  893. uint8 status = ZFailure;
  894. uint8 recvExtAddr[Z_EXTADDR_LEN];
  895. // Stop the Key Establishment aging timer because the message has been received
  896. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  897. // Check the incoming packet length
  898. if ( pInMsg->pDataLen >= PACKET_LEN_INITIATE_KEY_EST_RSP )
  899. {
  900. // Check state of the key establishment record. If not match, terminate the procedure
  901. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  902. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  903. {
  904. if ( keyEstablishRec[index].role == KEY_ESTABLISHMENT_INITIATOR &&
  905. keyEstablishRec[index].state == KeyEstablishState_InitiatePending )
  906. {
  907. // Parse the incoming message
  908. // Copy the remote device certificate
  909. osal_memcpy( keyEstablishRec[index].pRemoteCertificate, &(pInMsg->pData[KEY_ESTABLISH_CERT_IDX]),
  910. ZCL_KE_IMPLICIT_CERTIFICATE_LEN );
  911. // look for extended address of partner device
  912. AddrMgrExtAddrLookup(keyEstablishRec[index].dstAddr.addr.shortAddr,
  913. keyEstablishRec[index].partnerExtAddr);
  914. // retrieve extended address from certificate and reverse bytes
  915. SSP_MemCpyReverse( recvExtAddr,
  916. &(keyEstablishRec[index].pRemoteCertificate[KEY_ESTABLISH_CERT_EXT_ADDR_IDX]),
  917. Z_EXTADDR_LEN);
  918. // verify extended address in certificate matches partner's extended address
  919. if (osal_memcmp(keyEstablishRec[index].partnerExtAddr, recvExtAddr, Z_EXTADDR_LEN))
  920. {
  921. status = ZSuccess;
  922. }
  923. }
  924. else
  925. {
  926. // Reset the entry from the rec table
  927. zclGeneral_ResetKeyEstablishRec( index );
  928. }
  929. }
  930. }
  931. if ( status == ZFailure )
  932. {
  933. keyStatus = TermKeyStatus_BadMessage;
  934. }
  935. else
  936. {
  937. uint8 *implicitCert;
  938. // Parse the incoming message
  939. // Verify the certificate issuer and key establishment suite
  940. remoteKeyEstablishmentSuite = BUILD_UINT16( pInMsg->pData[0], pInMsg->pData[1] );
  941. if ( remoteKeyEstablishmentSuite != KEY_ESTABLISHMENT_SUITE )
  942. {
  943. keyStatus = TermKeyStatus_UnSupportedSuite;
  944. }
  945. else
  946. {
  947. // continue parsing message
  948. // Save Ephemeral Data Generate Key and Confirm Key Time
  949. if (pInMsg->pData[2] >= KEY_ESTABLISHMENT_EPH_DATA_GEN_INVALID_TIME)
  950. {
  951. status = TermKeyStatus_BadMessage;
  952. }
  953. else
  954. {
  955. // continue parsing message
  956. keyEstablishRec[index].remoteEphDataGenTime = pInMsg->pData[2];
  957. if (pInMsg->pData[3] >= KEY_ESTABLISHMENT_CONF_KEY_GEN_INVALID_TIME)
  958. {
  959. status = TermKeyStatus_BadMessage;
  960. }
  961. else
  962. {
  963. // continue parsing message
  964. keyEstablishRec[index].remoteConfKeyGenTime = pInMsg->pData[3];
  965. if ((implicitCert = osal_mem_alloc(ZCL_KE_IMPLICIT_CERTIFICATE_LEN)) == NULL)
  966. {
  967. // Reset the entry
  968. zclGeneral_ResetKeyEstablishRec( index );
  969. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  970. }
  971. osal_nv_read(ZCD_NV_IMPLICIT_CERTIFICATE, 0, ZCL_KE_IMPLICIT_CERTIFICATE_LEN, implicitCert);
  972. if ( !osal_memcmp( &(keyEstablishRec[index].pRemoteCertificate[KEY_ESTABLISH_CERT_ISSUER_IDX]),
  973. &(implicitCert[KEY_ESTABLISH_CERT_ISSUER_IDX]),
  974. KEY_ESTABLISH_CERT_ISSUER_LENTGH ) )
  975. {
  976. keyStatus = TermKeyStatus_UnknowIssuer;
  977. }
  978. osal_mem_free(implicitCert);
  979. }
  980. }
  981. }
  982. } // end of parsing of the message
  983. if ( keyStatus == TermKeyStatus_Success )
  984. {
  985. keyEstablishRec[index].state = KeyEstablishState_EDataPending;
  986. // Send Ephemeral Data Request back
  987. zclGeneral_KeyEstablish_Send_EphemeralDataReq( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  988. &pInMsg->msg->srcAddr,
  989. keyEstablishRec[index].pLocalEPublicKey,
  990. FALSE, zcl_SeqNum++ );
  991. // The Request was processed successfuly, now the age timer needs to start based on the
  992. // remote Ephemeral Data Generate Time
  993. keyEstablishRec[index].age = keyEstablishRec[index].remoteEphDataGenTime;
  994. // Start the Ephemeral Data Generate aging timer
  995. osal_start_reload_timer( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT,
  996. KEY_ESTABLISHMENT_REC_AGING_INTERVAL );
  997. }
  998. else
  999. {
  1000. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1001. &pInMsg->msg->srcAddr,
  1002. keyStatus,
  1003. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1004. KEY_ESTABLISHMENT_SUITE,
  1005. ZCL_FRAME_CLIENT_SERVER_DIR,
  1006. FALSE, zcl_SeqNum++ );
  1007. // Reset the entry
  1008. if ( index < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1009. {
  1010. zclGeneral_ResetKeyEstablishRec( index );
  1011. }
  1012. #if defined (NWK_AUTO_POLL)
  1013. // Restore the saved poll rate for end device
  1014. NLME_SetPollRate(zclSavedPollRate);
  1015. #endif
  1016. }
  1017. return ZCL_STATUS_CMD_HAS_RSP;
  1018. }
  1019. /*********************************************************************
  1020. * @fn zclGeneral_ProcessInCmd_EphemeralDataRsp
  1021. *
  1022. * @brief Process the received Initiate Key Establishment Response.
  1023. *
  1024. * @param pInMsg - pointer to the incoming message
  1025. *
  1026. * @return ZStatus_t - ZFailure @ Unsupported
  1027. * ZCL_STATUS_MALFORMED_COMMAND
  1028. * ZCL_STATUS_CMD_HAS_RSP
  1029. * ZCL_STATUS_SOFTWARE_FAILURE
  1030. */
  1031. static ZStatus_t zclGeneral_ProcessInCmd_EphemeralDataRsp( zclIncoming_t *pInMsg )
  1032. {
  1033. uint8 index;
  1034. uint8 status = ZFailure;
  1035. // Stop the Ephemeral Data Generate timer because the message has been received
  1036. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  1037. // Check state of the key establishment record. If not match, terminate the procedure
  1038. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  1039. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1040. {
  1041. if ( keyEstablishRec[index].role == KEY_ESTABLISHMENT_INITIATOR &&
  1042. keyEstablishRec[index].state == KeyEstablishState_EDataPending )
  1043. {
  1044. status = ZSuccess;
  1045. // Copy the remote device Ephemeral Public key
  1046. osal_memcpy( keyEstablishRec[index].pRemotePublicKey,
  1047. &(pInMsg->pData[0]),
  1048. ZCL_KE_CA_PUBLIC_KEY_LEN );
  1049. }
  1050. else
  1051. {
  1052. // Reset the entry from the rec table
  1053. zclGeneral_ResetKeyEstablishRec( index );
  1054. }
  1055. }
  1056. if ( status == ZFailure )
  1057. {
  1058. // No existing record found or the record found has a wrong state, terminate the procedure
  1059. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1060. &pInMsg->msg->srcAddr,
  1061. TermKeyStatus_BadMessage,
  1062. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1063. KEY_ESTABLISHMENT_SUITE,
  1064. ZCL_FRAME_CLIENT_SERVER_DIR,
  1065. FALSE, zcl_SeqNum++ );
  1066. #if defined (NWK_AUTO_POLL)
  1067. // Restore the saved poll rate for end device
  1068. NLME_SetPollRate(zclSavedPollRate);
  1069. #endif
  1070. }
  1071. else
  1072. {
  1073. keyEstablishRec[index].state = KeyEstablishState_KeyCalculatePending;
  1074. osal_start_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_RSP_PROCESS_EVT,
  1075. KEY_ESTABLISHMENT_WAIT_PERIOD );
  1076. }
  1077. return ZCL_STATUS_CMD_HAS_RSP;
  1078. }
  1079. /*********************************************************************
  1080. * @fn zclGeneral_ProcessInCmd_ConfirmKey
  1081. *
  1082. * @brief Process the received Confirm Key Command.
  1083. *
  1084. * @param pInMsg - pointer to the incoming message
  1085. *
  1086. * @return ZStatus_t - ZFailure @ Unsupported
  1087. * ZCL_STATUS_CMD_HAS_RSP
  1088. * ZCL_STATUS_SOFTWARE_FAILURE
  1089. */
  1090. static ZStatus_t zclGeneral_ProcessInCmd_ConfirmKey( zclIncoming_t *pInMsg )
  1091. {
  1092. uint8 index;
  1093. uint8 status = ZFailure;
  1094. uint8 MACu[KEY_ESTABLISH_MAC_KEY_LENGTH];
  1095. uint8 MACv[KEY_ESTABLISH_MAC_KEY_LENGTH];
  1096. TermKeyStatus_t keyStatus = TermKeyStatus_Success;
  1097. // Stop the Config Key Generate aging timer because the message has been received
  1098. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  1099. // Check state of the key establishment record. If not match, terminate the procedure
  1100. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  1101. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1102. {
  1103. if ( keyEstablishRec[index].role == KEY_ESTABLISHMENT_RESPONDER &&
  1104. keyEstablishRec[index].state == KeyEstablishState_ConfirmPending )
  1105. {
  1106. status = ZSuccess;
  1107. }
  1108. else
  1109. {
  1110. // Reset the entry
  1111. zclGeneral_ResetKeyEstablishRec( index );
  1112. }
  1113. }
  1114. if ( status == ZFailure )
  1115. {
  1116. keyStatus = TermKeyStatus_BadMessage;
  1117. }
  1118. else
  1119. {
  1120. // Calculate MAC(U). Note that the zData is also pointing to the macKey
  1121. zclGeneral_KeyEstablishment_GenerateMAC( index, TRUE, MACu );
  1122. // Compare MAC(U) with MAC(V)
  1123. if ( osal_memcmp( MACu, pInMsg->pData, KEY_ESTABLISH_MAC_LENGTH ) == TRUE )
  1124. {
  1125. // Send Confirm Key Response with Status - SUCCESS
  1126. keyEstablishRec[index].state = KeyEstablishState_TerminationPending;
  1127. // Store the key in the key table
  1128. ZDSecMgrAddLinkKey( pInMsg->msg->srcAddr.addr.shortAddr,
  1129. keyEstablishRec[index].partnerExtAddr,
  1130. keyEstablishRec[index].pKey );
  1131. // Calculate MAC(V) and send it back
  1132. zclGeneral_KeyEstablishment_GenerateMAC( index, FALSE, MACv );
  1133. zclGeneral_KeyEstablish_Send_ConfirmKeyRsp( pInMsg->msg->endPoint,
  1134. &pInMsg->msg->srcAddr,
  1135. MACv,
  1136. FALSE, pInMsg->hdr.transSeqNum );
  1137. }
  1138. else
  1139. {
  1140. keyStatus = TermKeyStatus_BadKeyConfirm;
  1141. }
  1142. // Reset the entry, at this point the Key Establishment process has
  1143. // finished and the record is not needed anymore
  1144. zclGeneral_ResetKeyEstablishRec( index );
  1145. }
  1146. if( keyStatus != TermKeyStatus_Success)
  1147. {
  1148. // If MAC(U) does not match MAC(V), send response with failure
  1149. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1150. &pInMsg->msg->srcAddr,
  1151. keyStatus,
  1152. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1153. KEY_ESTABLISHMENT_SUITE,
  1154. ZCL_FRAME_SERVER_CLIENT_DIR,
  1155. FALSE, zcl_SeqNum++ );
  1156. }
  1157. #if defined (NWK_AUTO_POLL)
  1158. // Key Establishment Procedure complete. Restore the saved poll rate for end device
  1159. NLME_SetPollRate(zclSavedPollRate);
  1160. #endif
  1161. return ZCL_STATUS_CMD_HAS_RSP;
  1162. }
  1163. /*********************************************************************
  1164. * @fn zclGeneral_ProcessInCmd_ConfirmKeyRsp
  1165. *
  1166. * @brief Process the received Confirm Key Response.
  1167. *
  1168. * @param pInMsg - pointer to the incoming message
  1169. *
  1170. * @return ZStatus_t - ZFailure @ Unsupported
  1171. * ZCL_STATUS_MALFORMED_COMMAND
  1172. * ZCL_STATUS_CMD_HAS_RSP
  1173. * ZCL_STATUS_SOFTWARE_FAILURE
  1174. */
  1175. static ZStatus_t zclGeneral_ProcessInCmd_ConfirmKeyRsp( zclIncoming_t *pInMsg )
  1176. {
  1177. uint8 index;
  1178. uint8 status = ZFailure;
  1179. uint8 MACv[KEY_ESTABLISH_MAC_LENGTH];
  1180. // Stop the Config Key Generate aging timer because the message has been received
  1181. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  1182. // Check state of the key establishment record. If not match, terminate the procedure
  1183. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  1184. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1185. {
  1186. if ( keyEstablishRec[index].role == KEY_ESTABLISHMENT_INITIATOR &&
  1187. keyEstablishRec[index].state == KeyEstablishState_ConfirmPending )
  1188. {
  1189. status = ZSuccess;
  1190. }
  1191. else
  1192. {
  1193. // Reset the entry from the rec table
  1194. zclGeneral_ResetKeyEstablishRec( index );
  1195. }
  1196. }
  1197. if ( status == ZFailure )
  1198. {
  1199. status = TermKeyStatus_BadMessage;
  1200. }
  1201. else
  1202. {
  1203. // Calculate MAC(V)
  1204. zclGeneral_KeyEstablishment_GenerateMAC( index, FALSE, MACv);
  1205. // Compare M(U) with M(V)
  1206. if ( osal_memcmp( MACv, pInMsg->pData, KEY_ESTABLISH_MAC_LENGTH ) == TRUE )
  1207. {
  1208. status = TermKeyStatus_Success;
  1209. // Store the link key
  1210. ZDSecMgrAddLinkKey( pInMsg->msg->srcAddr.addr.shortAddr,
  1211. keyEstablishRec[index].partnerExtAddr,
  1212. keyEstablishRec[index].pKey );
  1213. }
  1214. else
  1215. {
  1216. // If MAC(U) does not match MAC(V), send response with failure
  1217. status = TermKeyStatus_BadKeyConfirm;
  1218. }
  1219. }
  1220. if( status != TermKeyStatus_Success )
  1221. {
  1222. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1223. &pInMsg->msg->srcAddr,
  1224. (TermKeyStatus_t)status,
  1225. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1226. KEY_ESTABLISHMENT_SUITE,
  1227. ZCL_FRAME_CLIENT_SERVER_DIR,
  1228. FALSE, zcl_SeqNum++ );
  1229. }
  1230. // Send Osal message to the application to indicate the completion
  1231. if ( keyEstablishRec[index].appTaskID != INVALID_TASK_ID )
  1232. {
  1233. keyEstablishmentInd_t *ind;
  1234. ind = (keyEstablishmentInd_t *)osal_msg_allocate( sizeof( keyEstablishmentInd_t ) );
  1235. if ( ind )
  1236. {
  1237. ind->hdr.event = ZCL_KEY_ESTABLISH_IND;
  1238. ind->hdr.status = status;
  1239. // Clear remaining fields
  1240. ind->waitTime = 0;
  1241. ind->keyEstablishmentSuite = 0;
  1242. osal_msg_send( keyEstablishRec[index].appTaskID, (uint8*)ind );
  1243. }
  1244. }
  1245. // End of this transection. Reset the entry from the rec table
  1246. zclGeneral_ResetKeyEstablishRec( index );
  1247. #if defined (NWK_AUTO_POLL)
  1248. // Key Establishment Procedure complete. Restore the saved poll rate for end device
  1249. NLME_SetPollRate(zclSavedPollRate);
  1250. #endif
  1251. return ZCL_STATUS_CMD_HAS_RSP;
  1252. }
  1253. /*********************************************************************
  1254. * @fn zclGeneral_ProcessInCmd_TerminateKeyEstablish
  1255. *
  1256. * @brief Process the received Terminate Key Establishment Command.
  1257. *
  1258. * @param pInMsg - pointer to the incoming message
  1259. *
  1260. * @return ZStatus_t - ZFailure @ Unsupported
  1261. * ZSuccess @ Success
  1262. */
  1263. static ZStatus_t zclGeneral_ProcessInCmd_TerminateKeyEstablish( zclIncoming_t *pInMsg )
  1264. {
  1265. uint8 index;
  1266. // Find the key establishment record and delete the record entry.
  1267. if ( ( index = zclGeneral_GetKeyEstablishRecIndex( pInMsg->msg->srcAddr.addr.shortAddr ) )
  1268. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1269. {
  1270. if ( keyEstablishRec[index].appTaskID != INVALID_TASK_ID )
  1271. {
  1272. keyEstablishmentInd_t *ind;
  1273. // Send osal message to the application
  1274. ind = (keyEstablishmentInd_t *)osal_msg_allocate( sizeof( keyEstablishmentInd_t ) );
  1275. if ( ind )
  1276. {
  1277. ind->hdr.event = ZCL_KEY_ESTABLISH_IND;
  1278. ind->hdr.status = pInMsg->pData[0];
  1279. ind->waitTime = pInMsg->pData[1];
  1280. ind->keyEstablishmentSuite = BUILD_UINT16( pInMsg->pData[2], pInMsg->pData[3] );
  1281. osal_msg_send( keyEstablishRec[index].appTaskID, (uint8*)ind );
  1282. }
  1283. }
  1284. // In either case, remove the entry from the rec table
  1285. zclGeneral_ResetKeyEstablishRec( index );
  1286. #if defined (NWK_AUTO_POLL)
  1287. // Restore the saved poll rate for end device
  1288. NLME_SetPollRate(zclSavedPollRate);
  1289. #endif
  1290. }
  1291. return ZSuccess;
  1292. }
  1293. /*********************************************************************
  1294. * @fn zclGeneral_InitiateKeyEstablish_Cmd_CalculateKey
  1295. *
  1296. * @brief Calculate the Key using ECC library upon receipt of Initiate
  1297. Key Establishment Command.
  1298. *
  1299. * @param none
  1300. *
  1301. * @return ZStatus_t - ZFailure @ Entry pending key calculation not found
  1302. * ZSuccess
  1303. */
  1304. static ZStatus_t zclGeneral_InitiateKeyEstablish_Cmd_CalculateKey( void )
  1305. {
  1306. uint8 zData[KEY_ESTABLISH_SHARED_SECRET_LENGTH];
  1307. uint8 *caPublicKey, *devicePrivateKey, *keyBit;
  1308. uint8 index, status, tmp;
  1309. // It is possible to have multiple entries in the keyCalulationPending state.
  1310. // Here we assume the partner that starts the key establishment procedure earlier
  1311. // will have a smaller index in the table.
  1312. // However, this might not apply due to different processing capability of
  1313. // different processors.
  1314. if ( (index = zclGeneral_GetKeyEstablishRecIndex_State( KeyEstablishState_KeyCalculatePending ))
  1315. >= MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1316. {
  1317. return ZFailure;
  1318. }
  1319. if ((caPublicKey = osal_mem_alloc(ZCL_KE_CA_PUBLIC_KEY_LEN)) == NULL)
  1320. {
  1321. // Reset the entry
  1322. zclGeneral_ResetKeyEstablishRec( index );
  1323. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  1324. }
  1325. if ((devicePrivateKey = osal_mem_alloc(ZCL_KE_DEVICE_PRIVATE_KEY_LEN)) == NULL)
  1326. {
  1327. osal_mem_free(caPublicKey);
  1328. // Reset the entry
  1329. zclGeneral_ResetKeyEstablishRec( index );
  1330. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  1331. }
  1332. osal_nv_read(ZCD_NV_CA_PUBLIC_KEY, 0, ZCL_KE_CA_PUBLIC_KEY_LEN, caPublicKey);
  1333. osal_nv_read(ZCD_NV_DEVICE_PRIVATE_KEY, 0, ZCL_KE_DEVICE_PRIVATE_KEY_LEN, devicePrivateKey);
  1334. // Turn off the radio
  1335. tmp = FALSE;
  1336. ZMacSetReq( ZMacRxOnIdle, &tmp );
  1337. status = ZSE_ECCKeyBitGenerate( devicePrivateKey, keyEstablishRec[index].pLocalEPrivateKey,
  1338. keyEstablishRec[index].pLocalEPublicKey,
  1339. keyEstablishRec[index].pRemoteCertificate,
  1340. keyEstablishRec[index].pRemotePublicKey,
  1341. caPublicKey, zData,
  1342. zclGeneral_KeyEstablishment_HashFunc,
  1343. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel);
  1344. tmp = TRUE;
  1345. ZMacSetReq( ZMacRxOnIdle, &tmp ); // Turn the radio back on
  1346. osal_mem_free(caPublicKey);
  1347. osal_mem_free(devicePrivateKey);
  1348. if( status == MCE_SUCCESS )
  1349. {
  1350. // Allocate buffer to store KDF(Z) = MacKey || KeyData
  1351. if ( (keyBit = osal_mem_alloc( KEY_ESTABLISH_KEY_DATA_LENGTH +
  1352. KEY_ESTABLISH_MAC_KEY_LENGTH)) == NULL )
  1353. {
  1354. // Reset the entry
  1355. zclGeneral_ResetKeyEstablishRec( index );
  1356. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure
  1357. }
  1358. // Derive the keying data using KDF function
  1359. zclGeneral_KeyEstablishment_KeyDeriveFunction(zData,
  1360. KEY_ESTABLISH_SHARED_SECRET_LENGTH,
  1361. keyBit );
  1362. // Save the derived 128-bit key and macKey
  1363. osal_memcpy( keyEstablishRec[index].pMacKey, keyBit, KEY_ESTABLISH_MAC_KEY_LENGTH );
  1364. osal_memcpy( keyEstablishRec[index].pKey, &(keyBit[KEY_ESTABLISH_MAC_KEY_LENGTH]),
  1365. KEY_ESTABLISH_KEY_DATA_LENGTH);
  1366. osal_mem_free( keyBit );
  1367. // Key Bit generation success, send Ephemeral Data Response back
  1368. zclGeneral_KeyEstablish_Send_EphemeralDataRsp( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1369. &(keyEstablishRec[index].dstAddr),
  1370. keyEstablishRec[index].pLocalEPublicKey,
  1371. FALSE, keyEstablishRec[index].lastSeqNum );
  1372. // The Request was processed successfuly, now the age timer needs to start based on the
  1373. // remote Config Key Generate
  1374. keyEstablishRec[index].age = keyEstablishRec[index].remoteConfKeyGenTime;
  1375. // Start the Config Key Generate aging timer
  1376. osal_start_reload_timer( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT,
  1377. KEY_ESTABLISHMENT_REC_AGING_INTERVAL );
  1378. }
  1379. else
  1380. {
  1381. // Key Bit generation failure. Send terminate key command
  1382. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1383. &(keyEstablishRec[index].dstAddr),
  1384. TermKeyStatus_BadKeyConfirm,
  1385. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1386. KEY_ESTABLISHMENT_SUITE,
  1387. ZCL_FRAME_SERVER_CLIENT_DIR,
  1388. FALSE, zcl_SeqNum++ );
  1389. // Reset the entry
  1390. zclGeneral_ResetKeyEstablishRec( index );
  1391. #if defined (NWK_AUTO_POLL)
  1392. // Restore the saved poll rate for end device
  1393. NLME_SetPollRate(zclSavedPollRate);
  1394. #endif
  1395. return ZFailure;
  1396. }
  1397. keyEstablishRec[index].state = KeyEstablishState_ConfirmPending;
  1398. return ZSuccess;
  1399. }
  1400. /*********************************************************************
  1401. * @fn zclGeneral_InitiateKeyEstablish_Rsp_CalculateKey
  1402. *
  1403. * @brief Calculate the Key using ECC library upon receipt of
  1404. * Ephemeral Data Response.
  1405. *
  1406. * @param none
  1407. *
  1408. * @return ZStatus_t - ZFailure @ Unsupported
  1409. * ZCL_STATUS_MALFORMED_COMMAND
  1410. * ZCL_STATUS_CMD_HAS_RSP
  1411. */
  1412. static ZStatus_t zclGeneral_InitiateKeyEstablish_Rsp_CalculateKey( void )
  1413. {
  1414. uint8 zData[KEY_ESTABLISH_SHARED_SECRET_LENGTH];
  1415. uint8 MACu[KEY_ESTABLISH_MAC_LENGTH];
  1416. uint8 *caPublicKey, *devicePrivateKey, *keyBit;
  1417. uint8 index, ret, tmp, currentRxState;
  1418. // It is possible to have multiple entries in the keyCalulationPending state.
  1419. // Here we assume the partner that starts the key establishment procedure earlier
  1420. // will have a smaller index in the table.
  1421. // However, this might not apply due to different processing capability of
  1422. // different processors.
  1423. if ( (index = zclGeneral_GetKeyEstablishRecIndex_State( KeyEstablishState_KeyCalculatePending ))
  1424. >= MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1425. {
  1426. return ZFailure;
  1427. }
  1428. if ((caPublicKey = osal_mem_alloc(ZCL_KE_CA_PUBLIC_KEY_LEN)) == NULL)
  1429. {
  1430. // Reset the entry from the rec table
  1431. zclGeneral_ResetKeyEstablishRec( index );
  1432. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  1433. }
  1434. if ((devicePrivateKey = osal_mem_alloc(ZCL_KE_DEVICE_PRIVATE_KEY_LEN)) == NULL)
  1435. {
  1436. // Reset the entry from the rec table
  1437. zclGeneral_ResetKeyEstablishRec( index );
  1438. osal_mem_free(caPublicKey);
  1439. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  1440. }
  1441. osal_nv_read(ZCD_NV_CA_PUBLIC_KEY, 0, ZCL_KE_CA_PUBLIC_KEY_LEN, caPublicKey);
  1442. osal_nv_read(ZCD_NV_DEVICE_PRIVATE_KEY, 0, ZCL_KE_DEVICE_PRIVATE_KEY_LEN, devicePrivateKey);
  1443. ZMacGetReq( ZMacRxOnIdle, &currentRxState ); // Save current radio state
  1444. // Turn off the radio before the key bit generation, in order to avoid
  1445. // incoming messages accumulation by interrupts during the long process time.
  1446. tmp = FALSE;
  1447. ZMacSetReq( ZMacRxOnIdle, &tmp );
  1448. // Generate the Key Bits
  1449. ret = ZSE_ECCKeyBitGenerate( devicePrivateKey, keyEstablishRec[index].pLocalEPrivateKey,
  1450. keyEstablishRec[index].pLocalEPublicKey,
  1451. keyEstablishRec[index].pRemoteCertificate,
  1452. keyEstablishRec[index].pRemotePublicKey,
  1453. caPublicKey, zData,
  1454. zclGeneral_KeyEstablishment_HashFunc,
  1455. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel);
  1456. ZMacSetReq( ZMacRxOnIdle, &currentRxState ); // Resume saved radio state
  1457. osal_mem_free(caPublicKey);
  1458. osal_mem_free(devicePrivateKey);
  1459. if ( ret != MCE_SUCCESS )
  1460. {
  1461. // Key Bit generation failure. Send terminate key command
  1462. zclGeneral_KeyEstablish_Send_TerminateKeyEstablishment( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1463. &(keyEstablishRec[index].dstAddr),
  1464. TermKeyStatus_BadKeyConfirm,
  1465. KEY_ESTABLISHMENT_AVG_TIMEOUT,
  1466. KEY_ESTABLISHMENT_SUITE,
  1467. ZCL_FRAME_CLIENT_SERVER_DIR,
  1468. FALSE, zcl_SeqNum++ );
  1469. // Reset the entry from the rec table
  1470. zclGeneral_ResetKeyEstablishRec( index );
  1471. #if defined (NWK_AUTO_POLL)
  1472. // Restore the saved poll rate for end device
  1473. NLME_SetPollRate(zclSavedPollRate);
  1474. #endif
  1475. return ZFailure;
  1476. }
  1477. else
  1478. {
  1479. // Allocate buffer to store KDF(Z) = MacKey || KeyData
  1480. if ( (keyBit = osal_mem_alloc( KEY_ESTABLISH_KEY_DATA_LENGTH +
  1481. KEY_ESTABLISH_MAC_KEY_LENGTH)) == NULL )
  1482. {
  1483. // Reset the entry from the rec table
  1484. zclGeneral_ResetKeyEstablishRec( index );
  1485. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure
  1486. }
  1487. // Derive the keying data using KDF function
  1488. zclGeneral_KeyEstablishment_KeyDeriveFunction(zData,
  1489. KEY_ESTABLISH_SHARED_SECRET_LENGTH,
  1490. keyBit );
  1491. // Save the derived 128-bit keyData
  1492. osal_memcpy( keyEstablishRec[index].pMacKey, keyBit, KEY_ESTABLISH_KEY_DATA_LENGTH);
  1493. osal_memcpy( keyEstablishRec[index].pKey, &(keyBit[KEY_ESTABLISH_MAC_KEY_LENGTH]),
  1494. KEY_ESTABLISH_KEY_DATA_LENGTH);
  1495. // Calculate MAC(U). Note that the keyBit is also pointing to the macKey
  1496. zclGeneral_KeyEstablishment_GenerateMAC( index, TRUE, MACu );
  1497. osal_mem_free( keyBit );
  1498. // Send MAC(U) to the Partner
  1499. zclGeneral_KeyEstablish_Send_ConfirmKey( ZCL_KEY_ESTABLISHMENT_ENDPOINT,
  1500. &(keyEstablishRec[index].dstAddr),
  1501. MACu,
  1502. FALSE, zcl_SeqNum++ );
  1503. // The Request was processed successfuly, now the age timer needs to start based on the
  1504. // remote Config Key Generate
  1505. keyEstablishRec[index].age = keyEstablishRec[index].remoteConfKeyGenTime;
  1506. // Start the Config Key Generate aging timer
  1507. osal_start_reload_timer( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT,
  1508. KEY_ESTABLISHMENT_REC_AGING_INTERVAL );
  1509. keyEstablishRec[index].state = KeyEstablishState_ConfirmPending;
  1510. return ZSuccess;
  1511. }
  1512. }
  1513. /*********************************************************************
  1514. * @fn zclGeneral_InitKeyEstablishRecTable
  1515. *
  1516. * @brief Initializae key establishment record table entries.
  1517. *
  1518. * @param none
  1519. *
  1520. * @return none
  1521. */
  1522. static void zclGeneral_InitKeyEstablishRecTable( void )
  1523. {
  1524. uint8 i;
  1525. for ( i = 0; i < MAX_KEY_ESTABLISHMENT_REC_ENTRY; i++ )
  1526. {
  1527. zclGeneral_ResetKeyEstablishRec(i);
  1528. }
  1529. }
  1530. /*********************************************************************
  1531. * @fn zclGeneral_GetKeyEstablishRecIndex
  1532. *
  1533. * @brief Get the index of a particular key establishment record.
  1534. * If the input is INVALID_PARTNER_ADDR, return an empty slot.
  1535. *
  1536. * @param partnerAddress - address of the partner that the local device
  1537. * is establishing key with.
  1538. *
  1539. * @return index of the record
  1540. */
  1541. static uint8 zclGeneral_GetKeyEstablishRecIndex( uint16 partnerAddress )
  1542. {
  1543. uint8 i;
  1544. // Find an existing entry or vacant entry, depends on what DstAddress is
  1545. for ( i = 0; i < MAX_KEY_ESTABLISHMENT_REC_ENTRY ; i++ )
  1546. {
  1547. if ( keyEstablishRec[i].dstAddr.addr.shortAddr == partnerAddress )
  1548. {
  1549. // entry found
  1550. break;
  1551. }
  1552. }
  1553. return i;
  1554. }
  1555. /*********************************************************************
  1556. * @fn zclGeneral_GetKeyEstablishRecIndex
  1557. *
  1558. * @brief Get the index of a particular key establishment record.
  1559. * If the input is INVALID_PARTNER_ADDR, return an empty slot.
  1560. *
  1561. * @param state - state to find.
  1562. *
  1563. * @return index of the record
  1564. */
  1565. static uint8 zclGeneral_GetKeyEstablishRecIndex_State( KeyEstablishState_t state )
  1566. {
  1567. uint8 i;
  1568. // Find an existing entry or vacant entry, depends on what DstAddress is
  1569. for ( i = 0; i < MAX_KEY_ESTABLISHMENT_REC_ENTRY ; i++ )
  1570. {
  1571. if ( keyEstablishRec[i].state == state )
  1572. {
  1573. // entry found
  1574. break;
  1575. }
  1576. }
  1577. return i;
  1578. }
  1579. /*********************************************************************
  1580. * @fn zclGeneral_AddKeyEstablishRec
  1581. *
  1582. * @brief Add a new key establishment record. If one already exist,
  1583. * remove the existng entry. After initialization, fill in
  1584. * partner short address and extended address. If partner extended
  1585. * address not available, return failure.
  1586. *
  1587. * @param addr - address of the partner
  1588. *
  1589. * @return index - 0..(MAX_KEY_ESTABLISHMENT_REC_ENTRY-1) @ success
  1590. * - MAX_KEY_ESTABLISHMENT_REC_ENTRY @ failure due to rec table full or
  1591. * partner IEEE address not available or failure to allocate key buffers.
  1592. */
  1593. static uint8 zclGeneral_AddKeyEstablishRec( afAddrType_t *addr )
  1594. {
  1595. uint8 index, *pBuf;
  1596. // Search for all current key establishment record
  1597. // If not found, create a new entry
  1598. if ( ( index = zclGeneral_GetKeyEstablishRecIndex(addr->addr.shortAddr) )
  1599. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1600. {
  1601. // expire the existing entry for this address
  1602. zclGeneral_ResetKeyEstablishRec( index );
  1603. }
  1604. // Create a new Entry
  1605. if ( (index = zclGeneral_GetKeyEstablishRecIndex(INVALID_PARTNER_ADDR))
  1606. < MAX_KEY_ESTABLISHMENT_REC_ENTRY )
  1607. {
  1608. // Allocate memory for the rest of the fields
  1609. if ( (pBuf = osal_mem_alloc( ZCL_KE_DEVICE_PRIVATE_KEY_LEN +
  1610. ZCL_KE_CA_PUBLIC_KEY_LEN +
  1611. ZCL_KE_CA_PUBLIC_KEY_LEN +
  1612. ZCL_KE_IMPLICIT_CERTIFICATE_LEN +
  1613. KEY_ESTABLISH_KEY_DATA_LENGTH +
  1614. KEY_ESTABLISH_MAC_KEY_LENGTH )) != NULL )
  1615. {
  1616. keyEstablishRec[index].pLocalEPrivateKey = pBuf;
  1617. pBuf += ZCL_KE_DEVICE_PRIVATE_KEY_LEN;
  1618. keyEstablishRec[index].pLocalEPublicKey = pBuf;
  1619. pBuf += ZCL_KE_CA_PUBLIC_KEY_LEN;
  1620. keyEstablishRec[index].pRemotePublicKey = pBuf;
  1621. pBuf += ZCL_KE_CA_PUBLIC_KEY_LEN;
  1622. keyEstablishRec[index].pRemoteCertificate = pBuf;
  1623. pBuf += ZCL_KE_IMPLICIT_CERTIFICATE_LEN;
  1624. keyEstablishRec[index].pKey = pBuf;
  1625. pBuf += KEY_ESTABLISH_KEY_DATA_LENGTH;
  1626. keyEstablishRec[index].pMacKey = pBuf;
  1627. (void)osal_memcpy(&keyEstablishRec[index].dstAddr, addr, sizeof(afAddrType_t));
  1628. // extAddr will be unknown when the initator first initiates the key establishment
  1629. // It will be filled in later after the remote certificate is received.
  1630. }
  1631. else
  1632. {
  1633. index = MAX_KEY_ESTABLISHMENT_REC_ENTRY;
  1634. }
  1635. }
  1636. return index;
  1637. }
  1638. /*********************************************************************
  1639. * @fn zclGeneral_AgeKeyEstablishRec
  1640. *
  1641. * @brief Function to age Key Establish Rec. This function is called
  1642. * as event handler for KEY_ESTABLISHMENT_REC_AGING_EVT every
  1643. * second.
  1644. *
  1645. * @param none
  1646. *
  1647. * @return none
  1648. */
  1649. static void zclGeneral_AgeKeyEstablishRec( void )
  1650. {
  1651. uint8 i;
  1652. bool recFound = FALSE;
  1653. for ( i = 0; i < MAX_KEY_ESTABLISHMENT_REC_ENTRY; i++ )
  1654. {
  1655. // Only age valid rec entry
  1656. if (keyEstablishRec[i].dstAddr.addrMode == afAddrNotPresent)
  1657. {
  1658. continue;
  1659. }
  1660. if (--(keyEstablishRec[i].age) == 0)
  1661. {
  1662. // Reset this table entry
  1663. zclGeneral_ResetKeyEstablishRec( i );
  1664. }
  1665. else
  1666. {
  1667. recFound = TRUE;
  1668. }
  1669. }
  1670. if ( recFound == FALSE )
  1671. {
  1672. osal_stop_timerEx( zcl_KeyEstablishment_TaskID, KEY_ESTABLISHMENT_REC_AGING_EVT );
  1673. }
  1674. }
  1675. /*********************************************************************
  1676. * @fn zclGeneral_ResetKeyEstablishRec
  1677. *
  1678. * @brief Reset specified key establishment record to initial value.
  1679. *
  1680. * @param index - index of table entry to reset
  1681. *
  1682. * @return ZStatus_t - ZSuccess or ZFailure
  1683. */
  1684. static void zclGeneral_ResetKeyEstablishRec( uint8 index )
  1685. {
  1686. uint8 *pKeys;
  1687. pKeys = keyEstablishRec[index].pLocalEPrivateKey;
  1688. if ( pKeys != NULL )
  1689. {
  1690. // All "Key infomation" was allocated in one block,
  1691. // Clear the allocated memory to remove all copies of keys,
  1692. (void)osal_memset( pKeys, 0, ZCL_KE_DEVICE_PRIVATE_KEY_LEN +
  1693. ZCL_KE_CA_PUBLIC_KEY_LEN +
  1694. ZCL_KE_CA_PUBLIC_KEY_LEN +
  1695. ZCL_KE_IMPLICIT_CERTIFICATE_LEN +
  1696. KEY_ESTABLISH_KEY_DATA_LENGTH +
  1697. KEY_ESTABLISH_MAC_KEY_LENGTH );
  1698. osal_mem_free( pKeys );
  1699. }
  1700. // Reset the table entry to initial state
  1701. (void)osal_memset( &(keyEstablishRec[index]), 0, sizeof( zclKeyEstablishRec_t ) );
  1702. keyEstablishRec[index].dstAddr.addrMode = afAddrNotPresent;
  1703. keyEstablishRec[index].dstAddr.addr.shortAddr = INVALID_PARTNER_ADDR;
  1704. keyEstablishRec[index].appTaskID = INVALID_TASK_ID;
  1705. keyEstablishRec[index].age = KEY_ESTABLISHMENT_REC_EXPIRY_TIME;
  1706. keyEstablishRec[index].state = KeyEstablishState_Idle;
  1707. keyEstablishRec[index].remoteEphDataGenTime = KEY_ESTABLISHMENT_EPH_DATA_GEN_INVALID_TIME;
  1708. keyEstablishRec[index].remoteConfKeyGenTime = KEY_ESTABLISHMENT_CONF_KEY_GEN_INVALID_TIME;
  1709. }
  1710. /*********************************************************************
  1711. * @fn zclGeneral_KeyEstablishment_GetRandom
  1712. *
  1713. * @brief Fill in a buffer with random numbers
  1714. *
  1715. * @param buffer - output buffer
  1716. * len - length of the buffer
  1717. *
  1718. * @return MCE_SUCCESS indicates success
  1719. */
  1720. static int zclGeneral_KeyEstablishment_GetRandom(unsigned char *buffer, unsigned long len)
  1721. {
  1722. uint8 *pBuf;
  1723. pBuf = buffer;
  1724. // Input to SSP_GetTrueRandAES assumes len <= SEC_KEY_LEN
  1725. // Therefore, call SSP_GetTrueRandAES multiple times to
  1726. // fill out the buffer.
  1727. while( len > SEC_KEY_LEN )
  1728. {
  1729. SSP_GetTrueRandAES( SEC_KEY_LEN, pBuf );
  1730. len -= SEC_KEY_LEN;
  1731. pBuf += SEC_KEY_LEN;
  1732. }
  1733. SSP_GetTrueRandAES( len, pBuf );
  1734. return MCE_SUCCESS;
  1735. }
  1736. /*********************************************************************
  1737. * @fn zclGeneral_KeyEstablishment_HashFunc
  1738. *
  1739. * @brief Hash Function
  1740. *
  1741. * @param digest - output buffer 16 bytes
  1742. * len - length of the input buffer
  1743. * data - input buffer
  1744. *
  1745. * @return MCE_SUCCESS indicates success
  1746. */
  1747. static int zclGeneral_KeyEstablishment_HashFunc(unsigned char *digest, unsigned long len, unsigned char *data)
  1748. {
  1749. len *= 8; // Convert to bit length
  1750. sspMMOHash( NULL, 0, data, (uint16)len, digest );
  1751. return MCE_SUCCESS;
  1752. }
  1753. /*********************************************************************
  1754. * @fn zclGeneral_KeyEstablishment_KeyDeriveFunction
  1755. *
  1756. * @brief Key Derive Function (ANSI X9.63).
  1757. * Note this is not a generalized KDF. It only applies to the KDF
  1758. * specified in ZigBee SE profile. Only the first two hashed keys
  1759. * are calculated and concatenated.
  1760. *
  1761. * @param zData - input shared secret (length = KEY_ESTABLISH_SHARED_SECRET_LENGTH)
  1762. * keyBitLen - input key data length
  1763. * keyBit - output buffer ( 16*2 bytes)
  1764. *
  1765. * @return none
  1766. */
  1767. static void zclGeneral_KeyEstablishment_KeyDeriveFunction( uint8 *zData,
  1768. uint8 keyBitLen,
  1769. uint8 *keyBit )
  1770. {
  1771. uint8 hashCounter[4] = {0x00, 0x00, 0x00, 0x01};
  1772. uint8 hashedData[KEY_ESTABLISH_SHARED_SECRET_LENGTH + 4];
  1773. uint8 bitLen;
  1774. bitLen = (keyBitLen + 4 ) * 8;
  1775. // Calculate K1: Ki = Hash(Z || Counter1 )
  1776. osal_memcpy( hashedData, zData, KEY_ESTABLISH_SHARED_SECRET_LENGTH );
  1777. osal_memcpy( &(hashedData[KEY_ESTABLISH_SHARED_SECRET_LENGTH]), hashCounter, 4);
  1778. sspMMOHash(NULL, 0, hashedData, bitLen, keyBit);
  1779. // Indrement the counter
  1780. hashedData[KEY_ESTABLISH_SHARED_SECRET_LENGTH + 3] = 0x02;
  1781. sspMMOHash(NULL, 0, hashedData, bitLen, &(keyBit[KEY_ESTABLISH_KEY_DATA_LENGTH]));
  1782. }
  1783. /*********************************************************************
  1784. * @fn zclGeneral_KeyEstablishment_GenerateMAC
  1785. *
  1786. * @brief Key Derive Function (ANSI X9.63).
  1787. * Note this is not a generalized KDF. It only applies to the KDF
  1788. * specified in ZigBee SE profile. Only the first two hashed keys
  1789. * are calculated and concatenated.
  1790. *
  1791. * @param recIndex - input key establishment record index
  1792. * ifMACu - use M(U) if TRUE, otherwise M(V)
  1793. * MAC - output buffer ( 16 bytes )
  1794. *
  1795. * @return ZStatus_t - success
  1796. */
  1797. static ZStatus_t zclGeneral_KeyEstablishment_GenerateMAC(uint8 recIndex,
  1798. uint8 ifMACu,
  1799. uint8 *MAC)
  1800. {
  1801. uint8 i;
  1802. uint8 M;
  1803. uint8 *hashBuf;
  1804. uint16 bufLen;
  1805. // Assumption for M(U) and M(V) is: M(U) = 0x02, M(V) = 0x03
  1806. if( ifMACu == TRUE )
  1807. {
  1808. M = 0x02; // Assumption
  1809. }
  1810. else
  1811. {
  1812. M = 0x03; // Assumption
  1813. }
  1814. // At this point, it is assumed the device has already
  1815. // obtained the IEEE address of the partner device.
  1816. for ( i = 0; i < Z_EXTADDR_LEN; i++ )
  1817. {
  1818. if ( keyEstablishRec[recIndex].partnerExtAddr[i] != 0 )
  1819. {
  1820. break;
  1821. }
  1822. }
  1823. if ( i == Z_EXTADDR_LEN )
  1824. {
  1825. return ZFailure; // Partner IEEE address not available, return failure.
  1826. }
  1827. // MAC(U) = MAC(MacKey) { M(U) || ID(U) || ID(V) || E(U) || E(V) }
  1828. bufLen = (1 + (Z_EXTADDR_LEN * 2) + (ZCL_KE_CA_PUBLIC_KEY_LEN * 2));
  1829. if( ( hashBuf = osal_mem_alloc( (bufLen) )) == NULL )
  1830. {
  1831. return ZMemError; // Memory allocation error
  1832. }
  1833. // Fill in the buffer
  1834. hashBuf[0] = M; // M(U)
  1835. bufLen = bufLen * 8; // Convert to bitlength
  1836. if ( (keyEstablishRec[recIndex].role == KEY_ESTABLISHMENT_INITIATOR && ifMACu == TRUE) ||
  1837. (keyEstablishRec[recIndex].role == KEY_ESTABLISHMENT_RESPONDER && ifMACu == FALSE))
  1838. {
  1839. // MAC = MAC(MacKey) { M() || ID(L) || ID(R) || E(L) || E(R) }
  1840. // L - Local, R - Remote
  1841. SSP_MemCpyReverse( &(hashBuf[1]), NLME_GetExtAddr(), Z_EXTADDR_LEN); // ID(U)
  1842. SSP_MemCpyReverse( &(hashBuf[1+Z_EXTADDR_LEN]), keyEstablishRec[recIndex].partnerExtAddr,
  1843. Z_EXTADDR_LEN); // ID(V)
  1844. osal_memcpy( &(hashBuf[1 + (2 * Z_EXTADDR_LEN)]), // E(U)
  1845. keyEstablishRec[recIndex].pLocalEPublicKey,
  1846. ZCL_KE_CA_PUBLIC_KEY_LEN );
  1847. osal_memcpy( &(hashBuf[1 + (2 * Z_EXTADDR_LEN) + ZCL_KE_CA_PUBLIC_KEY_LEN]), // E(V)
  1848. keyEstablishRec[recIndex].pRemotePublicKey, ZCL_KE_CA_PUBLIC_KEY_LEN );
  1849. SSP_KeyedHash (hashBuf, bufLen, keyEstablishRec[recIndex].pMacKey, MAC);
  1850. }
  1851. else
  1852. {
  1853. // MAC = MAC(MacKey) { M() || ID(R) || ID(L) || E(R) || E(L) }
  1854. // L - Local, R - Remote
  1855. SSP_MemCpyReverse( &(hashBuf[1]), keyEstablishRec[recIndex].partnerExtAddr,
  1856. Z_EXTADDR_LEN); // ID(R)
  1857. SSP_MemCpyReverse( &(hashBuf[1 + Z_EXTADDR_LEN]), NLME_GetExtAddr(), Z_EXTADDR_LEN); // ID(L)
  1858. osal_memcpy( &(hashBuf[ 1 + (2 * Z_EXTADDR_LEN)]), // E(R)
  1859. keyEstablishRec[recIndex].pRemotePublicKey,
  1860. ZCL_KE_CA_PUBLIC_KEY_LEN );
  1861. osal_memcpy( &(hashBuf[1 + (2 * Z_EXTADDR_LEN) + ZCL_KE_CA_PUBLIC_KEY_LEN]), // E(U)
  1862. keyEstablishRec[recIndex].pLocalEPublicKey,
  1863. ZCL_KE_CA_PUBLIC_KEY_LEN );
  1864. SSP_KeyedHash (hashBuf, bufLen, keyEstablishRec[recIndex].pMacKey, MAC);
  1865. }
  1866. osal_mem_free(hashBuf);
  1867. return ZSuccess;
  1868. }
  1869. /*********************************************************************
  1870. * @fn zclGeneral_KeyEstablishment_ECDSASign
  1871. *
  1872. * @brief Creates an ECDSA signature of a message digest.
  1873. *
  1874. * @param input - input data buffer
  1875. * inputLen - byte length of the input buffer
  1876. * output - output buffer ( 21x2 bytes )
  1877. *
  1878. * @return ZStatus_t - success
  1879. */
  1880. ZStatus_t zclGeneral_KeyEstablishment_ECDSASign( uint8 *input, uint8 inputLen,
  1881. uint8 *output)
  1882. {
  1883. uint8 msgDigest[KEY_ESTABLISH_AES_MMO_HASH_SIZE];
  1884. uint16 bitLen = inputLen * 8;
  1885. uint8 status;
  1886. uint8 *devicePrivateKey;
  1887. if ((devicePrivateKey = osal_mem_alloc(ZCL_KE_DEVICE_PRIVATE_KEY_LEN)) == NULL)
  1888. {
  1889. return ZCL_STATUS_SOFTWARE_FAILURE; // Memory allocation failure.
  1890. }
  1891. osal_nv_read(ZCD_NV_DEVICE_PRIVATE_KEY, 0, ZCL_KE_DEVICE_PRIVATE_KEY_LEN, devicePrivateKey);
  1892. // First hash the input buffer
  1893. sspMMOHash(NULL, 0, input, bitLen, msgDigest);
  1894. status = ZSE_ECDSASign( (unsigned char*)devicePrivateKey, (unsigned char*)msgDigest,
  1895. zclGeneral_KeyEstablishment_GetRandom,
  1896. (unsigned char*)output, (unsigned char*)output + KEY_ESTABLISH_POINT_ORDER_SIZE,
  1897. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel );
  1898. osal_mem_free(devicePrivateKey);
  1899. if (status == MCE_SUCCESS )
  1900. {
  1901. return ZSuccess;
  1902. }
  1903. return ZFailure;
  1904. }
  1905. /*********************************************************************
  1906. * @fn zclGeneral_KeyEstablishment_ECDSAVerify
  1907. *
  1908. * @brief Verify an ECDSA signature of a message digest.
  1909. *
  1910. * @param input - input data buffer
  1911. * inputLen - byte length of the input buffer
  1912. * signature - input signature ( 21x2 bytes )
  1913. *
  1914. * @return ZSuccess - success verify
  1915. * ZFailure - fail to verify
  1916. */
  1917. ZStatus_t zclGeneral_KeyEstablishment_ECDSAVerify( uint8 *input, uint8 inputLen,
  1918. uint8 *signature)
  1919. {
  1920. uint8 msgDigest[KEY_ESTABLISH_AES_MMO_HASH_SIZE];
  1921. uint16 bitLen;
  1922. uint8 ret;
  1923. bitLen = inputLen * 8;
  1924. // First hash the input buffer
  1925. sspMMOHash(NULL, 0, input, bitLen, msgDigest);
  1926. ret = ZSE_ECDSAVerify((unsigned char*)NULL, (unsigned char*)msgDigest,
  1927. (unsigned char*)signature, (unsigned char*)signature + KEY_ESTABLISH_POINT_ORDER_SIZE,
  1928. zclKeyEstablish_YieldFunc, zclKeyEstablish_YieldLevel );
  1929. if ( ret == MCE_SUCCESS )
  1930. {
  1931. return ZSuccess;
  1932. }
  1933. return ZFailure;
  1934. }
  1935. #endif // ZCL_KEY_ESTABLISH
  1936. /***************************************************************************
  1937. ****************************************************************************/