CommandLib.c 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974
  1. /**
  2. * MIT License
  3. *
  4. * Copyright (c) 2018 Infineon Technologies AG
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE
  23. *
  24. *
  25. * \file
  26. *
  27. * \brief This file implements the command library.
  28. *
  29. * \addtogroup grCmdLib
  30. * @{
  31. */
  32. #include <stdint.h>
  33. #include "optiga/common/Util.h"
  34. #include "optiga/cmd/CommandLib.h"
  35. #include "optiga/common/MemoryMgmt.h"
  36. #ifdef USE_CMDLIB_WITH_RTOS
  37. #include "optiga/pal/pal_os_timer.h"
  38. #endif
  39. /// @cond hidden
  40. static optiga_comms_t* p_optiga_comms;
  41. ///Maximum size of buffer, considering Maximum size of arbitrary data (1500) and header bytes
  42. #define MAX_APDU_BUFF_LEN 1558
  43. ///Get Data Parameter
  44. #define PARAM_GET_DATA 0x00
  45. ///Get Meta Data Parameter
  46. #define PARAM_GET_METADATA 0x01
  47. ///Set Data Parameter
  48. #define PARAM_SET_DATA 0x00
  49. ///Set Meta Data Parameter
  50. #define PARAM_SET_METADATA 0x01
  51. ///Erase and Write Parameter
  52. #define PARAM_SET_DATA_ERASE 0x40
  53. ///ECDSA Set Auth message
  54. #define PARAM_SET_AUTH_MSG 0x01
  55. ///ECDSA Get Auth message
  56. #define PARAM_GET_AUTH_MSG 0x02
  57. ///Encrypt Data
  58. #define PARAM_ENC_DATA 0x61
  59. ///Decrypt Data
  60. #define PARAM_DEC_DATA 0x51
  61. ///Number of bytes in CMD
  62. #define BYTES_CMD 0x01
  63. ///Number of bytes in PARAM
  64. #define BYTES_PARAM 0x01
  65. ///Number of bytes in LEN
  66. #define BYTES_LENGTH 0x02
  67. ///Number of bytes in Sequence
  68. #define BYTES_SEQ 0x01
  69. ///Number of bytes in OID
  70. #define BYTES_OID 0x02
  71. ///Number of bytes in OFFSET
  72. #define BYTES_OFFSET 0x02
  73. ///Offset of status in the response APDU
  74. #define OFFSET_RESP_STATUS 0x00
  75. ///Offset of CMD byte
  76. #define OFFSET_CMD (0x00)
  77. ///Offset of PARAM byte
  78. #define OFFSET_PARAM (OFFSET_CMD + BYTES_CMD)
  79. ///Offset of LEN byte
  80. #define OFFSET_LENGTH (OFFSET_PARAM + BYTES_PARAM)
  81. ///Offset of PAYLOAD
  82. #define OFFSET_PAYLOAD (OFFSET_LENGTH + BYTES_LENGTH)
  83. ///Offset of TAG
  84. #define TAG_LENGTH_OFFSET 0x01
  85. ///Offset of TAG + LEN
  86. #define TAG_VALUE_OFFSET 0x03
  87. ///Cmd of Get Data Object
  88. #define CMD_GETDATA 0x01
  89. ///Cmd of Set Data Object
  90. #define CMD_SETDATA 0x02
  91. ///Cmd of Set Auth Scheme
  92. #define CMD_SETAUTH_SCM 0x10
  93. ///Cmd of Set Auth Data
  94. #define CMD_SETAUTH_MSG 0x19
  95. ///Cmd of Get Auth Data
  96. #define CMD_GETAUTH_MSG 0x18
  97. ///Cmd of Get Random
  98. #define CMD_GET_RND 0x0C
  99. ///Cmd of Open Application
  100. #define CMD_OPEN_APP 0x70
  101. ///Cmd for ProcUplinkMsg
  102. #define CMD_GETMSG 0x1A
  103. ///Cmd for ProcDownlinkMsg
  104. #define CMD_PUTMSG 0x1B
  105. ///Cmd for Encrypt Data
  106. #define CMD_ENCDATA CMD_GETMSG
  107. ///Cmd for Decrypt Data
  108. #define CMD_DECDATA CMD_PUTMSG
  109. ///Cmd for CalcHash
  110. #define CMD_CALCHASH 0x30
  111. ///Cmd for VerifySign
  112. #define CMD_VERIFYSIGN 0x32
  113. ///Cmd for GenKeyPair
  114. #define CMD_GENERATE_KEY_PAIR 0x38
  115. ///Cmd for CalcSign
  116. #define CMD_CALC_SIGN 0x31
  117. ///Cmd for CalcSSec
  118. #define CMD_CALC_SHARED_SEC 0x33
  119. ///Cmd for DeriveKey
  120. #define CMD_DERIVE_KEY 0x34
  121. ///Payload length of Get Data
  122. #define LEN_PL_OIDDATA 0x06
  123. ///Payload length of OID
  124. #define LEN_PL_OID 0x02
  125. ///Oid of error object
  126. #define OID_ERROR 0xF1C2
  127. ///Cmd with MSB set
  128. #define CMD_CODE_MSB_SET 0x80
  129. /// Unique application identifier
  130. #define UNIQUE_APP_IDENTIFIER 0xD2, 0x76, 0x00, 0x00, 0x04, 0x47, 0x65, 0x6E, 0x41, 0x75, 0x74, 0x68, 0x41, 0x70, 0x70, 0x6C
  131. ///Session ID Lower value
  132. #define SESSION_ID_LOWER_VALUE 0xE100
  133. ///Session ID Higher value
  134. #define SESSION_ID_HIGHER_VALUE 0xE103
  135. ///Tag for unprotected Message in the response data
  136. #define TAG_UNPROTECTED 0x60
  137. ///Tag for protected Message in the response data
  138. #define TAG_PROTECTED 0x50
  139. ///Mask the higher nibble
  140. #define MASK_HIGHER_NIBBLE 0xF0
  141. ///Mask the higher nibble
  142. #define MASK_LOWER_NIBBLE 0x0F
  143. ///Offset of tag byte
  144. #define OFFSET_TAG (OFFSET_PAYLOAD + BYTES_SESSIONID)
  145. ///Offset of Tag Length byte
  146. #define OFFSET_TAG_LEN (OFFSET_TAG + 1)
  147. ///Offset of Tag data
  148. #define OFFSET_TAG_DATA (OFFSET_TAG_LEN + BYTES_LENGTH)
  149. ///GMT Unix time tag
  150. #define TAG_GMTUNIX_TIME 0x31
  151. ///Number of bytes of GMT time
  152. #define BYTES_GMT_TIME 0x04
  153. ///Certificate OID tag
  154. #define TAG_CERTIFICATE_OID 0x32
  155. ///Invalid value for Max size of comms buffer
  156. #define INVALID_MAX_COMMS_BUFF_SIZE 0xFFFF
  157. ///Tag for digest
  158. #define TAG_DIGEST 0x01
  159. ///Tag for signature
  160. #define TAG_SIGNATURE 0x02
  161. ///Tag for public key oid
  162. #define TAG_PUB_KEY_OID 0x04
  163. ///Tag for algorithm identifier
  164. #define TAG_ALGO_IDENTIFIER 0x05
  165. ///Tag for private key OID
  166. #define TAG_OID 0x01
  167. ///Tag for key usage identifier
  168. #define TAG_KEY_USAGE_IDENTIFIER 0x02
  169. ///Tag for OID of signature key
  170. #define TAG_OID_SIG_KEY 0x03
  171. ///Tag for seed
  172. #define TAG_SEED 0x02
  173. /// Length for OID of signature key
  174. #define LEN_OID_SIG_KEY 0x0002
  175. ///Len for algorithm identifier
  176. #define LEN_KEY_USAGE_IDENTIFIER 0x0001
  177. ///Tag for export key pair
  178. #define TAG_EXPORT_KEY_PAIR 0x07
  179. ///Len for private key oid
  180. #define LEN_PRI_KEY 0x0002
  181. ///Len for Shared Secret oid
  182. #define LEN_SHARED_SECRET_OID 0x0002
  183. ///Len for exported key pair
  184. #define LEN_EXPORT_KEY_PAIR 0x0000
  185. ///Tag for public key
  186. #define TAG_PUB_KEY 0x06
  187. ///Len for public key oid
  188. #define LEN_PUB_KEY 0x0002
  189. ///Len for algorithm identifier
  190. #define LEN_ALGO_IDENTIFIER 0x0001
  191. ///Error in security chip indicating data out of boundary
  192. #define ERR_DATA_OUT_OF_BOUND 0x00000008
  193. //Maximum size of the communication buffer
  194. /*lint --e{552} suppress "Temporary" */
  195. uint16_t wMaxCommsBuffer = INVALID_MAX_COMMS_BUFF_SIZE;
  196. //Finds minimum amongst the given 2 value
  197. #ifndef MIN
  198. #define MIN(a,b) ((a<b)?a:b)
  199. #endif
  200. ///Hash Output length for SHA256 Hash Algorithm
  201. #define SHA256_HASH_LEN 32
  202. ///ECC NIST P 256 Private key length
  203. #define ECC_NIST_P_256_KEY_LEN 32
  204. ///ECC NIST P 384 Private key length
  205. #define ECC_NIST_P_384_KEY_LEN 48
  206. /**
  207. * Initializes the APDU buffer in stack.<br>
  208. **/
  209. #define INIT_STACK_APDUBUFFER(pbBuffer,wLen)\
  210. { \
  211. /*lint --e{733,830} suppress "Used only within Command Lib Block" */\
  212. uint8_t rgbAPDUBuffer[wLen]; \
  213. pbBuffer = rgbAPDUBuffer; \
  214. }
  215. /**
  216. * Initializes the APDU buffer in heap.<br>
  217. **/
  218. #define INIT_HEAP_APDUBUFFER(pbBuffer,wLen) \
  219. { \
  220. if(INVALID_MAX_COMMS_BUFF_SIZE == wMaxCommsBuffer) \
  221. { \
  222. i4Status = (int32_t)CMD_DEV_EXEC_ERROR; \
  223. break; \
  224. } \
  225. pbBuffer = (uint8_t*)OCP_MALLOC(wLen); \
  226. if(NULL == pbBuffer) \
  227. { \
  228. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY; \
  229. break; \
  230. } \
  231. } \
  232. /**
  233. * Frees the heap memory.<br>
  234. **/
  235. #define FREE_HEAP_APDUBUFFER(pbBuffer) \
  236. { \
  237. if(NULL != pbBuffer) \
  238. { \
  239. OCP_FREE(pbBuffer); \
  240. pbBuffer = NULL; \
  241. } \
  242. }
  243. //Hash info details for Hash algorithm
  244. const sHashinfo_d sHashInfo[1]=
  245. {
  246. {eSHA256, SHA256_HASH_LEN, CALC_HASH_SHA256_CONTEXT_SIZE}
  247. };
  248. /**
  249. * \brief Structure to specify algorithm identifier and key length.
  250. */
  251. typedef struct sAlgoinfo
  252. {
  253. ///Algorithm type
  254. eAlgId_d eAlgKeyId;
  255. ///Key Length
  256. uint8_t bKeyLen;
  257. }sAlgoInfo_d;
  258. //Algorithm identifier
  259. const sAlgoInfo_d sAlgoInfo[2]=
  260. {
  261. {eECC_NIST_P256, ECC_NIST_P_256_KEY_LEN},
  262. {eECC_NIST_P384, ECC_NIST_P_384_KEY_LEN}
  263. };
  264. /**
  265. * \brief Structure to specify GetDataObject command parameters.
  266. */
  267. typedef struct sApduData_d
  268. {
  269. ///Cmd of the APDU
  270. uint8_t bCmd;
  271. ///Param of APDU
  272. uint8_t bParam;
  273. ///Payload length
  274. uint16_t wPayloadLength;
  275. //Payload Data
  276. uint8_t* prgbAPDUBuffer;
  277. //Response Data
  278. uint8_t* prgbRespBuffer;
  279. //Response Length
  280. uint16_t wResponseLength;
  281. }sApduData_d;
  282. /**
  283. * \brief Enumeration to specify the sequence of message/record.
  284. */
  285. //lint --e{749} suppress "Added for future use"
  286. typedef enum eFragSeq_d
  287. {
  288. ///Start
  289. eStart = 0x00,
  290. ///Final
  291. eFinal = 0x01,
  292. ///Intermediate
  293. eContinue = 0x02
  294. }eFragSeq_d;
  295. volatile static host_lib_status_t optiga_comms_status;
  296. //lint --e{715, 818} suppress "This is ignored as app_event_handler_t handler function prototype requires this argument.This will be used for object based implementation"
  297. static void optiga_comms_event_handler(void* upper_layer_ctx, host_lib_status_t event)
  298. {
  299. optiga_comms_status = event;
  300. }
  301. /**
  302. *
  303. * Gets the device error code by reading the Error code object id.<br>
  304. * If there is an internal error in function, then #CMD_DEV_ERROR is returned.<br>
  305. * Otherwise,the device error code is ORed with #CMD_DEV_ERROR and returned.<br>
  306. *
  307. * \retval #CMD_DEV_ERROR
  308. * \retval #CMD_LIB_ERROR
  309. * \retval #CMD_DEV_EXEC_ERROR
  310. *
  311. */
  312. _STATIC_H int32_t CmdLib_GetDeviceError(void)
  313. {
  314. int32_t i4Status = (int32_t)CMD_DEV_ERROR;
  315. uint8_t rgbErrorCmd[] = {CMD_GETDATA,0x00,0x00,0x02,(uint8_t)(OID_ERROR>>8),(uint8_t)OID_ERROR};
  316. uint16_t wBufferLength = sizeof(rgbErrorCmd);
  317. do
  318. {
  319. p_optiga_comms->upper_layer_handler = optiga_comms_event_handler;
  320. optiga_comms_status = OPTIGA_COMMS_BUSY;
  321. i4Status = optiga_comms_transceive(p_optiga_comms,rgbErrorCmd,&wBufferLength,
  322. rgbErrorCmd,&wBufferLength);
  323. if(OPTIGA_COMMS_SUCCESS != i4Status)
  324. {
  325. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  326. break;
  327. }
  328. //wait for completion
  329. while(optiga_comms_status == OPTIGA_COMMS_BUSY){
  330. #ifdef USE_CMDLIB_WITH_RTOS
  331. pal_os_timer_delay_in_milliseconds(1);
  332. #endif
  333. };
  334. if(optiga_comms_status != OPTIGA_COMMS_SUCCESS)
  335. {
  336. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  337. break;
  338. }
  339. if(0 == rgbErrorCmd[OFFSET_RESP_STATUS])
  340. { //If response Header
  341. i4Status = (int32_t)(CMD_DEV_ERROR | rgbErrorCmd[OFFSET_PAYLOAD]);
  342. }
  343. else
  344. {
  345. //In this case, execution error is returned.
  346. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  347. }
  348. }while(FALSE);
  349. return i4Status;
  350. }
  351. /**
  352. * \brief Formats data as per Security Chip application and send using the communication functions.
  353. */
  354. _STATIC_H int32_t TransceiveAPDU(sApduData_d *PpsApduData,uint8_t bGetError)
  355. {
  356. //lint --e{818} suppress "PpsResponse is out parameter"
  357. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  358. uint16_t wTotalLength;
  359. do
  360. {
  361. if(NULL == PpsApduData || NULL == p_optiga_comms)
  362. {
  363. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  364. break;
  365. }
  366. PpsApduData->prgbAPDUBuffer[OFFSET_CMD] = PpsApduData->bCmd;
  367. PpsApduData->prgbAPDUBuffer[OFFSET_PARAM] = PpsApduData->bParam;
  368. //copy length
  369. PpsApduData->prgbAPDUBuffer[OFFSET_LENGTH] = (uint8_t)(PpsApduData->wPayloadLength >> BITS_PER_BYTE);
  370. PpsApduData->prgbAPDUBuffer[OFFSET_LENGTH+1] = (uint8_t)PpsApduData->wPayloadLength;
  371. //update total length to consider total header length
  372. wTotalLength = PpsApduData->wPayloadLength + LEN_APDUHEADER;
  373. p_optiga_comms->upper_layer_handler = optiga_comms_event_handler;
  374. optiga_comms_status = OPTIGA_COMMS_BUSY;
  375. i4Status = optiga_comms_transceive(p_optiga_comms,PpsApduData->prgbAPDUBuffer,&wTotalLength,
  376. PpsApduData->prgbRespBuffer,&PpsApduData->wResponseLength);
  377. if(OPTIGA_COMMS_SUCCESS != i4Status)
  378. {
  379. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  380. break;
  381. }
  382. //wait for completion
  383. do
  384. {
  385. #ifdef USE_CMDLIB_WITH_RTOS
  386. pal_os_timer_delay_in_milliseconds(1);
  387. #endif
  388. }while(optiga_comms_status == OPTIGA_COMMS_BUSY);
  389. if(optiga_comms_status != OPTIGA_COMMS_SUCCESS)
  390. {
  391. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  392. break;
  393. }
  394. //return device error if not success
  395. if(0 != PpsApduData->prgbRespBuffer[OFFSET_RESP_STATUS])
  396. {
  397. if(TRUE == bGetError)
  398. {
  399. i4Status = CmdLib_GetDeviceError();
  400. }
  401. else
  402. {
  403. i4Status = (int32_t)CMD_LIB_ERROR;
  404. }
  405. break;
  406. }
  407. i4Status = CMD_LIB_OK;
  408. }while(FALSE);
  409. return i4Status;
  410. }
  411. /**
  412. * \brief Read the maximum size of communication buffer supported by the security chip by reading "Max comms buffer size" OID.
  413. */
  414. _STATIC_H int32_t GetMaxCommsBuffer()
  415. {
  416. #define GETDATA_MAX_COMMS_SIZE 10
  417. #define OID_MAX_COMMS_SIZE 0xE0C6
  418. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  419. sApduData_d sApduData;
  420. do
  421. {
  422. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,GETDATA_MAX_COMMS_SIZE);
  423. //Set the pointer to the response buffer
  424. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  425. //Set the CMD
  426. sApduData.bCmd = CMD_GETDATA;
  427. sApduData.bParam = PARAM_GET_DATA;
  428. sApduData.wPayloadLength = LEN_PL_OID;
  429. sApduData.wResponseLength = GETDATA_MAX_COMMS_SIZE;
  430. //copy OID
  431. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(OID_MAX_COMMS_SIZE >> BITS_PER_BYTE);
  432. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD +1] = (uint8_t)OID_MAX_COMMS_SIZE;
  433. i4Status = TransceiveAPDU(&sApduData,TRUE);
  434. if(CMD_LIB_OK != i4Status)
  435. {
  436. break;
  437. }
  438. //Assign value to MaxCommsBuffer
  439. wMaxCommsBuffer = (uint16_t )((sApduData.prgbRespBuffer[LEN_APDUHEADER] << 8) | (sApduData.prgbRespBuffer[LEN_APDUHEADER+1]));
  440. }while(FALSE);
  441. #undef GETDATA_MAX_COMMS_SIZE
  442. #undef OID_MAX_COMMS_SIZE
  443. return i4Status;
  444. }
  445. #ifdef MODULE_ENABLE_DTLS_MUTUAL_AUTH
  446. /**
  447. * \brief A common function for CmdLib_Encrypt and CmdLib_Decrypt.
  448. *
  449. */
  450. _STATIC_H int32_t CmdLib_EncDecHelper(sProcCryptoData_d *PpsCryptoVector, uint8_t PbCmd, uint8_t PbParam);
  451. /**
  452. * A common function for CmdLib_Encrypt and CmdLib_Decrypt.<br>
  453. * Forms the APDU required for encryption/decryption and sends to the security chip for processing.<br>
  454. *
  455. * \param[in,out] PpsCryptoVector Pointer to structure containing Ciphertext and Plaintext
  456. * \param[in] bCmd ProcUplink or ProcDownlink
  457. * \param[in] bParam Parameter to Encrypt/Decrypt data
  458. *
  459. * \retval #CMD_LIB_OK
  460. * \retval #CMD_LIB_ERROR
  461. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  462. * \retval #CMD_LIB_INVALID_SESSIONID
  463. * \retval #CMD_LIB_INVALID_LEN
  464. * \retval #CMD_DEV_ERROR
  465. * \retval #CMD_LIB_NULL_PARAM
  466. */
  467. _STATIC_H int32_t CmdLib_EncDecHelper(sProcCryptoData_d *PpsCryptoVector, uint8_t PbCmd, uint8_t PbParam)
  468. {
  469. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  470. uint16_t wRespLen;
  471. uint16_t wDataRemaining;
  472. uint16_t wMaxDataLen;
  473. uint16_t wTotalEncDecLen =0;
  474. uint16_t wOffset = ADDITIONALBYTES_ENCDEC;
  475. uint16_t wMaxPlaintText;
  476. uint8_t bFragSeq ;
  477. uint8_t bSendTag,bRecvTag;
  478. uint8_t *pbResponse;
  479. uint8_t bGetError = TRUE;
  480. sApduData_d sApduData;
  481. do
  482. {
  483. //NULL checks
  484. if((NULL == PpsCryptoVector) || (NULL == PpsCryptoVector->sInData.prgbStream) ||
  485. (NULL == PpsCryptoVector->sOutData.prgbBuffer))
  486. {
  487. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  488. break;
  489. }
  490. //Verify the Session OID reference
  491. if((SESSION_ID_LOWER_VALUE > PpsCryptoVector->wSessionKeyOID) ||
  492. (SESSION_ID_HIGHER_VALUE < PpsCryptoVector->wSessionKeyOID))
  493. {
  494. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  495. break;
  496. }
  497. if((0 == PpsCryptoVector->wInDataLength) ||
  498. (PpsCryptoVector->sInData.wLen < (PpsCryptoVector->wInDataLength + OVERHEAD_UPDOWNLINK)))
  499. {
  500. i4Status = (int32_t)CMD_LIB_INVALID_LEN;
  501. break;
  502. }
  503. //Check if plaintext length is more than the size of the out buffer
  504. if(PpsCryptoVector->wInDataLength > PpsCryptoVector->sOutData.wBufferLength)
  505. {
  506. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  507. break;
  508. }
  509. PpsCryptoVector->sOutData.wRespLength = 0;
  510. //Assign cmd,param
  511. sApduData.bCmd = PbCmd;
  512. sApduData.bParam = PbParam;
  513. wMaxPlaintText = wMaxCommsBuffer - OVERHEAD_UPDOWNLINK;
  514. //Data that is yet to be encrypted/decrypted
  515. wDataRemaining = PpsCryptoVector->wInDataLength;
  516. //Set the fragment sequence to start
  517. bFragSeq = (wDataRemaining>wMaxPlaintText)?(uint8_t)eStart:(uint8_t)eFinal;
  518. //Assign send or receive Tag
  519. if(PARAM_ENC_DATA == PbParam)
  520. {
  521. bSendTag = TAG_UNPROTECTED;
  522. bRecvTag = TAG_PROTECTED;
  523. }
  524. else
  525. {
  526. bSendTag= TAG_PROTECTED;
  527. bRecvTag = TAG_UNPROTECTED;
  528. bGetError = FALSE;
  529. }
  530. pbResponse = PpsCryptoVector->sOutData.prgbBuffer;
  531. while(wDataRemaining !=0)
  532. {
  533. //Maximum data that can be sent to chip in one APDU
  534. wMaxDataLen = (wDataRemaining>wMaxPlaintText)?wMaxPlaintText:wDataRemaining;
  535. //Assign InData memory pointer to the APDU Buffer in the Apdu structure
  536. sApduData.prgbAPDUBuffer = PpsCryptoVector->sInData.prgbStream + wOffset;
  537. //Form data and assign to apdu structure
  538. //Total payload length is Session ID Length + bytes for tag encoding + data
  539. sApduData.wPayloadLength = BYTES_SESSIONID + LEN_TAG_ENCODING + wMaxDataLen;
  540. //Add the session ID to the buffer
  541. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsCryptoVector->wSessionKeyOID >> BITS_PER_BYTE);
  542. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsCryptoVector->wSessionKeyOID;
  543. //Add the encoding tag to the buffer
  544. sApduData.prgbAPDUBuffer[OFFSET_TAG] = (bSendTag | bFragSeq);
  545. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = (uint8_t)(wMaxDataLen >> 8);
  546. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = (uint8_t)wMaxDataLen;
  547. //Payload data should already be present in input buffer as per documentation
  548. sApduData.prgbRespBuffer = pbResponse;
  549. sApduData.wResponseLength = PpsCryptoVector->sOutData.wBufferLength - wTotalEncDecLen;
  550. //Now Transmit data
  551. i4Status = TransceiveAPDU(&sApduData,bGetError);
  552. if(CMD_LIB_OK != i4Status)
  553. {
  554. if(PARAM_DEC_DATA == PbParam)
  555. {
  556. i4Status = (int32_t)CMD_LIB_DECRYPT_FAILURE;
  557. }
  558. break;
  559. }
  560. //Remove 4 byte apdu header + tag encoding
  561. sApduData.wResponseLength -= OVERHEAD_ENCDEC_RESPONSE;
  562. //Sequence of flag for start,continue or final should be same that was sent
  563. if((bRecvTag|bFragSeq) != (*(sApduData.prgbRespBuffer + LEN_APDUHEADER)))
  564. {
  565. i4Status = (int32_t)CMD_LIB_INVALID_TAG;
  566. break;
  567. }
  568. //Extract the tag length field to get enc data length
  569. wRespLen = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + 1);
  570. //Length validation for response length with the tag length
  571. if(sApduData.wResponseLength != wRespLen)
  572. {
  573. i4Status = (int32_t)CMD_LIB_INVALID_TAGLEN;
  574. break;
  575. }
  576. //Copy the data to output data buffer
  577. Utility_Memmove(pbResponse,sApduData.prgbRespBuffer+(LEN_APDUHEADER + LEN_TAG_ENCODING),wRespLen);
  578. wTotalEncDecLen += wRespLen;
  579. pbResponse += wRespLen;
  580. //Data remaining to encrypt
  581. wDataRemaining -= wMaxDataLen;
  582. //Since using the buffer provided by user, using offset to form next APDU command
  583. wOffset += wMaxDataLen;
  584. //If last fragment then make flag final else let it continue
  585. bFragSeq = (wDataRemaining>wMaxPlaintText)?(uint8_t)eContinue:(uint8_t)eFinal;
  586. }
  587. //Update on success only
  588. if(CMD_LIB_OK == i4Status)
  589. {
  590. PpsCryptoVector->sOutData.wRespLength = wTotalEncDecLen;
  591. }
  592. }while(FALSE);
  593. return i4Status;
  594. }
  595. #endif /* MODULE_ENABLE_DTLS_MUTUAL_AUTH*/
  596. #ifdef MODULE_ENABLE_TOOLBOX
  597. /**
  598. * This function returns Hash Algorithm information such as Hash output length, Hash context data.
  599. *
  600. * \param[in] PeHashAlgo Hash Algorithm type
  601. * \param[in,out] PpsHashinfo Pointer to a structure containing Hash algorithm information
  602. *
  603. * \retval #CMD_LIB_OK
  604. * \retval #CMD_LIB_ERROR
  605. */
  606. _STATIC_H int32_t Get_HashInfo(eHashAlg_d PeHashAlgo, const sHashinfo_d** PppsHashinfo )
  607. {
  608. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  609. uint8_t bCount;
  610. //Search the table for the given session key id
  611. for(bCount= 0;bCount<(sizeof(sHashInfo)/sizeof(sHashinfo_d));bCount++)
  612. {
  613. if(PeHashAlgo == sHashInfo[bCount].eHashAlgo)
  614. {
  615. *PppsHashinfo = &sHashInfo[bCount];
  616. i4Status = (int32_t) CMD_LIB_OK;
  617. break;
  618. }
  619. }
  620. return i4Status;
  621. }
  622. /**
  623. * This function returns key size based on the algorithm.
  624. *
  625. * \param[in] PeAlgoIden Algorithm identifier type
  626. * \param[in,out] PpsAlgoinfo Pointer to a structure containing key size of algorithm identifier
  627. *
  628. * \retval #CMD_LIB_OK
  629. * \retval #CMD_LIB_ERROR
  630. */
  631. _STATIC_H int32_t Get_KeySize(eAlgId_d PeAlgoIden,uint8_t* pbKeySize )
  632. {
  633. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  634. uint8_t bCount;
  635. //Search the table for the given session key id
  636. for(bCount= 0;bCount<(sizeof(sAlgoInfo)/sizeof(sAlgoInfo_d));bCount++)
  637. {
  638. if(PeAlgoIden == sAlgoInfo[bCount].eAlgKeyId)
  639. {
  640. *pbKeySize = sAlgoInfo[bCount].bKeyLen;
  641. i4Status = (int32_t) CMD_LIB_OK;
  642. break;
  643. }
  644. }
  645. return i4Status;
  646. }
  647. #endif/*MODULE_ENABLE_TOOLBOX*/
  648. /// @endcond
  649. /**
  650. * Sets the OPTIGA Comms context provided by user application in the command libary.
  651. *
  652. * <br>
  653. * \param[in] p_input_optiga_comms Pointer to OPTIGA comms context
  654. *
  655. * \retval #CMD_LIB_OK
  656. * \retval #CMD_LIB_ERROR
  657. */
  658. void CmdLib_SetOptigaCommsContext(const optiga_comms_t *p_input_optiga_comms)
  659. {
  660. p_optiga_comms = (optiga_comms_t*)p_input_optiga_comms;
  661. }
  662. /**
  663. * Opens the Security Chip Application. The Unique Application Identifier is used internally by
  664. * the function while forming a command APDU.
  665. *
  666. *\param[in] PpsOpenApp Pointer to a structure #sOpenApp_d containing inputs for opening application on security chip
  667. *
  668. * Notes:
  669. * - This function must be mandatorily invoked before starting any interactions with security Chip after the reset.
  670. *
  671. * \retval #CMD_LIB_OK
  672. * \retval #CMD_LIB_ERROR
  673. * \retval #CMD_LIB_INVALID_PARAM
  674. * \retval #CMD_LIB_NULL_PARAM
  675. */
  676. int32_t CmdLib_OpenApplication(const sOpenApp_d* PpsOpenApp)
  677. {
  678. /// @cond hidden
  679. #define OPEN_APDU_BUF_LEN 25
  680. /// @endcond
  681. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  682. uint8_t rgbUID[] = {UNIQUE_APP_IDENTIFIER};
  683. sApduData_d sApduData;
  684. do
  685. {
  686. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,OPEN_APDU_BUF_LEN);
  687. if(NULL == PpsOpenApp)
  688. {
  689. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  690. break;
  691. }
  692. //Validate option for opening application
  693. if(eInit != PpsOpenApp->eOpenType)
  694. {
  695. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  696. break;
  697. }
  698. //Set the pointer to the response buffer
  699. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  700. //Open application command with MSB set to flush the last error code
  701. sApduData.bCmd = CMD_OPEN_APP | CMD_CODE_MSB_SET ;
  702. sApduData.bParam = (uint8_t)PpsOpenApp->eOpenType;
  703. sApduData.wPayloadLength = sizeof(rgbUID);
  704. sApduData.wResponseLength = OPEN_APDU_BUF_LEN;
  705. OCP_MEMCPY(sApduData.prgbAPDUBuffer+OFFSET_PAYLOAD, rgbUID, sizeof(rgbUID));
  706. i4Status = TransceiveAPDU(&sApduData,FALSE);
  707. if(CMD_LIB_OK != i4Status)
  708. {
  709. break;
  710. }
  711. //Read Max comms buffer size if not already read
  712. if(INVALID_MAX_COMMS_BUFF_SIZE == wMaxCommsBuffer)
  713. {
  714. //Get Maximum Comms buffer size
  715. i4Status = GetMaxCommsBuffer();
  716. }
  717. }while(FALSE);
  718. /// @cond hidden
  719. #undef OPEN_APDU_BUF_LEN
  720. /// @endcond
  721. return i4Status;
  722. }
  723. #ifdef MODULE_ENABLE_READ_WRITE
  724. /**
  725. * Reads data or metadata of the specified data object by issuing GetDataObject command based on input parameters.
  726. *
  727. * <br>
  728. * Notes:
  729. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  730. * - The function does not verify if the read access is permitted for the data object.<br>
  731. *
  732. *\param[in] PpsGDVector Pointer to Get Data Object inputs
  733. *\param[in,out] PpsResponse Pointer to Response structure
  734. *
  735. * \retval #CMD_LIB_OK
  736. * \retval #CMD_LIB_LENZERO_ERROR
  737. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  738. * \retval #CMD_DEV_ERROR
  739. * \retval #CMD_LIB_NULL_PARAM
  740. */
  741. int32_t CmdLib_GetDataObject(const sGetData_d *PpsGDVector, sCmdResponse_d *PpsResponse)
  742. {
  743. /// @cond hidden
  744. #define ALLOCATE_ADDITIONAL_BYTES 6 // hdr(4) + oid(2)
  745. /// @endcond
  746. //lint --e{818} suppress "PpsResponse is out parameter"
  747. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  748. uint16_t wTotalRecvLen = 0;
  749. uint16_t wReadLen = 0;
  750. uint16_t wOffset = 0;
  751. sApduData_d sApduData;
  752. sApduData.prgbAPDUBuffer = NULL;
  753. do
  754. {
  755. //To use stack memory for APDU buffer, define STACK_ALLOC macro locally and else heap memory is used
  756. #ifdef STACK_ALLOC
  757. #error "Implement the inilization of stack memory for the required buffer"
  758. //INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer, wLen); //wLen to be replaced with the required const length
  759. #else
  760. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wMaxCommsBuffer + ALLOCATE_ADDITIONAL_BYTES);
  761. #endif
  762. if((NULL == PpsGDVector)||(NULL == PpsResponse)||(NULL == PpsResponse->prgbBuffer))
  763. {
  764. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  765. break;
  766. }
  767. if(0x00 == PpsResponse->wBufferLength)
  768. {
  769. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  770. break;
  771. }
  772. //Set the pointer to the response buffer
  773. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer+ALLOCATE_ADDITIONAL_BYTES;
  774. sApduData.bCmd = CMD_GETDATA;
  775. //copy OID
  776. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsGDVector->wOID >> BITS_PER_BYTE);
  777. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD +1] = (uint8_t)PpsGDVector->wOID;
  778. //set param, payload length and offset ,if reading data
  779. if(eDATA == PpsGDVector->eDataOrMdata)
  780. {
  781. sApduData.bParam = PARAM_GET_DATA;
  782. sApduData.wPayloadLength = LEN_PL_OIDDATA;
  783. wOffset = PpsGDVector->wOffset;
  784. }
  785. //set param and payload length ,if reading metadata
  786. else if(eMETA_DATA == PpsGDVector->eDataOrMdata)
  787. {
  788. sApduData.bParam = PARAM_GET_METADATA;
  789. sApduData.wPayloadLength = LEN_PL_OID;
  790. }
  791. else
  792. {
  793. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  794. break;
  795. }
  796. do
  797. {
  798. if(eDATA == PpsGDVector->eDataOrMdata)
  799. {
  800. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID] = (uint8_t)(wOffset >> BITS_PER_BYTE);
  801. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID +1] = (uint8_t)wOffset;
  802. //copy read length
  803. wReadLen = MIN((wMaxCommsBuffer-LEN_APDUHEADER),(PpsGDVector->wLength-wTotalRecvLen));
  804. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID + BYTES_OFFSET] = (uint8_t)(wReadLen >> BITS_PER_BYTE);
  805. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID + BYTES_OFFSET +1] = (uint8_t)wReadLen;
  806. }
  807. sApduData.wResponseLength = wMaxCommsBuffer;
  808. i4Status = TransceiveAPDU(&sApduData,TRUE);
  809. if(CMD_LIB_OK != i4Status)
  810. {
  811. break;
  812. }
  813. //strip 4 byte apdu header
  814. sApduData.wResponseLength -= LEN_APDUHEADER;
  815. //Copy read data
  816. if(((PpsResponse->wBufferLength-wTotalRecvLen) < sApduData.wResponseLength))
  817. {
  818. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  819. break;
  820. }
  821. OCP_MEMCPY(PpsResponse->prgbBuffer+wTotalRecvLen,sApduData.prgbRespBuffer+LEN_APDUHEADER,sApduData.wResponseLength);
  822. //Update total received data
  823. wTotalRecvLen += sApduData.wResponseLength;
  824. //increment the offset to get data from
  825. wOffset += sApduData.wResponseLength;
  826. //If requested data is read
  827. if(wTotalRecvLen == PpsGDVector->wLength)
  828. {
  829. break;
  830. }
  831. //continue, if total requested data not yet received and more data available for reading
  832. }while(wReadLen == sApduData.wResponseLength);
  833. if((CMD_LIB_OK != i4Status)&&((wTotalRecvLen == 0)||
  834. (ERR_DATA_OUT_OF_BOUND != (i4Status^(int32_t)CMD_DEV_ERROR))))
  835. {
  836. //Clear existing data
  837. OCP_MEMSET(PpsResponse->prgbBuffer,0,wTotalRecvLen);
  838. PpsResponse->wRespLength = 0;
  839. break;
  840. }
  841. PpsResponse->wRespLength = wTotalRecvLen;
  842. i4Status = (int32_t)CMD_LIB_OK;
  843. }while(FALSE);
  844. #ifndef STACK_ALLOC
  845. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  846. #else
  847. #undef STACK_ALLOC
  848. #endif
  849. ///@cond hidden
  850. #undef ALLOCATE_ADDITIONAL_BYTES
  851. ///@endcond
  852. return i4Status;
  853. }
  854. /**
  855. * Writes data or metadata to the specified data object by issuing SetDataObject command based on input parameters.
  856. *
  857. * <br>
  858. * Notes: <br>
  859. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  860. *
  861. * - The function does not verify if the write access permitted for the data object.
  862. *
  863. * - While writing metadata, the metadata must be specified in an already TLV encoded
  864. * byte array format. For example, to set LcsO to operational the value passed by
  865. * the user must be 0x20 0x03 0xC0, 0x01, 0x07. <br>
  866. *
  867. * - The function does not validate if the provided input data bytes are correctly
  868. * formatted. For example, while setting LcsO to operational, function does not
  869. * verify if the value is indeed 0x07. <br>
  870. *
  871. * - In case of failure,it is possible that partial data is written into the data object.<br>
  872. * In such a case, the user should decide if the data has to be re-written.
  873. *
  874. *\param[in] PpsSDVector Pointer to Set Data Object inputs
  875. *
  876. * \retval #CMD_LIB_OK
  877. * \retval #CMD_LIB_ERROR
  878. * \retval #CMD_LIB_INVALID_PARAM
  879. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  880. * \retval #CMD_DEV_ERROR
  881. * \retval #CMD_LIB_NULL_PARAM
  882. */
  883. int32_t CmdLib_SetDataObject(const sSetData_d *PpsSDVector)
  884. {
  885. /// @cond hidden
  886. #define BUFFER_SIZE (wMaxCommsBuffer)
  887. /// @endcond
  888. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  889. uint16_t wTotalWriteLen = 0;
  890. uint16_t wWriteLen = 0;
  891. uint16_t wOffset;
  892. sApduData_d sApduData;
  893. sApduData.prgbAPDUBuffer = NULL;
  894. do
  895. {
  896. //To use stack memory for APDU buffer, define STACK_ALLOC macro locally and else heap memory is used
  897. #ifdef STACK_ALLOC
  898. #error "Implement the inilization of stack memory for the required buffer"
  899. //INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer, wLen); //wLen to be replaced with the required const length
  900. #else
  901. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,BUFFER_SIZE);
  902. #endif
  903. if((NULL == PpsSDVector)||(NULL == PpsSDVector->prgbData))
  904. {
  905. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  906. break;
  907. }
  908. if(0x00 == PpsSDVector->wLength)
  909. {
  910. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  911. break;
  912. }
  913. sApduData.bCmd = CMD_SETDATA;
  914. if((eDATA == PpsSDVector->eDataOrMdata)&&
  915. (eWRITE == PpsSDVector->eWriteOption))
  916. {
  917. sApduData.bParam = PARAM_SET_DATA;
  918. }
  919. else if((eDATA == PpsSDVector->eDataOrMdata)&&
  920. (eERASE_AND_WRITE == PpsSDVector->eWriteOption))
  921. {
  922. sApduData.bParam = PARAM_SET_DATA_ERASE;
  923. }
  924. else if((eMETA_DATA == PpsSDVector->eDataOrMdata)&&
  925. (eWRITE == PpsSDVector->eWriteOption))
  926. {
  927. sApduData.bParam = PARAM_SET_METADATA;
  928. }
  929. else
  930. {
  931. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  932. break;
  933. }
  934. //Set the pointer to the response buffer
  935. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer+7;
  936. //copy OID
  937. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsSDVector->wOID >> BITS_PER_BYTE);
  938. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsSDVector->wOID;
  939. wOffset = PpsSDVector->wOffset;
  940. do
  941. {
  942. //While chaining for erase & write option, all subsequent write must be only write operation
  943. if((sApduData.bParam == PARAM_SET_DATA_ERASE)&&
  944. (wTotalWriteLen != 0))
  945. {
  946. sApduData.bParam = PARAM_SET_DATA;
  947. }
  948. /// @cond hidden
  949. #define OVERHEAD (OFFSET_PAYLOAD+BYTES_OID+BYTES_OFFSET)
  950. /// @endcond
  951. wWriteLen = MIN((wMaxCommsBuffer-OVERHEAD),(PpsSDVector->wLength-wTotalWriteLen));
  952. //set data payload length is 4(OID length + offset length) plus length of data to write
  953. sApduData.wPayloadLength = BYTES_OID + BYTES_OFFSET + wWriteLen;
  954. //copy offset
  955. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID] = (uint8_t)(wOffset >> BITS_PER_BYTE);
  956. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_OID + 1] = (uint8_t)wOffset;
  957. //copy the data
  958. OCP_MEMCPY(sApduData.prgbAPDUBuffer+OVERHEAD,PpsSDVector->prgbData+wTotalWriteLen,wWriteLen);
  959. //Set Response buffer length
  960. sApduData.wResponseLength = BUFFER_SIZE;
  961. i4Status = TransceiveAPDU(&sApduData,TRUE);
  962. if(CMD_LIB_OK != i4Status)
  963. {
  964. break;
  965. }
  966. wTotalWriteLen += wWriteLen;
  967. wOffset += wWriteLen;
  968. }while(wTotalWriteLen != PpsSDVector->wLength);
  969. }while(FALSE);
  970. #ifndef STACK_ALLOC
  971. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  972. #else
  973. #undef STACK_ALLOC
  974. #endif
  975. /// @cond hidden
  976. #undef OVERHEAD
  977. #undef BUFFER_SIZE
  978. /// @endcond
  979. return i4Status;
  980. }
  981. /**
  982. * Reads maximum communication buffer size supported by the security chip.<br>
  983. *
  984. * Notes:
  985. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  986. * - The function does not verify if the read access is permitted for the data object.<br>
  987. *
  988. * \retval #CMD_LIB_OK
  989. * \retval #CMD_LIB_ERROR
  990. */
  991. uint16_t CmdLib_GetMaxCommsBufferSize(Void)
  992. {
  993. return wMaxCommsBuffer;
  994. }
  995. #endif /* MODULE_ENABLE_READ_WRITE */
  996. /**
  997. * Gets the signature generated by Security Chip. The message to be signed is provided by the user.<br>
  998. * The following commands are issued in the sequence.<br>
  999. * - SetAuthScheme : To set authentication scheme and the private key to be used <br>
  1000. * - SetAuthMsg : To write the message to Security Chip that must be digitally signed.<br>
  1001. * - GetAuthMsg : To read the digitally signed message from Security Chip.<br>
  1002. *
  1003. * <br>
  1004. * Notes: <br>
  1005. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1006. * - The function just returns the signature without verifying it.
  1007. * - The private key to be used in set auth scheme is passed in \ref #sAuthMsg_d.wOIDDevPrivKey.
  1008. * - The \ref #sAuthMsg_d.prgbRnd and \ref #sAuthMsg_d.wRndLength carry the challenge to be signed.
  1009. * - The length of challenge should be between 8 and 256 bytes. If the length of challenge is out of this range, #CMD_LIB_INVALID_LEN error is returned.<br>
  1010. *
  1011. *\param[in] PpsAuthMsg Pointer to Get Signature Object inputs
  1012. *\param[in,out] PpsResponse Pointer to Response structure
  1013. *
  1014. * \retval #CMD_LIB_OK
  1015. * \retval #CMD_LIB_ERROR
  1016. * \retval #CMD_DEV_ERROR
  1017. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1018. * \retval #CMD_LIB_NULL_PARAM
  1019. * \retval #CMD_LIB_INVALID_LEN
  1020. */
  1021. int32_t CmdLib_GetSignature(const sAuthMsg_d *PpsAuthMsg, sCmdResponse_d *PpsResponse)
  1022. {
  1023. /// @cond hidden
  1024. #define STACK_ALLOC
  1025. #define GETSIGN_APDU_BUF_LEN 270 //4 (cmd header) + 256 (Max Payload) + additional 10
  1026. /// @endcond
  1027. //lint --e{818} suppress "PpsResponse is out parameter"
  1028. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1029. sApduData_d sApduData;
  1030. sAuthScheme_d sAuthScheme;
  1031. do
  1032. {
  1033. //To use stack memory for APDU buffer, define STACK_ALLOC locally else heap memory is used
  1034. #ifdef STACK_ALLOC
  1035. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,GETSIGN_APDU_BUF_LEN);
  1036. #else
  1037. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,GETSIGN_APDU_BUF_LEN);
  1038. #endif
  1039. if((NULL == PpsAuthMsg)||(NULL == PpsAuthMsg->prgbRnd)||
  1040. (NULL == PpsResponse)||(NULL == PpsResponse->prgbBuffer))
  1041. {
  1042. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1043. break;
  1044. }
  1045. //Check if Challenge length is in between 8 to 256
  1046. if((CHALLENGE_MIN_LEN > PpsAuthMsg->wRndLength) || (CHALLENGE_MAX_LEN < PpsAuthMsg->wRndLength))
  1047. {
  1048. i4Status = (int32_t)CMD_LIB_INVALID_LEN;
  1049. break;
  1050. }
  1051. //Set the pointer to the response buffer
  1052. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1053. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1054. //Set Auth scheme
  1055. sAuthScheme.eAuthScheme = eECDSA;
  1056. sAuthScheme.wDevicePrivKey = PpsAuthMsg->wOIDDevPrivKey;
  1057. i4Status = CmdLib_SetAuthScheme(&sAuthScheme);
  1058. if(CMD_LIB_OK != i4Status)
  1059. {
  1060. break;
  1061. }
  1062. //Set Auth msg
  1063. sApduData.bCmd = CMD_SETAUTH_MSG;
  1064. sApduData.bParam = PARAM_SET_AUTH_MSG;
  1065. sApduData.wPayloadLength = PpsAuthMsg->wRndLength;
  1066. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1067. //copy the random number
  1068. OCP_MEMCPY(sApduData.prgbAPDUBuffer+OFFSET_PAYLOAD,PpsAuthMsg->prgbRnd,PpsAuthMsg->wRndLength);
  1069. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1070. if(CMD_LIB_OK != i4Status)
  1071. {
  1072. break;
  1073. }
  1074. //Get Auth msg
  1075. sApduData.bCmd = CMD_GETAUTH_MSG;
  1076. sApduData.bParam = PARAM_GET_AUTH_MSG;
  1077. sApduData.wPayloadLength = 0;
  1078. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1079. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1080. if(CMD_LIB_OK != i4Status)
  1081. {
  1082. break;
  1083. }
  1084. //strip 4 byte apdu header
  1085. sApduData.wResponseLength -= LEN_APDUHEADER;
  1086. PpsResponse->wRespLength = sApduData.wResponseLength;
  1087. if(PpsResponse->wBufferLength < sApduData.wResponseLength)
  1088. {
  1089. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1090. break;
  1091. }
  1092. OCP_MEMCPY(PpsResponse->prgbBuffer,sApduData.prgbAPDUBuffer+LEN_APDUHEADER,sApduData.wResponseLength);
  1093. }while(FALSE);
  1094. #ifndef STACK_ALLOC
  1095. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1096. #else
  1097. #undef STACK_ALLOC
  1098. #endif
  1099. ///@cond hidden
  1100. #undef GETSIGN_APDU_BUF_LEN
  1101. ///@endcond
  1102. return i4Status;
  1103. }
  1104. /**
  1105. * Gets random bytes generated by the Security Chip.<br>
  1106. *
  1107. * <br>
  1108. * Notes: <br>
  1109. * - Command chaining is not supported in this API.<br>
  1110. * - If the requested length of random bytes is either more than communication buffer size or more than the buffer size in PpsResponse,#CMD_LIB_INSUFFICIENT_MEMORY error is returned.<br>
  1111. *
  1112. *\param[in] PpsRng Pointer to sRngOptions_d to specify random number generation
  1113. *\param[in,out] PpsResponse Pointer to sCmdResponse_d to store random number
  1114. *
  1115. * \retval #CMD_LIB_OK
  1116. * \retval #CMD_LIB_ERROR
  1117. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1118. * \retval #CMD_LIB_LENZERO_ERROR
  1119. * \retval #CMD_DEV_ERROR
  1120. * \retval #CMD_LIB_NULL_PARAM
  1121. */
  1122. int32_t CmdLib_GetRandom(const sRngOptions_d *PpsRng, sCmdResponse_d *PpsResponse)
  1123. {
  1124. //lint --e{818} suppress "PpsResponse is out parameter"
  1125. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1126. sApduData_d sApduData;
  1127. do
  1128. {
  1129. //Initial value set it to NULL
  1130. sApduData.prgbAPDUBuffer = NULL;
  1131. if((NULL == PpsRng)||(NULL == PpsResponse)||(NULL == PpsResponse->prgbBuffer))
  1132. {
  1133. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1134. break;
  1135. }
  1136. if(0x00 == PpsResponse->wBufferLength)
  1137. {
  1138. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  1139. break;
  1140. }
  1141. //If the length of requested random bytes is more than the maximum comms buffer size
  1142. if((wMaxCommsBuffer) < (LEN_APDUHEADER + PpsRng->wRandomDataLen))
  1143. {
  1144. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1145. break;
  1146. }
  1147. PpsResponse->wRespLength = 0;
  1148. sApduData.bCmd = CMD_GET_RND;
  1149. sApduData.bParam = (uint8_t)PpsRng->eRngType;
  1150. sApduData.wPayloadLength = LEN_PL_OID;
  1151. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer, (LEN_APDUHEADER + PpsRng->wRandomDataLen));
  1152. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsRng->wRandomDataLen >> BITS_PER_BYTE);
  1153. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsRng->wRandomDataLen;
  1154. sApduData.wResponseLength = (LEN_APDUHEADER + PpsRng->wRandomDataLen);
  1155. //Set the pointer to the response buffer
  1156. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1157. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1158. if(CMD_LIB_OK != i4Status)
  1159. {
  1160. break;
  1161. }
  1162. //strip 4 byte apdu header
  1163. sApduData.wResponseLength -= LEN_APDUHEADER;
  1164. if(PpsResponse->wBufferLength < sApduData.wResponseLength)
  1165. {
  1166. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1167. break;
  1168. }
  1169. OCP_MEMCPY(PpsResponse->prgbBuffer,sApduData.prgbAPDUBuffer+LEN_APDUHEADER,sApduData.wResponseLength);
  1170. PpsResponse->wRespLength = sApduData.wResponseLength;
  1171. }while(FALSE);
  1172. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1173. return i4Status;
  1174. }
  1175. /**
  1176. * Sets the Authentication Scheme by issuing SetAuthScheme command to Security Chip.
  1177. *
  1178. * <br>
  1179. * Notes: <br>
  1180. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1181. * - Currently only 1 session OID (0xE100) is supported by the security chip.
  1182. *
  1183. *\param[in] PpsAuthVector Pointer to Authentication Scheme data
  1184. *
  1185. * \retval #CMD_LIB_OK
  1186. * \retval #CMD_LIB_ERROR
  1187. * \retval #CMD_LIB_INVALID_PARAM
  1188. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1189. * \retval #CMD_DEV_ERROR
  1190. * \retval #CMD_LIB_NULL_PARAM
  1191. */
  1192. int32_t CmdLib_SetAuthScheme(const sAuthScheme_d *PpsAuthVector)
  1193. {
  1194. /// @cond hidden
  1195. #define SET_AUTH_SCHEME_APDU_BUF_LEN 10
  1196. /// @endcond
  1197. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1198. sApduData_d sApduData;
  1199. uint16_t wPayloadSize;
  1200. do
  1201. {
  1202. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer, SET_AUTH_SCHEME_APDU_BUF_LEN);
  1203. if(NULL == PpsAuthVector)
  1204. {
  1205. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1206. break;
  1207. }
  1208. //verify the param
  1209. if(eDTLSClient == PpsAuthVector->eAuthScheme)
  1210. {
  1211. //Verify the range of session ID
  1212. if((SESSION_ID_LOWER_VALUE > PpsAuthVector->wSessionKeyId)
  1213. || (SESSION_ID_HIGHER_VALUE < PpsAuthVector->wSessionKeyId))
  1214. {
  1215. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  1216. break;
  1217. }
  1218. wPayloadSize = 4;
  1219. }
  1220. else if(eECDSA == PpsAuthVector->eAuthScheme)
  1221. {
  1222. wPayloadSize = 2;
  1223. }
  1224. else
  1225. {
  1226. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  1227. break;
  1228. }
  1229. //Set the pointer to the response buffer
  1230. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1231. //Form the command
  1232. //Assign Cmd,param,payload length
  1233. sApduData.bCmd = CMD_SETAUTH_SCM;
  1234. sApduData.bParam = (uint8_t)PpsAuthVector->eAuthScheme;
  1235. sApduData.wPayloadLength = wPayloadSize;
  1236. //Assign the device private key OID at payload offset
  1237. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsAuthVector->wDevicePrivKey >> BITS_PER_BYTE);
  1238. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+1] = (uint8_t)PpsAuthVector->wDevicePrivKey;
  1239. sApduData.wResponseLength = SET_AUTH_SCHEME_APDU_BUF_LEN;
  1240. if(eDTLSClient == PpsAuthVector->eAuthScheme)
  1241. {
  1242. //Assign the session OID
  1243. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+2] = (uint8_t)(PpsAuthVector->wSessionKeyId >> BITS_PER_BYTE);
  1244. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+3] = (uint8_t)PpsAuthVector->wSessionKeyId;
  1245. }
  1246. //Transmit the Data
  1247. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1248. if(CMD_LIB_OK != i4Status)
  1249. {
  1250. break;
  1251. }
  1252. }while(FALSE);
  1253. /// @cond hidden
  1254. #undef SET_AUTH_SCHEME_APDU_BUF_LEN
  1255. /// @endcond
  1256. return i4Status;
  1257. }
  1258. #ifdef MODULE_ENABLE_TOOLBOX
  1259. /**
  1260. * Calculates the hash of input data by using the Security Chip.<br>
  1261. *
  1262. * Input:<br>
  1263. * - Provide the required type of input data for hashing. Use \ref sCalcHash_d.eHashDataType with the following options,
  1264. * - eDataStream : Indicates, sDataStream is considered as hash input.
  1265. * - eOIDData : Indicates, sOIDData is considered for hash input.
  1266. *
  1267. * - Provide the input to import/export the hash context. Use \ref sContextInfo_d.eContextAction with the following options,
  1268. * - #eImport : Import hash context to perform the hash.
  1269. * - #eExport : Export current active hash context.
  1270. * - #eImportExport : Import hash context and Export back the context after hashing.
  1271. * - #eUnused : Context data import/export feature is not used. This option is also recommended for #eHashSequence_d as #eStartFinalizeHash or #eTerminateHash.
  1272. *
  1273. * Output:<br>
  1274. * - Successful API execution,
  1275. * - Hash is returned in sOutHash only if #eHashSequence_d is #eStartFinalizeHash,#eIntermediateHash or #eFinalizeHash.<br>
  1276. * - Hash context data is returned only if \ref sContextInfo_d.eContextAction is #eExport or #eImportExport.<br>
  1277. *
  1278. * Notes: <br>
  1279. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1280. * - #eTerminateHash in #eHashSequence_d is used to terminate any existing hash session. Any input data or hash context options supplied with this sequence is ignored.
  1281. * - Sequences for generating a hash successfully can be as follows:<br>
  1282. * - #eStartHash,#eFinalizeHash<br>
  1283. * - #eStartHash,#eContinueHash (single or multiple),#eFinalizeHash<br>
  1284. * - #eStartFinalizeHash<br>
  1285. * - #eStartHash,#eIntermediateHash,#eContinueHash,#eFinalizeHash<br>
  1286. *
  1287. * - If the memory buffer is not sufficient to store output hash/hash context or the data to be sent to security chip is more than communication buffer,#CMD_LIB_INSUFFICIENT_MEMORY error is retured.
  1288. * - This API does not maintain any state of hashing operations.<br>
  1289. * - There is no support for chaining while sending data therefore in order to avoid communication buffer overflow, the user must take care of fragmenting the data for hashing.<br>
  1290. * Use the API #CmdLib_GetMaxCommsBufferSize to check the maximum communication buffer size supported by the security chip. In addition, the overhead for command APDU header and
  1291. * TLV encoding must be considered as explained below.<br>
  1292. *
  1293. * Read the maximum communication buffer size using the API #CmdLib_GetMaxCommsBufferSize() and store in a variable <b>"wMaxCommsBuffer"</b><br>
  1294. * Substract the header overheads and hash context size(depends on applicable Hash algorithm) respectively from wMaxCommsBuffer. The result gives the Available_Size to frame the hash data input.<br>
  1295. *
  1296. * - Only hash calculation : <br>
  1297. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Available_Size = (wMaxCommsBuffer - #CALC_HASH_FIXED_OVERHEAD_SIZE)<br>
  1298. * - Import context to security chip and calculate hash : <br>
  1299. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Available_Size = (wMaxCommsBuffer - #CALC_HASH_FIXED_OVERHEAD_SIZE - #CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE - #CALC_HASH_SHA256_CONTEXT_SIZE)<br>
  1300. * - Calulate hash and export context out of security chip : <br>
  1301. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Available_Size = (wMaxCommsBuffer - #CALC_HASH_FIXED_OVERHEAD_SIZE - #CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE)<br>
  1302. * - Import context to security chip, calculate hash and export context out of security chip :<br>
  1303. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Available_Size = (wMaxCommsBuffer - #CALC_HASH_FIXED_OVERHEAD_SIZE - #CALC_HASH_IMPORT_AND_EXPORT_OVERHEAD_SIZE - #CALC_HASH_SHA256_CONTEXT_SIZE)<br>
  1304. *
  1305. *
  1306. * \param[in,out] PpsCalcHash Pointer to #sCalcHash_d that contains information to calculate hash
  1307. *
  1308. * \retval #CMD_LIB_OK
  1309. * \retval #CMD_LIB_ERROR
  1310. * \retval #CMD_LIB_NULL_PARAM
  1311. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1312. * \retval #CMD_DEV_EXEC_ERROR
  1313. * \retval #CMD_DEV_ERROR
  1314. */
  1315. int32_t CmdLib_CalcHash(sCalcHash_d* PpsCalcHash)
  1316. {
  1317. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1318. sApduData_d sApduData;
  1319. eDataType_d eHashDataType;
  1320. uint16_t wMemoryAllocLen;
  1321. uint16_t wInDataLen;
  1322. const sHashinfo_d* psHashinfo;
  1323. uint16_t wOptTagLen = 0;
  1324. uint16_t wOptTagOffset = 0;
  1325. uint16_t wOffset;
  1326. uint16_t wBufferLen;
  1327. do
  1328. {
  1329. //Initial value set it to NULL
  1330. sApduData.prgbAPDUBuffer = NULL;
  1331. //Check for NULL inputs
  1332. if(NULL == PpsCalcHash)
  1333. {
  1334. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1335. break;
  1336. }
  1337. i4Status = Get_HashInfo(PpsCalcHash->eHashAlg, &psHashinfo);
  1338. if(CMD_LIB_OK != i4Status)
  1339. {
  1340. break;
  1341. }
  1342. //For eHashSequence_d as eFinalizeHash,validate sOutData
  1343. if(((eFinalizeHash == PpsCalcHash->eHashSequence) || (eStartFinalizeHash == PpsCalcHash->eHashSequence) ||
  1344. (eIntermediateHash == PpsCalcHash->eHashSequence)) && (NULL == PpsCalcHash->sOutHash.prgbBuffer))
  1345. {
  1346. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1347. break;
  1348. }
  1349. //Validate the Context data buffer if optional tag is provided
  1350. if((eUnused != PpsCalcHash->sContextInfo.eContextAction) && (NULL == PpsCalcHash->sContextInfo.pbContextData))
  1351. {
  1352. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1353. break;
  1354. }
  1355. /// @cond hidden
  1356. #define INDATA_LEN_OID (BYTES_OID + BYTES_LENGTH + BYTES_OFFSET)
  1357. #define NIBBLE_LEN 4
  1358. /// @endcond
  1359. eHashDataType = PpsCalcHash->eHashDataType;
  1360. //For eHashDataType_d as eDataStream, validate psDataStream
  1361. if(eTerminateHash == PpsCalcHash->eHashSequence)
  1362. {
  1363. wInDataLen = 0;
  1364. eHashDataType = eDataStream;
  1365. }
  1366. else if(eDataStream == eHashDataType)
  1367. {
  1368. if(NULL == PpsCalcHash->sDataStream.prgbStream)
  1369. {
  1370. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1371. break;
  1372. }
  1373. //Set the total data length as input length
  1374. wInDataLen = PpsCalcHash->sDataStream.wLen;
  1375. }
  1376. else
  1377. {
  1378. //Set the total data length as 6 bytes (2 byte OID + 2 bytes Offset + 2 bytes Length)
  1379. wInDataLen = INDATA_LEN_OID;
  1380. }
  1381. //Calculate the offset and length for optional tags in the command APDU
  1382. if(eUnused != PpsCalcHash->sContextInfo.eContextAction)
  1383. {
  1384. wOptTagLen = (eExport != PpsCalcHash->sContextInfo.eContextAction)? (CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE + PpsCalcHash->sContextInfo.dwContextLen) : (CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE);
  1385. //Total length of optional tag which includes tag, length and data
  1386. if(eImportExport == PpsCalcHash->sContextInfo.eContextAction)
  1387. {
  1388. wOptTagLen += CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE;
  1389. }
  1390. wOptTagOffset = (eDataStream == PpsCalcHash->eHashDataType)? (OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + wInDataLen) :
  1391. (OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + INDATA_LEN_OID);
  1392. }
  1393. //Validate the size of input data with the Communication buffer
  1394. if((wInDataLen + wOptTagLen + CALC_HASH_FIXED_OVERHEAD_SIZE) > wMaxCommsBuffer)
  1395. {
  1396. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1397. break;
  1398. }
  1399. //Form data
  1400. sApduData.bCmd = CMD_CALCHASH;
  1401. sApduData.bParam = (uint8_t)PpsCalcHash->eHashAlg;
  1402. wMemoryAllocLen = CALC_HASH_FIXED_OVERHEAD_SIZE + wInDataLen + wOptTagLen;
  1403. wBufferLen = CALC_HASH_FIXED_OVERHEAD_SIZE;
  1404. //Check to validate sufficient memory to store the output
  1405. //If Hash is the output
  1406. if((eFinalizeHash == PpsCalcHash->eHashSequence) || (eStartFinalizeHash == PpsCalcHash->eHashSequence) ||
  1407. (eIntermediateHash == PpsCalcHash->eHashSequence))
  1408. {
  1409. wBufferLen += psHashinfo->bHashLen;
  1410. }
  1411. //If context data is output
  1412. if((eExport == PpsCalcHash->sContextInfo.eContextAction) || (eImportExport == PpsCalcHash->sContextInfo.eContextAction))
  1413. {
  1414. wBufferLen += psHashinfo->wHashCntx;
  1415. }
  1416. if(wBufferLen > wMemoryAllocLen)
  1417. {
  1418. wMemoryAllocLen = wBufferLen;
  1419. }
  1420. // Allocate the memory
  1421. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer, wMemoryAllocLen);
  1422. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(((uint8_t)eHashDataType << NIBBLE_LEN) | (uint8_t) PpsCalcHash->eHashSequence);
  1423. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ] = (uint8_t)(wInDataLen >> 8);
  1424. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + 1] = (uint8_t)wInDataLen ;
  1425. if(eTerminateHash != PpsCalcHash->eHashSequence)
  1426. {
  1427. //If the DataType is Data stream, copy the input data to the buffer
  1428. if(eDataStream == eHashDataType)
  1429. {
  1430. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH], PpsCalcHash->sDataStream.prgbStream,
  1431. wInDataLen);
  1432. }
  1433. else
  1434. {
  1435. //If the Data type is OID, copy the OID information to the buffer
  1436. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH] = (uint8_t)(PpsCalcHash->sOIDData.wOID >> 8);
  1437. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + 1] = (uint8_t)PpsCalcHash->sOIDData.wOID;
  1438. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + BYTES_OID] = (uint8_t)(PpsCalcHash->sOIDData.wOffset >> 8);
  1439. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + BYTES_OID + 1] = (uint8_t)PpsCalcHash->sOIDData.wOffset;
  1440. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + INDATA_LEN_OID] = (uint8_t)(PpsCalcHash->sOIDData.wLength >> 8);
  1441. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + INDATA_LEN_OID + 1] = (uint8_t)(PpsCalcHash->sOIDData.wLength);
  1442. }
  1443. /// @cond hidden
  1444. #define OFFSET_EXPORT_CNTXTAG (wOptTagOffset + BYTES_SEQ+ BYTES_LENGTH + PpsCalcHash->sContextInfo.dwContextLen)
  1445. /// @endcond
  1446. //If the optional tag is either eImport or eImportAndExport, 0x06 tag is sent as part of command APDU
  1447. if((eImportExport == PpsCalcHash->sContextInfo.eContextAction) ||
  1448. (eImport == PpsCalcHash->sContextInfo.eContextAction))
  1449. {
  1450. sApduData.prgbAPDUBuffer[wOptTagOffset] = (uint8_t)eImport;
  1451. sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ] = (uint8_t)(PpsCalcHash->sContextInfo.dwContextLen >> 8);
  1452. sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ + 1] = (uint8_t)(PpsCalcHash->sContextInfo.dwContextLen);
  1453. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ + BYTES_LENGTH], PpsCalcHash->sContextInfo.pbContextData,
  1454. PpsCalcHash->sContextInfo.dwContextLen);
  1455. }
  1456. //If the optional tag is either eExport or eImportAndeExport, 0x07 tag is sent as part of command APDU
  1457. if((eImportExport == PpsCalcHash->sContextInfo.eContextAction) ||
  1458. (eExport == PpsCalcHash->sContextInfo.eContextAction))
  1459. {
  1460. wOffset = (eExport == PpsCalcHash->sContextInfo.eContextAction)?wOptTagOffset : OFFSET_EXPORT_CNTXTAG;
  1461. sApduData.prgbAPDUBuffer[wOffset] = (uint8_t)eExport;
  1462. sApduData.prgbAPDUBuffer[wOffset + BYTES_SEQ] = 0x00;
  1463. sApduData.prgbAPDUBuffer[wOffset + BYTES_SEQ + 1] =0x00;
  1464. }
  1465. }
  1466. //set data payload length is 3(BYTES_SEQ + BYTES_LENGTH) plus length of data to write
  1467. sApduData.wPayloadLength = BYTES_SEQ + BYTES_LENGTH + wInDataLen + wOptTagLen;
  1468. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1469. sApduData.wResponseLength = wMemoryAllocLen;
  1470. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1471. if(CMD_LIB_OK != i4Status)
  1472. {
  1473. break;
  1474. }
  1475. /// @cond hidden
  1476. #define TAG_HASH_OUTPUT 0x01
  1477. #define TAG_CONTEXT_OUTPUT 0x06
  1478. /// @endcond
  1479. sApduData.wResponseLength -= LEN_APDUHEADER;
  1480. //Validate the output buffer size if tag received on reponse is 0x01 and
  1481. //copy the hash data to sOutput buffer
  1482. if((TAG_HASH_OUTPUT == (*(sApduData.prgbRespBuffer + LEN_APDUHEADER))) && (sApduData.wResponseLength != 0))
  1483. {
  1484. //Length check for sOutData
  1485. if((psHashinfo->bHashLen) > PpsCalcHash->sOutHash.wBufferLength)
  1486. {
  1487. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1488. break;
  1489. }
  1490. PpsCalcHash->sOutHash.wRespLength = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + BYTES_SEQ);
  1491. OCP_MEMCPY(PpsCalcHash->sOutHash.prgbBuffer, (sApduData.prgbRespBuffer + CALC_HASH_FIXED_OVERHEAD_SIZE), PpsCalcHash->sOutHash.wRespLength);
  1492. }
  1493. //Validate the Context buffer size if the 0x06 context data tag is there in response and
  1494. //copy the context data to pbContextData buffer
  1495. if((TAG_CONTEXT_OUTPUT == (*(sApduData.prgbRespBuffer + LEN_APDUHEADER))) && (sApduData.wResponseLength != 0))
  1496. {
  1497. //Length check for Context Data
  1498. if((psHashinfo->wHashCntx) > PpsCalcHash->sContextInfo.dwContextLen)
  1499. {
  1500. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1501. break;
  1502. }
  1503. PpsCalcHash->sContextInfo.dwContextLen = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + BYTES_SEQ);
  1504. OCP_MEMCPY(PpsCalcHash->sContextInfo.pbContextData, (sApduData.prgbRespBuffer + CALC_HASH_FIXED_OVERHEAD_SIZE), PpsCalcHash->sContextInfo.dwContextLen);
  1505. }
  1506. }while(FALSE);
  1507. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1508. /// @cond hidden
  1509. #undef INDATA_LEN_OID
  1510. #undef NIBBLE_LEN
  1511. #undef OFFSET_EXPORT_CNTXTAG
  1512. #undef TAG_HASH_OUTPUT
  1513. #undef TAG_CONTEXT_OUTPUT
  1514. /// @endcond
  1515. return i4Status;
  1516. }
  1517. /**
  1518. * Verifies the signature over the input digest by using the Security Chip.<br>
  1519. *
  1520. * Input:<br>
  1521. * - For eVerifyDataType
  1522. * - #eDataStream indicates that sPubKeyInput is considered for signature verification.<br>
  1523. * - #eOIDData indicates that wOIDPubKey is considered for signature verification.<br>
  1524. *
  1525. * Output:<br>
  1526. * - Successful signature verification returns #CMD_LIB_OK.<br>
  1527. *
  1528. * Notes: <br>
  1529. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1530. * - If the the data to be sent to security chip is more than communication buffer,#CMD_LIB_INSUFFICIENT_MEMORY is returned. Refer OPTIGA_Trust_X_SolutionReferenceManual_v1.x.pdf for more details.
  1531. *
  1532. * \param[in] PpsVerifySign Pointer to information for verifying signature
  1533. * \param[in,out] PpsDigest pointer to a blob which holds the Digest
  1534. * \param[in,out] PpsSignature pointer to a blob which holds the Signature to be verified
  1535. *
  1536. * \retval #CMD_LIB_OK
  1537. * \retval #CMD_LIB_ERROR
  1538. * \retval #CMD_LIB_NULL_PARAM
  1539. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1540. * \retval #CMD_DEV_EXEC_ERROR
  1541. * \retval #CMD_DEV_ERROR
  1542. */
  1543. int32_t CmdLib_VerifySign(const sVerifyOption_d* PpsVerifySign,const sbBlob_d * PpsDigest,const sbBlob_d * PpsSignature)
  1544. {
  1545. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1546. sApduData_d sApduData = {0};
  1547. uint16_t wWritePosition = OFFSET_PAYLOAD;
  1548. uint16_t wCalApduLen = 0;
  1549. /// @cond hidden
  1550. ///Minimum length of APDU InData in case of Public Key from Host. [TLV Header(3) for Digest + TLV Header (3) for Signature + TLV Header(3) for Public Key + TLV for Algo (4)]
  1551. #define DATA_STREAM_APDU_INDATA_LEN 13
  1552. ///Minimum length of APDU InData in case of Public Key OID. [TLV Header(3) for Digest + TLV Header (3) for Signature + TLV for Public Key OID (5)]
  1553. #define OID_APDU_INDATA_LEN 11
  1554. /// @endcond
  1555. do
  1556. {
  1557. //NULL checks
  1558. if((NULL == PpsVerifySign) || (NULL == PpsDigest->prgbStream) ||
  1559. (NULL == PpsSignature->prgbStream))
  1560. {
  1561. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1562. break;
  1563. }
  1564. if(eDataStream == PpsVerifySign->eVerifyDataType)
  1565. {
  1566. //NULL checks
  1567. if(NULL == PpsVerifySign->sPubKeyInput.sDataStream.prgbStream)
  1568. {
  1569. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1570. break;
  1571. }
  1572. wCalApduLen = OFFSET_PAYLOAD + DATA_STREAM_APDU_INDATA_LEN + PpsDigest->wLen + PpsSignature->wLen + PpsVerifySign->sPubKeyInput.sDataStream.wLen;
  1573. }
  1574. if(eOIDData == PpsVerifySign->eVerifyDataType)
  1575. {
  1576. wCalApduLen = OFFSET_PAYLOAD + OID_APDU_INDATA_LEN + PpsDigest->wLen + PpsSignature->wLen;
  1577. }
  1578. if((wMaxCommsBuffer) < wCalApduLen)
  1579. {
  1580. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1581. break;
  1582. }
  1583. //Allocating Heap memory
  1584. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1585. //Set the pointer to the response buffer
  1586. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1587. sApduData.wResponseLength = wMaxCommsBuffer;
  1588. //Set digest tag, length, data
  1589. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = TAG_DIGEST;
  1590. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsDigest->wLen);
  1591. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDigest->prgbStream,PpsDigest->wLen);
  1592. wWritePosition += TAG_VALUE_OFFSET+ PpsDigest->wLen;
  1593. //Set signature tag, length, data
  1594. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_SIGNATURE;
  1595. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsSignature->wLen);
  1596. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsSignature->prgbStream,PpsSignature->wLen);
  1597. wWritePosition += TAG_VALUE_OFFSET + PpsSignature->wLen;
  1598. if(eDataStream == PpsVerifySign->eVerifyDataType)
  1599. {
  1600. //Set TLV values for external public key
  1601. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_ALGO_IDENTIFIER;
  1602. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_ALGO_IDENTIFIER);
  1603. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsVerifySign->sPubKeyInput.eAlgId;
  1604. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET + BYTES_SEQ] = (uint8_t)TAG_PUB_KEY;
  1605. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET + BYTES_OFFSET], PpsVerifySign->sPubKeyInput.sDataStream.wLen);
  1606. wWritePosition += TAG_VALUE_OFFSET + BYTES_OFFSET + BYTES_OFFSET;
  1607. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition],PpsVerifySign->sPubKeyInput.sDataStream.prgbStream ,PpsVerifySign->sPubKeyInput.sDataStream.wLen);
  1608. //Total payload length
  1609. sApduData.wPayloadLength = (uint16_t)(wWritePosition + PpsVerifySign->sPubKeyInput.sDataStream.wLen - OFFSET_PAYLOAD);
  1610. }
  1611. if(eOIDData == PpsVerifySign->eVerifyDataType)
  1612. {
  1613. //Set TLV values for public key OID
  1614. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_PUB_KEY_OID;
  1615. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_PUB_KEY);
  1616. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsVerifySign->wOIDPubKey);
  1617. //Total payload length
  1618. sApduData.wPayloadLength = (uint16_t)(wWritePosition + TAG_VALUE_OFFSET + BYTES_OFFSET - OFFSET_PAYLOAD);
  1619. }
  1620. //Form Command
  1621. sApduData.bCmd = CMD_VERIFYSIGN;
  1622. sApduData.bParam = (uint8_t)PpsVerifySign->eSignScheme;
  1623. //Transmit data
  1624. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1625. if(CMD_LIB_OK != i4Status)
  1626. {
  1627. break;
  1628. }
  1629. }while(FALSE);
  1630. //Free the allocated memory for buffer
  1631. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1632. /// @cond hidden
  1633. #undef DATA_STREAM_APDU_INDATA_LEN
  1634. #undef OID_APDU_INDATA_LEN
  1635. /// @endcond
  1636. return i4Status;
  1637. }
  1638. /**
  1639. * Generates a key pair by using the Security Chip.<br>
  1640. *
  1641. * Input:
  1642. * - Provide the required option for exporting the generated keys. Use \ref sKeyPairOption_d.eKeyExport
  1643. * - #eStorePrivKeyOnly indicates that only private key is stored in the OID and public key is exported.
  1644. * - #eExportKeyPair indicates that both public and private keys are exported.
  1645. *
  1646. * Output:
  1647. * - Successful API execution,
  1648. * - Public key is returned in \ref sOutKeyPair_d.sPublicKey.
  1649. * - Private key is returned in \ref sOutKeyPair_d.sPrivateKey , if input is #eExportKeyPair.
  1650. *
  1651. * Notes:
  1652. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1653. * - Values of #eKeyUsage_d can be logically 'ORed' and passed to \ref sKeyPairOption_d.eKeyUsage.
  1654. * - If the memory buffers in #sOutKeyPair_d is not sufficient to store the generated keys,#CMD_LIB_INSUFFICIENT_MEMORY is returned. Refer OPTIGA_Trust_X_SolutionReferenceManual_v1.x.pdf for more details.
  1655. *
  1656. * \param[in] PpsKeyPairOption Pointer to #sKeyPairOption_d to provide input for key pair generation
  1657. * \param[in,out] PpsOutKeyPair Pointer to #sOutKeyPair_d that contains generated key pair
  1658. *
  1659. * \retval #CMD_LIB_OK
  1660. * \retval #CMD_LIB_ERROR
  1661. * \retval #CMD_LIB_NULL_PARAM
  1662. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1663. * \retval #CMD_DEV_EXEC_ERROR
  1664. * \retval #CMD_DEV_ERROR
  1665. */
  1666. int32_t CmdLib_GenerateKeyPair(const sKeyPairOption_d* PpsKeyPairOption,sOutKeyPair_d* PpsOutKeyPair)
  1667. {
  1668. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1669. uint16_t wWritePosition = LEN_APDUHEADER;
  1670. uint16_t wCalApduLen;
  1671. uint16_t wLen;
  1672. uint16_t wParsLen;
  1673. uint8_t bMultiplier;
  1674. sApduData_d sApduData = {0};
  1675. uint8_t wAlgoLen;
  1676. sbBlob_d * psBlobKey = NULL;
  1677. /// @cond hidden
  1678. ///Tag for public key
  1679. #define TAG_PUBLIC_KEY 0x02
  1680. ///Minimum length of APDU InData in case of Private key store. [TLV Header(3) of OID + OID (2) + TLV Header(3) for key usage identifier + Identifier (1)]
  1681. #define PRIV_KEY_APDU_INDATA_LEN 9
  1682. /// Encoding bytes for private and public key
  1683. #define KEY_PAIR_INDATA_LEN 4
  1684. /// @endcond
  1685. do
  1686. {
  1687. //NULL checks
  1688. if((NULL == PpsKeyPairOption) || (NULL == PpsOutKeyPair) || (NULL == PpsOutKeyPair->sPublicKey.prgbStream))
  1689. {
  1690. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1691. break;
  1692. }
  1693. wCalApduLen = LEN_APDUHEADER + PRIV_KEY_APDU_INDATA_LEN;
  1694. bMultiplier = 2;
  1695. if(eExportKeyPair == PpsKeyPairOption->eKeyExport)
  1696. {
  1697. //NULL checks
  1698. if(NULL == PpsOutKeyPair->sPrivateKey.prgbStream)
  1699. {
  1700. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1701. break;
  1702. }
  1703. wCalApduLen = LEN_APDUHEADER + KEY_PAIR_INDATA_LEN + TAG_VALUE_OFFSET + TAG_VALUE_OFFSET;
  1704. bMultiplier = 3;
  1705. }
  1706. //Get key size using algorithm identifier
  1707. i4Status = Get_KeySize(PpsKeyPairOption->eAlgId, &wAlgoLen);
  1708. if(CMD_LIB_OK != i4Status)
  1709. {
  1710. break;
  1711. }
  1712. wCalApduLen += ((wAlgoLen * bMultiplier) + 2);
  1713. //Allocating Heap memory
  1714. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1715. //Set the pointer to the response buffer
  1716. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1717. sApduData.wResponseLength = wCalApduLen;
  1718. if(eStorePrivKeyOnly == PpsKeyPairOption->eKeyExport)
  1719. {
  1720. //Set private key OID tag, length, data
  1721. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  1722. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_PRI_KEY);
  1723. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsKeyPairOption->wOIDPrivKey);
  1724. wWritePosition += TAG_VALUE_OFFSET+ BYTES_OFFSET;
  1725. //Set key usage identifier tag, length, data
  1726. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_KEY_USAGE_IDENTIFIER;
  1727. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_KEY_USAGE_IDENTIFIER);
  1728. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsKeyPairOption->eKeyUsage;
  1729. wWritePosition += TAG_VALUE_OFFSET + BYTES_SEQ;
  1730. }
  1731. if(eExportKeyPair == PpsKeyPairOption->eKeyExport)
  1732. {
  1733. //Set TLV values for extract key pair
  1734. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_KEY_PAIR;
  1735. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_KEY_PAIR);
  1736. wWritePosition += TAG_VALUE_OFFSET;
  1737. }
  1738. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1739. //Form Command
  1740. sApduData.bCmd = CMD_GENERATE_KEY_PAIR;
  1741. sApduData.bParam = (uint8_t)PpsKeyPairOption->eAlgId;
  1742. //Transmit data
  1743. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1744. if(CMD_LIB_OK != i4Status)
  1745. {
  1746. break;
  1747. }
  1748. wParsLen = LEN_APDUHEADER;
  1749. do
  1750. {
  1751. wLen = Utility_GetUint16(&sApduData.prgbRespBuffer[wParsLen+BYTES_SEQ]);
  1752. psBlobKey = (TAG_PUBLIC_KEY == sApduData.prgbRespBuffer[wParsLen])?&(PpsOutKeyPair->sPublicKey):&(PpsOutKeyPair->sPrivateKey);
  1753. if(wLen > psBlobKey->wLen)
  1754. {
  1755. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1756. break;
  1757. }
  1758. //Copy public key to output buffer
  1759. OCP_MEMCPY(psBlobKey->prgbStream,&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wParsLen] ,wLen);
  1760. psBlobKey->wLen = wLen;
  1761. wParsLen += (wLen + TAG_VALUE_OFFSET);
  1762. }while(wParsLen != sApduData.wResponseLength);
  1763. }while(FALSE);
  1764. //Free the allocated memory for buffer
  1765. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1766. /// @cond hidden
  1767. #undef TAG_PUBLIC_KEY
  1768. #undef PRIV_KEY_APDU_INDATA_LEN
  1769. #undef KEY_PAIR_INDATA_LEN
  1770. /// @endcond
  1771. return i4Status;
  1772. }
  1773. /**
  1774. * Calculates signature on a digest by using the Security Chip.<br>
  1775. *
  1776. * Input:
  1777. * - Provide the signature scheme. Use \ref sCalcSignOptions_d.eSignScheme.
  1778. * - Provide the digest to be signed. Use \ref sCalcSignOptions_d.sDigestToSign.
  1779. * - Provide the OID of the private key. Use \ref sCalcSignOptions_d.wOIDSignKey.
  1780. *
  1781. * Output:
  1782. * - Successful API execution,
  1783. * - Signature is returned in PpsSignature.<br>
  1784. *
  1785. * Notes:
  1786. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1787. * - If the the data to be sent to security chip is more than communication buffer,#CMD_LIB_INSUFFICIENT_MEMORY is returned. Refer OPTIGA_Trust_X_SolutionReferenceManual_v1.x.pdf for more details.
  1788. * - If the memory buffer in PpsSignature is not sufficient to store the generated signature,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  1789. *
  1790. * \param[in] PpsCalcSign Pointer to #sCalcSignOptions_d to provide input for signature generation
  1791. * \param[in,out] PpsSignature Pointer to #sbBlob_d that contains generated signature
  1792. *
  1793. * \retval #CMD_LIB_OK
  1794. * \retval #CMD_LIB_ERROR
  1795. * \retval #CMD_LIB_NULL_PARAM
  1796. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1797. * \retval #CMD_DEV_EXEC_ERROR
  1798. * \retval #CMD_DEV_ERROR
  1799. */
  1800. int32_t CmdLib_CalculateSign(const sCalcSignOptions_d *PpsCalcSign,sbBlob_d *PpsSignature)
  1801. {
  1802. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1803. uint16_t wWritePosition = LEN_APDUHEADER;
  1804. uint16_t wCalApduLen;
  1805. sApduData_d sApduData = {0};
  1806. do
  1807. {
  1808. //NULL checks
  1809. if((NULL == PpsCalcSign) || (NULL == PpsSignature->prgbStream) || (NULL == PpsCalcSign->sDigestToSign.prgbStream))
  1810. {
  1811. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1812. break;
  1813. }
  1814. /// @cond hidden
  1815. ///Minimum length of APDU InData in case of calculate sign. [TLV Header(3) of OID + OID (2) + TLV Header(3) for digest ]
  1816. #define CALSIGN_APDU_LEN 8
  1817. ///Tag for Signature length
  1818. #define SIGNATURE_LEN 0x77
  1819. ///Total value required while sending the command
  1820. #define TX_LEN (CALSIGN_APDU_LEN + PpsCalcSign->sDigestToSign.wLen)
  1821. /// @endcond
  1822. //Calculate the size of memory to be allocated
  1823. wCalApduLen = LEN_APDUHEADER + (TX_LEN > SIGNATURE_LEN ? TX_LEN : SIGNATURE_LEN);
  1824. if((wMaxCommsBuffer) < wCalApduLen)
  1825. {
  1826. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1827. break;
  1828. }
  1829. //Allocating Heap memory
  1830. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1831. //Set the pointer to the response buffer
  1832. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1833. sApduData.wResponseLength = wCalApduLen;
  1834. //Set digest tag, length, data
  1835. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_DIGEST;
  1836. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsCalcSign->sDigestToSign.wLen);
  1837. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsCalcSign->sDigestToSign.prgbStream,PpsCalcSign->sDigestToSign.wLen);
  1838. wWritePosition += TAG_VALUE_OFFSET + PpsCalcSign->sDigestToSign.wLen;
  1839. //Set OID of signature key tag, length, data
  1840. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_SIG_KEY;
  1841. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_OID_SIG_KEY);
  1842. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsCalcSign->wOIDSignKey);
  1843. wWritePosition += TAG_VALUE_OFFSET + LEN_OID_SIG_KEY;
  1844. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1845. //Form Command
  1846. sApduData.bCmd = CMD_CALC_SIGN;
  1847. sApduData.bParam = (uint8_t)PpsCalcSign->eSignScheme;
  1848. //Transmit data
  1849. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1850. if(CMD_LIB_OK != i4Status)
  1851. {
  1852. break;
  1853. }
  1854. sApduData.wResponseLength -= LEN_APDUHEADER;
  1855. if(sApduData.wResponseLength > PpsSignature->wLen)
  1856. {
  1857. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1858. break;
  1859. }
  1860. //Copy signature to output buffer
  1861. OCP_MEMCPY(PpsSignature->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  1862. PpsSignature->wLen = sApduData.wResponseLength;
  1863. }while(FALSE);
  1864. //Free the allocated memory for buffer
  1865. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1866. /// @cond hidden
  1867. #undef CALSIGN_APDU_LEN
  1868. #undef SIGNATURE_LEN
  1869. #undef TX_LEN
  1870. /// @endcond
  1871. return i4Status;
  1872. }
  1873. /**
  1874. * Generates a shared secret by using the Security Chip.<br>
  1875. *
  1876. * Input:
  1877. * - Provide the key agreement algorithm for generating shared secret. Use \ref sCalcSSecOptions_d.eKeyAgreementType.
  1878. * - Provide the OID of private key. Use \ref sCalcSSecOptions_d.wOIDPrivKey.
  1879. * - Provide the algorithm identifier of the public key. Use \ref sCalcSSecOptions_d.ePubKeyAlgId.
  1880. * - Provide the public key. Use \ref sCalcSSecOptions_d.sPubKey.
  1881. * - Provide the OID to store the shared secret. Use \ref sCalcSSecOptions_d.wOIDSharedSecret.
  1882. * - 0x0000 indicates that the shared secret is exported.
  1883. *
  1884. * Output:
  1885. * - Successful API execution,
  1886. * - Calculated shared secret is returned in PpsSecret if \ref sCalcSSecOptions_d.wOIDSharedSecret is 0x0000.
  1887. *
  1888. * Notes:
  1889. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1890. * - If the the data to be sent to security chip is more than communication buffer,#CMD_LIB_INSUFFICIENT_MEMORY is returned. Refer OPTIGA_Trust_X_SolutionReferenceManual_v1.x.pdf for more details.
  1891. * - If the memory buffer in PpsSecret is not sufficient to store the calculated secret,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  1892. *
  1893. * \param[in] PpsCalcSSec Pointer to #sCalcSSecOptions_d to provide input for shared secret calculation
  1894. * \param[in,out] PpsSecret Pointer to #sbBlob_d that contains calculated shared secret
  1895. *
  1896. * \retval #CMD_LIB_OK
  1897. * \retval #CMD_LIB_ERROR
  1898. * \retval #CMD_LIB_NULL_PARAM
  1899. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1900. * \retval #CMD_DEV_EXEC_ERROR
  1901. * \retval #CMD_DEV_ERROR
  1902. */
  1903. int32_t CmdLib_CalculateSharedSecret(const sCalcSSecOptions_d *PpsCalcSSec,sbBlob_d *PpsSecret)
  1904. {
  1905. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1906. uint16_t wWritePosition = LEN_APDUHEADER;
  1907. uint16_t wCalApduLen = 0;
  1908. sApduData_d sApduData = {0};
  1909. do
  1910. {
  1911. //NULL checks
  1912. if((NULL == PpsCalcSSec) || (NULL == PpsCalcSSec->sPubKey.prgbStream))
  1913. {
  1914. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1915. break;
  1916. }
  1917. /// @cond hidden
  1918. ///Minimum length of APDU InData in case of calculate shared secret.
  1919. ///[TLV Header(3) of OID Private key + OID Private key (2) + TLV Header(3) for public key algoId + algoId (1) + TLV Header(3) for public key + TLV Header(3) for alternative ]
  1920. #define CALCSSEC_APDU_LEN 15
  1921. ///Tag for public key
  1922. #define TAG_PUBLIC_KEY 0x06
  1923. ///Len for privet key oid
  1924. #define LEN_EXPORT_SHAR_SEC 0x0000
  1925. ///Len for share sec oid
  1926. #define LEN_OID_SHARE_SEC 0x0002
  1927. ///Share sec OID zero value
  1928. #define OID_SHARE_SEC_ZERO 0x0000
  1929. ///Tag for export share secret
  1930. #define TAG_EXPORT_SHARE_SEC 0x07
  1931. ///Tag for share secret oid
  1932. #define TAG_OID_SHARE_SEC 0x08
  1933. ///Minimum length of APDU
  1934. #define TX_LEN (CALCSSEC_APDU_LEN + PpsCalcSSec->sPubKey.wLen + 2)
  1935. /// @endcond
  1936. //Considering the size of Indata for allocating memory as this size is also sufficient for storing the response
  1937. wCalApduLen = LEN_APDUHEADER + TX_LEN;
  1938. //NULL checks
  1939. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  1940. {
  1941. if(NULL == PpsSecret->prgbStream)
  1942. {
  1943. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1944. break;
  1945. }
  1946. wCalApduLen -=2;
  1947. }
  1948. //Check max comms buffer size
  1949. if((wMaxCommsBuffer) < wCalApduLen)
  1950. {
  1951. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1952. break;
  1953. }
  1954. //Allocating Heap memory
  1955. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1956. //Set the pointer to the response buffer
  1957. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1958. sApduData.wResponseLength = wCalApduLen;
  1959. //Set privet key tag, length, data
  1960. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  1961. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_PRI_KEY);
  1962. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsCalcSSec->wOIDPrivKey);
  1963. wWritePosition += TAG_VALUE_OFFSET + LEN_PRI_KEY;
  1964. //Set public key algoId tag, length, data
  1965. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_ALGO_IDENTIFIER;
  1966. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_ALGO_IDENTIFIER);
  1967. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsCalcSSec->ePubKeyAlgId;
  1968. wWritePosition += TAG_VALUE_OFFSET + LEN_ALGO_IDENTIFIER;
  1969. //Set public key tag, length, data
  1970. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_PUBLIC_KEY;
  1971. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],PpsCalcSSec->sPubKey.wLen);
  1972. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsCalcSSec->sPubKey.prgbStream,PpsCalcSSec->sPubKey.wLen);
  1973. wWritePosition += TAG_VALUE_OFFSET + PpsCalcSSec->sPubKey.wLen;
  1974. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  1975. {
  1976. //Set export share sec tag, length, data
  1977. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_SHARE_SEC;
  1978. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_SHAR_SEC);
  1979. wWritePosition += TAG_VALUE_OFFSET;
  1980. }
  1981. else
  1982. {
  1983. //Set OID of signature key tag, length, data
  1984. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_SHARE_SEC;
  1985. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_OID_SHARE_SEC);
  1986. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsCalcSSec->wOIDSharedSecret);
  1987. wWritePosition += TAG_VALUE_OFFSET + LEN_OID_SHARE_SEC;
  1988. }
  1989. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1990. //Form Command
  1991. sApduData.bCmd = CMD_CALC_SHARED_SEC;
  1992. sApduData.bParam = (uint8_t)PpsCalcSSec->eKeyAgreementType;
  1993. //Transmit data
  1994. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1995. if(CMD_LIB_OK != i4Status)
  1996. {
  1997. break;
  1998. }
  1999. sApduData.wResponseLength -= LEN_APDUHEADER;
  2000. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  2001. {
  2002. if(sApduData.wResponseLength > PpsSecret->wLen)
  2003. {
  2004. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2005. break;
  2006. }
  2007. //Copy signature to output buffer
  2008. OCP_MEMCPY(PpsSecret->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  2009. PpsSecret->wLen = sApduData.wResponseLength;
  2010. }
  2011. }while(FALSE);
  2012. //Free the allocated memory for buffer
  2013. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2014. /// @cond hidden
  2015. #undef CALCSSEC_APDU_LEN
  2016. #undef TAG_PUBLIC_KEY
  2017. #undef LEN_EXPORT_SHAR_SEC
  2018. #undef LEN_OID_SHARE_SEC
  2019. #undef OID_SHARE_SEC_ZERO
  2020. #undef TAG_EXPORT_SHARE_SEC
  2021. #undef TAG_OID_SHARE_SEC
  2022. #undef TX_LEN
  2023. /// @endcond
  2024. return i4Status;
  2025. }
  2026. /**
  2027. * Derives a session key by using the Security Chip.<br>
  2028. *
  2029. * Input:
  2030. * - Provide the key derivation method. Use \ref sDeriveKeyOptions_d.eKDM.
  2031. * - Provide the OID of the shared secret. Use \ref sDeriveKeyOptions_d.wOIDSharedSecret.
  2032. * - Provide the input seed. Use \ref sDeriveKeyOptions_d.sSeed.
  2033. * - Provide the length for derived key. Use \ref sDeriveKeyOptions_d.wDerivedKeyLen.
  2034. * - Provide the OID to store the derived key. Use \ref sDeriveKeyOptions_d.wOIDDerivedKey.
  2035. * - 0x0000 indicates that the derived key is exported.
  2036. *
  2037. * Output:
  2038. * - Successful API execution,
  2039. * - Derived key is returned in PpsKey if \ref sDeriveKeyOptions_d.wOIDDerivedKey is 0x0000.
  2040. *
  2041. * Notes:
  2042. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  2043. * - If the the data to be sent to security chip is more than communication buffer,#CMD_LIB_INSUFFICIENT_MEMORY is returned. Refer OPTIGA_Trust_X_SolutionReferenceManual_v1.x.pdf for more details.
  2044. * - If the memory buffer in PpsKey is not sufficient to store the derived key,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  2045. *
  2046. * \param[in] PpsDeriveKey Pointer to #sDeriveKeyOptions_d to provide input for session key generation
  2047. * \param[in,out] PpsKey Pointer to #sbBlob_d that contains the derived key
  2048. *
  2049. * \retval #CMD_LIB_OK
  2050. * \retval #CMD_LIB_ERROR
  2051. * \retval #CMD_LIB_NULL_PARAM
  2052. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2053. * \retval #CMD_DEV_EXEC_ERROR
  2054. * \retval #CMD_DEV_ERROR
  2055. */
  2056. int32_t CmdLib_DeriveKey(const sDeriveKeyOptions_d *PpsDeriveKey,sbBlob_d *PpsKey)
  2057. {
  2058. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2059. uint16_t wWritePosition = LEN_APDUHEADER;
  2060. uint16_t wCalApduLen = 0;
  2061. sApduData_d sApduData = {0};
  2062. do
  2063. {
  2064. //NULL checks
  2065. if((NULL == PpsDeriveKey) || (NULL == PpsDeriveKey->sSeed.prgbStream))
  2066. {
  2067. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2068. break;
  2069. }
  2070. /// @cond hidden
  2071. ///Minimum length of APDU InData in case of calculate shared secret.
  2072. ///[TLV Header(3) of OID share secret + OID share secret (2) + TLV Header(3) for seed + TLV Header(3) for derive secret length + derive secret length(2) + TLV Header(3) for alternative ]
  2073. #define DERIVEKEY_APDU_LEN 16
  2074. ///Tag for derive key
  2075. #define TAG_DERIVE_KEY 0x03
  2076. ///Len for export derive key
  2077. #define LEN_EXPORT_DERIVE_KEY 0x0000
  2078. ///Len for share sec oid
  2079. #define LEN_DERIVE_KEY 0x0002
  2080. ///Derive key OID zero value
  2081. #define OID_DERIVE_SEC_ZERO 0x0000
  2082. ///Tag for export derive share secret
  2083. #define TAG_EXPORT_DERIVE_KEY 0x07
  2084. ///Tag for derive key oid
  2085. #define TAG_OID_DERIVE_KEY 0x08
  2086. ///Minimum length of APDU
  2087. #define TX_LEN (DERIVEKEY_APDU_LEN + 2)
  2088. /// @endcond
  2089. //Considering the size of Indata for allocating memory as this size is also sufficient for storing the response
  2090. wCalApduLen = LEN_APDUHEADER + TX_LEN + (PpsDeriveKey->sSeed.wLen > PpsDeriveKey->wDerivedKeyLen ? PpsDeriveKey->sSeed.wLen : PpsDeriveKey->wDerivedKeyLen);
  2091. //NULL checks
  2092. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2093. {
  2094. if(NULL == PpsKey->prgbStream)
  2095. {
  2096. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2097. break;
  2098. }
  2099. wCalApduLen -= 2;
  2100. }
  2101. //Check max comms buffer size
  2102. if((wMaxCommsBuffer) < wCalApduLen)
  2103. {
  2104. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2105. break;
  2106. }
  2107. //Allocating Heap memory
  2108. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  2109. //Set the pointer to the response buffer
  2110. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2111. sApduData.wResponseLength = wCalApduLen;
  2112. //Set share secret key tag, length, data
  2113. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  2114. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_SHARED_SECRET_OID);
  2115. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDeriveKey->wOIDSharedSecret);
  2116. wWritePosition += TAG_VALUE_OFFSET + LEN_PRI_KEY;
  2117. //Set public key algoId tag, length, data
  2118. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_SEED;
  2119. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],PpsDeriveKey->sSeed.wLen);
  2120. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsDeriveKey->sSeed.prgbStream,PpsDeriveKey->sSeed.wLen);
  2121. wWritePosition += TAG_VALUE_OFFSET + PpsDeriveKey->sSeed.wLen;
  2122. //Set public key tag, length, data
  2123. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_DERIVE_KEY;
  2124. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_DERIVE_KEY);
  2125. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDeriveKey->wDerivedKeyLen);
  2126. wWritePosition += TAG_VALUE_OFFSET + LEN_DERIVE_KEY;
  2127. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2128. {
  2129. //Set export share sec tag, length, data
  2130. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_DERIVE_KEY;
  2131. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_DERIVE_KEY);
  2132. wWritePosition += TAG_VALUE_OFFSET;
  2133. }
  2134. else
  2135. {
  2136. //Set OID of signature key tag, length, data
  2137. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_DERIVE_KEY;
  2138. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_DERIVE_KEY);
  2139. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsDeriveKey->wOIDDerivedKey);
  2140. wWritePosition += TAG_VALUE_OFFSET + LEN_DERIVE_KEY;
  2141. }
  2142. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  2143. //Form Command
  2144. sApduData.bCmd = CMD_DERIVE_KEY;
  2145. sApduData.bParam = (uint8_t)PpsDeriveKey->eKDM;
  2146. //Transmit data
  2147. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2148. if(CMD_LIB_OK != i4Status)
  2149. {
  2150. break;
  2151. }
  2152. sApduData.wResponseLength -= LEN_APDUHEADER;
  2153. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2154. {
  2155. if(sApduData.wResponseLength > PpsKey->wLen)
  2156. {
  2157. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2158. break;
  2159. }
  2160. //Copy signature to output buffer
  2161. OCP_MEMCPY(PpsKey->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  2162. PpsKey->wLen = sApduData.wResponseLength;
  2163. }
  2164. }while(FALSE);
  2165. //Free the allocated memory for buffer
  2166. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2167. /// @cond hidden
  2168. #undef DERIVEKEY_APDU_LEN
  2169. #undef TAG_DERIVE_KEY
  2170. #undef LEN_EXPORT_DERIVE_KEY
  2171. #undef LEN_DERIVE_KEY
  2172. #undef OID_DERIVE_SEC_ZERO
  2173. #undef TAG_EXPORT_DERIVE_KEY
  2174. #undef TAG_OID_DERIVE_KEY
  2175. #undef TX_LEN
  2176. /// @endcond
  2177. return i4Status;
  2178. }
  2179. #endif/*MODULE_ENABLE_TOOLBOX*/
  2180. #ifdef MODULE_ENABLE_DTLS_MUTUAL_AUTH
  2181. /**
  2182. * Gets Handshake message from Security Chip.<br>
  2183. *
  2184. *
  2185. * Notes: <br>
  2186. * - User should provide a callback through #sCallBack_d.
  2187. * - This callback allows the caller to allocate memory for the message and keep copying data into the memory in case of lengthy messages.
  2188. * - Allocated buffer is returned to user in #sCBGetMsg_d.
  2189. * - The callback should return #CMD_LIB_OK for successful allocation of memory else #CMD_LIB_ERROR in case of error.<br>
  2190. *
  2191. * - Any Message specific data must be provided by the user in the union puMsgParams.<br>
  2192. * The union is defined as #uMsgParams_d.
  2193. *
  2194. * - The user must provide correct data in puMsgParams.This function does not <br>
  2195. * validate the content of the message specific data.
  2196. * E.g For sending gmt_unix_time for Client Hello message,uMsgParams_d.sMsgParamCH_d.dwUnixTime must be set.
  2197. * If puMsgParams is set to NULL,then random dwUnixTime will be considered for Client Hello message <br>
  2198. * and certificate will not be send for Client Certificate message.
  2199. *
  2200. * The psBlobInBuffer pointer which is member of sProcMsgData_d should be set to NULL
  2201. *
  2202. * \param[in,out] PpsGMsgVector Pointer to DTLS Handshake Message parameters
  2203. *
  2204. * \retval #CMD_LIB_OK
  2205. * \retval #CMD_LIB_ERROR
  2206. * \retval #CMD_LIB_INVALID_PARAM
  2207. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2208. * \retval #CMD_DEV_ERROR
  2209. * \retval #CMD_LIB_NULL_PARAM
  2210. */
  2211. int32_t CmdLib_GetMessage(const sProcMsgData_d *PpsGMsgVector)
  2212. {
  2213. ///@cond hidden
  2214. #define STACK_ALLOC
  2215. ///@endcond
  2216. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2217. sApduData_d sApduData;
  2218. uint8_t bFragSeq ;
  2219. uint16_t wRespLen;
  2220. sbBlob_d sBlobMessage;
  2221. do
  2222. {
  2223. //To use stack memory for APDU buffer, define STACK_ALLOC locally else heap memory is used
  2224. #ifdef STACK_ALLOC
  2225. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,MAX_APDU_BUFF_LEN);
  2226. #else
  2227. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,MAX_APDU_BUFF_LEN);
  2228. #endif
  2229. //NULL checks
  2230. if((NULL == PpsGMsgVector) || (NULL == PpsGMsgVector->psCallBack) ||
  2231. (NULL == PpsGMsgVector->psCallBack->pfAcceptMessage) || (NULL == PpsGMsgVector->psCallBack->fvParams))
  2232. {
  2233. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2234. break;
  2235. }
  2236. //Verify the range of the param
  2237. if((eClientHello != PpsGMsgVector->eParam) && (eClientHelloWithCookie != PpsGMsgVector->eParam) &&
  2238. (eClientCertificate != PpsGMsgVector->eParam) && (eClientKeyExchange != PpsGMsgVector->eParam) &&
  2239. (eCertificateVerify != PpsGMsgVector->eParam) && (eClientFinished != PpsGMsgVector->eParam))
  2240. {
  2241. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  2242. break;
  2243. }
  2244. //Verify the Session OID reference
  2245. if((SESSION_ID_LOWER_VALUE > PpsGMsgVector->wSessionKeyOID) ||
  2246. (SESSION_ID_HIGHER_VALUE < PpsGMsgVector->wSessionKeyOID))
  2247. {
  2248. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2249. break;
  2250. }
  2251. //Set the fragment sequence to start
  2252. bFragSeq = (uint8_t)eStart;
  2253. //Set the pointer to the response buffer
  2254. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2255. while((eFragSeq_d)bFragSeq != eFinal)
  2256. {
  2257. //Form data and assign to apdu structure
  2258. //Assign cmd,param,length
  2259. sApduData.bCmd = CMD_GETMSG;
  2260. sApduData.bParam = (uint8_t)PpsGMsgVector->eParam;
  2261. //Total payload length is Session ID Length
  2262. sApduData.wPayloadLength = BYTES_SESSIONID;
  2263. //Form the data in order in the buffer
  2264. //Add the session ID to the buffer
  2265. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsGMsgVector->wSessionKeyOID >> BITS_PER_BYTE);
  2266. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsGMsgVector->wSessionKeyOID;
  2267. sApduData.wResponseLength = MAX_APDU_BUFF_LEN;
  2268. if(((uint8_t)eClientHello == sApduData.bParam) && (NULL != PpsGMsgVector->puMsgParams))
  2269. {
  2270. sApduData.wPayloadLength += LEN_TAG_ENCODING + BYTES_GMT_TIME;
  2271. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_GMTUNIX_TIME;
  2272. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = 0x00;
  2273. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = BYTES_GMT_TIME;
  2274. Utility_SetUint32 (&sApduData.prgbAPDUBuffer[OFFSET_TAG_DATA],PpsGMsgVector->puMsgParams->sMsgParamCH_d.dwUnixTime);
  2275. }
  2276. else if(((uint8_t)eClientCertificate == sApduData.bParam) && (NULL != PpsGMsgVector->puMsgParams))
  2277. {
  2278. sApduData.wPayloadLength += LEN_TAG_ENCODING + BYTES_OID;
  2279. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_CERTIFICATE_OID;
  2280. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = 0x00;
  2281. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = BYTES_OID;
  2282. Utility_SetUint16 (&sApduData.prgbAPDUBuffer[OFFSET_TAG_DATA],PpsGMsgVector->puMsgParams->sMsgParamCert_d.wCertOID);
  2283. }
  2284. //Transmit data
  2285. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2286. if(CMD_LIB_OK != i4Status)
  2287. {
  2288. break;
  2289. }
  2290. //Remove 4 byte apdu header + tag encoding
  2291. sApduData.wResponseLength -= (LEN_APDUHEADER + LEN_TAG_ENCODING);
  2292. //Verify the TLV encoding
  2293. //Verify the Tag
  2294. if(TAG_UNPROTECTED != (*(sApduData.prgbRespBuffer + LEN_APDUHEADER) & MASK_HIGHER_NIBBLE))
  2295. {
  2296. i4Status = (int32_t)CMD_LIB_INVALID_TAG;
  2297. break;
  2298. }
  2299. //Extract the fragment sequence information
  2300. bFragSeq = *(sApduData.prgbRespBuffer + LEN_APDUHEADER) & MASK_LOWER_NIBBLE;
  2301. //extract the tag length field
  2302. wRespLen = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + 1);
  2303. //Length validation for response length with the tag length
  2304. if(sApduData.wResponseLength != wRespLen)
  2305. {
  2306. i4Status = (int32_t)CMD_LIB_INVALID_TAGLEN;
  2307. break;
  2308. }
  2309. //Assign the handshake message pointer to the sblob
  2310. sBlobMessage.prgbStream = sApduData.prgbRespBuffer + LEN_APDUHEADER + LEN_TAG_ENCODING;
  2311. //Assign the response length(only Handshake message) excluding the tag encoding
  2312. sBlobMessage.wLen = sApduData.wResponseLength;
  2313. //Call back function to allocate the memory for handshake message based the response length
  2314. i4Status = PpsGMsgVector->psCallBack->pfAcceptMessage(PpsGMsgVector->psCallBack->fvParams, &sBlobMessage);
  2315. if(i4Status != CMD_LIB_OK)
  2316. {
  2317. i4Status = (int32_t)CMD_LIB_ERROR;
  2318. break;
  2319. }
  2320. }
  2321. //Note: If data is encoded with eContinue then loop to get complete data till eFinal is encoded
  2322. //The response pointer should be updated for each loop and check for buffer overflow
  2323. }while(FALSE);
  2324. //Free the allocated memory for buffer
  2325. #ifndef STACK_ALLOC
  2326. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2327. #else
  2328. #undef STACK_ALLOC
  2329. #endif
  2330. return i4Status;
  2331. }
  2332. /**
  2333. * Sends Handshake message to Security Chip for processing.<br>
  2334. *
  2335. *
  2336. * Notes: <br>
  2337. * - Input buffer must be provided by the user.<br>
  2338. * - Clearing of the buffers is the responsibility of the user.
  2339. *
  2340. * - The input pointer should contain sufficient memory to accommodate <br>
  2341. * APDU header and data formatting.
  2342. *
  2343. * - The API will not recopy the Authentication message data but add the header and data<br>
  2344. * formatting information before it, in the same input buffer.
  2345. *
  2346. * The puMsgParams and psCallBack pointer which is member of sProcMsgData_d should be set to NULL
  2347. *
  2348. * \param[in] PpsPMsgVector Pointer to DTLS Handshake Message parameters
  2349. *
  2350. * \retval #CMD_LIB_OK
  2351. * \retval #CMD_LIB_ERROR
  2352. * \retval #CMD_LIB_INVALID_PARAM
  2353. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2354. * \retval #CMD_DEV_ERROR
  2355. * \retval #CMD_LIB_NULL_PARAM
  2356. */
  2357. int32_t CmdLib_PutMessage(const sProcMsgData_d *PpsPMsgVector)
  2358. {
  2359. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2360. sApduData_d sApduData;
  2361. do
  2362. {
  2363. //NULL checks
  2364. if((NULL == PpsPMsgVector) || (NULL == PpsPMsgVector->psBlobInBuffer) ||
  2365. (NULL == PpsPMsgVector->psBlobInBuffer->prgbStream))
  2366. {
  2367. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2368. break;
  2369. }
  2370. //Zero length checks
  2371. if(0x00 == PpsPMsgVector->psBlobInBuffer->wLen)
  2372. {
  2373. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  2374. break;
  2375. }
  2376. //Verify the range of the param
  2377. if(((eServerCertificate > PpsPMsgVector->eParam) || (eServerHelloDone < PpsPMsgVector->eParam)) &&
  2378. ((eServerHello != PpsPMsgVector->eParam) && (eHelloVerifyRequest != PpsPMsgVector->eParam) &&
  2379. (eServerFinished != PpsPMsgVector->eParam)))
  2380. {
  2381. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  2382. break;
  2383. }
  2384. //Verify the Session OID reference
  2385. if((SESSION_ID_LOWER_VALUE > PpsPMsgVector->wSessionKeyOID) ||
  2386. (SESSION_ID_HIGHER_VALUE < PpsPMsgVector->wSessionKeyOID))
  2387. {
  2388. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2389. break;
  2390. }
  2391. //Length of data + OverHeadLen should not to be more than wMaxCommsBuffer
  2392. //Currently, chaining is not supported by Command library and security chip.Hence, this length check is performed.
  2393. if(PpsPMsgVector->psBlobInBuffer->wLen > (wMaxCommsBuffer) )
  2394. {
  2395. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2396. break;
  2397. }
  2398. //Assign In memory pointer to the APDU Buffer in the Apdu structure
  2399. sApduData.prgbAPDUBuffer = PpsPMsgVector->psBlobInBuffer->prgbStream;
  2400. //Set the pointer to the response buffer
  2401. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2402. //Form data and assign to apdu structure
  2403. //Assign cmd,param,length
  2404. sApduData.bCmd = CMD_PUTMSG;
  2405. sApduData.bParam = (uint8_t)PpsPMsgVector->eParam;
  2406. //Total payload length is sum of length of Session ID , Tag, Tag length and the data
  2407. sApduData.wPayloadLength = PpsPMsgVector->psBlobInBuffer->wLen - OFFSET_PAYLOAD;
  2408. //Add the session ID to the buffer
  2409. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsPMsgVector->wSessionKeyOID >> BITS_PER_BYTE);
  2410. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsPMsgVector->wSessionKeyOID;
  2411. //Add the encoding tag to the buffer
  2412. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_UNPROTECTED;
  2413. sApduData.prgbAPDUBuffer[OFFSET_TAG] |= (uint8_t)eFinal;
  2414. //Add the tag length to the buffer
  2415. //lint --e{702} suppress "Acknowledging the shift. Reviewed it"
  2416. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = (uint8_t)(((PpsPMsgVector->psBlobInBuffer->wLen) - (OFFSET_PAYLOAD + BYTES_SESSIONID + LEN_TAG_ENCODING)) >> BITS_PER_BYTE);
  2417. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = (uint8_t)(PpsPMsgVector->psBlobInBuffer->wLen - (OFFSET_PAYLOAD + BYTES_SESSIONID + LEN_TAG_ENCODING));
  2418. sApduData.wResponseLength = PpsPMsgVector->psBlobInBuffer->wLen;
  2419. //Transmit data
  2420. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2421. if(CMD_LIB_OK != i4Status)
  2422. {
  2423. break;
  2424. }
  2425. }while(FALSE);
  2426. return i4Status;
  2427. }
  2428. /**
  2429. *
  2430. * Closes the DTLS session as indicated by the Session OID.<br>
  2431. *
  2432. *
  2433. * \param[in] PwSessionRefId session OID to be closed
  2434. *
  2435. * \retval #CMD_LIB_OK
  2436. * \retval #CMD_LIB_ERROR
  2437. * \retval #CMD_LIB_INVALID_SESSIONID
  2438. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2439. */
  2440. int32_t CmdLib_CloseSession(uint16_t PwSessionRefId)
  2441. {
  2442. /// @cond hidden
  2443. #define CLOSE_SESSION_APDU_BUF_LEN 6
  2444. /// @endcond
  2445. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2446. sApduData_d sApduData;
  2447. do
  2448. {
  2449. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,CLOSE_SESSION_APDU_BUF_LEN);
  2450. //Verify the session id
  2451. if((SESSION_ID_LOWER_VALUE > PwSessionRefId) ||
  2452. (SESSION_ID_HIGHER_VALUE < PwSessionRefId))
  2453. {
  2454. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2455. break;
  2456. }
  2457. //Set the pointer to the response buffer
  2458. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2459. //Form the command
  2460. //Assign Cmd,param,payload length
  2461. sApduData.bCmd = CMD_GETMSG;
  2462. sApduData.bParam = (uint8_t)eCloseSession;
  2463. //Total payload length is equal to session ID length
  2464. sApduData.wPayloadLength = BYTES_SESSIONID;
  2465. //Assign the session key
  2466. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)( PwSessionRefId >> BITS_PER_BYTE);
  2467. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PwSessionRefId;
  2468. sApduData.wResponseLength = CLOSE_SESSION_APDU_BUF_LEN;
  2469. //Transmit the Data
  2470. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2471. if(CMD_LIB_OK != i4Status)
  2472. {
  2473. break;
  2474. }
  2475. }while(FALSE);
  2476. /// @cond hidden
  2477. #undef CLOSE_SESSION_APDU_BUF_LEN
  2478. /// @endcond
  2479. return i4Status;
  2480. }
  2481. /**
  2482. * Encrypts data by issuing ProcUpLink command to Security Chip.<br>
  2483. *
  2484. *
  2485. * Notes: <br>
  2486. * - Input and Output buffers must be provided by the user.
  2487. *Buffer deallocation is the responsibility of the user.<br>
  2488. *
  2489. * - The input data in #sbBlob_d sInData should contain sufficient memory to accommodate APDU header,
  2490. *data formatting,Plaintext.<br>
  2491. *The Plaintext and any specific data for encryption should start after an overhead of #OVERHEAD_UPDOWNLINK.<br>
  2492. *
  2493. * - wInDataLength in #sProcCryptoData_d should be greater than zero.<br>
  2494. *
  2495. * - Ciphertext is returned in #sCmdResponse_d* sOutData from zero offset.<br>
  2496. *
  2497. * - In addition to the Ciphertext, the length of buffer in sOutData
  2498. *should be sufficient to accommodate Response APDU header and data formatting. This is defined as #OVERHEAD_ENCDEC_RESPONSE<br>
  2499. *The total length of the Ciphertext is returned in wRespLength of #sCmdResponse_d.<br>
  2500. *
  2501. * - The current implementation of Security chip does not support command chaining.
  2502. *The maximum value of wInDataLength depends on the value supported by the security chip.<br>
  2503. *
  2504. * - Currently,the security chip supports only 0xE100 as session key OID.
  2505. *
  2506. * \param[in,out] PpsEncVector Pointer to structure containing Plaintext and Ciphertext
  2507. *
  2508. * \retval #CMD_LIB_OK
  2509. * \retval #CMD_LIB_ERROR
  2510. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2511. * \retval #CMD_LIB_INVALID_SESSIONID
  2512. * \retval #CMD_LIB_INVALID_LEN
  2513. * \retval #CMD_DEV_ERROR
  2514. * \retval #CMD_LIB_NULL_PARAM
  2515. */
  2516. int32_t CmdLib_Encrypt(sProcCryptoData_d *PpsEncVector)
  2517. {
  2518. return CmdLib_EncDecHelper(PpsEncVector,CMD_ENCDATA,PARAM_ENC_DATA);
  2519. }
  2520. /**
  2521. * Decrypts data by issuing ProcDownLink command to Security Chip.<br>
  2522. *
  2523. *
  2524. * Notes: <br>
  2525. * - Input and Output buffers must be provided by the user.
  2526. *Buffer deallocation is the responsibility of the user.<br>
  2527. *
  2528. * - The input data in #sbBlob_d sInData should contain sufficient memory to accommodate APDU header,
  2529. *data formatting,Ciphertext.<br>
  2530. *The Ciphertext and any specific data for decryption should start after an overhead of #OVERHEAD_UPDOWNLINK.<br>
  2531. *
  2532. * - wInDataLength in #sProcCryptoData_d should be greater than zero.<br>
  2533. *
  2534. * - Plaintext is returned in #sCmdResponse_d* sOutData from zero offset.<br>
  2535. *
  2536. * - In addition to the Plaintext, the length of buffer in sOutData
  2537. *should be sufficient to accommodate Response APDU header and data formatting. This is defined as #OVERHEAD_ENCDEC_RESPONSE<br>
  2538. *The total length of the Plaintext is returned in wRespLength of #sCmdResponse_d.<br>
  2539. *
  2540. * - The current implementation of Security chip does not support command chaining.
  2541. *The maximum value of wInDataLength depends on the value supported by the security chip.<br>
  2542. *
  2543. * - Currently,the security chip supports only 0xE100 as session key OID.
  2544. *
  2545. * \param[in,out] PpsDecVector Pointer to structure containing Ciphertext and Plaintext
  2546. *
  2547. * \retval #CMD_LIB_OK
  2548. * \retval #CMD_LIB_ERROR
  2549. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2550. * \retval #CMD_LIB_INVALID_SESSIONID
  2551. * \retval #CMD_LIB_INVALID_LEN
  2552. * \retval #CMD_DEV_ERROR
  2553. * \retval #CMD_LIB_DECRYPT_FAILURE
  2554. * \retval #CMD_LIB_NULL_PARAM
  2555. */
  2556. int32_t CmdLib_Decrypt(sProcCryptoData_d *PpsDecVector)
  2557. {
  2558. return CmdLib_EncDecHelper(PpsDecVector,CMD_DECDATA,PARAM_DEC_DATA);
  2559. }
  2560. #endif /* MODULE_ENABLE_DTLS_MUTUAL_AUTH*/
  2561. /**
  2562. * @}
  2563. */