CommandLib.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975
  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. sHashinfo_d sHashInfo[1]={
  245. {eSHA256, SHA256_HASH_LEN, CALC_HASH_SHA256_CONTEXT_SIZE}
  246. };
  247. /**
  248. * \brief Structure to specify algorithm identifier and key length.
  249. */
  250. typedef struct sAlgoinfo
  251. {
  252. ///Algorithm type
  253. eAlgId_d eAlgKeyId;
  254. ///Key Length
  255. uint8_t bKeyLen;
  256. }sAlgoInfo_d;
  257. //Algorithm identifier
  258. sAlgoInfo_d sAlgoInfo[2]={
  259. {eECC_NIST_P256, ECC_NIST_P_256_KEY_LEN},
  260. {eECC_NIST_P384, ECC_NIST_P_384_KEY_LEN}
  261. };
  262. /**
  263. * \brief Structure to specify GetDataObject command parameters.
  264. */
  265. typedef struct sApduData_d
  266. {
  267. ///Cmd of the APDU
  268. uint8_t bCmd;
  269. ///Param of APDU
  270. uint8_t bParam;
  271. ///Payload length
  272. uint16_t wPayloadLength;
  273. //Payload Data
  274. uint8_t* prgbAPDUBuffer;
  275. //Response Data
  276. uint8_t* prgbRespBuffer;
  277. //Response Length
  278. uint16_t wResponseLength;
  279. }sApduData_d;
  280. /**
  281. * \brief Enumeration to specify the sequence of message/record.
  282. */
  283. //lint --e{749} suppress "Added for future use"
  284. typedef enum eFragSeq_d
  285. {
  286. ///Start
  287. eStart = 0x00,
  288. ///Final
  289. eFinal = 0x01,
  290. ///Intermediate
  291. eContinue = 0x02
  292. }eFragSeq_d;
  293. volatile static host_lib_status_t optiga_comms_status;
  294. //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"
  295. static void optiga_comms_event_handler(void* upper_layer_ctx, host_lib_status_t event)
  296. {
  297. optiga_comms_status = event;
  298. }
  299. /**
  300. *
  301. * Gets the device error code by reading the Error code object id.<br>
  302. * If there is an internal error in function, then #CMD_DEV_ERROR is returned.<br>
  303. * Otherwise,the device error code is ORed with #CMD_DEV_ERROR and returned.<br>
  304. *
  305. *
  306. * \retval #CMD_DEV_ERROR
  307. * \retval #CMD_LIB_ERROR
  308. * \retval #CMD_DEV_EXEC_ERROR
  309. *
  310. */
  311. _STATIC_H int32_t CmdLib_GetDeviceError(void)
  312. {
  313. int32_t i4Status = (int32_t)CMD_DEV_ERROR;
  314. uint8_t rgbErrorCmd[] = {CMD_GETDATA,0x00,0x00,0x02,(uint8_t)(OID_ERROR>>8),(uint8_t)OID_ERROR};
  315. uint16_t wBufferLength = sizeof(rgbErrorCmd);
  316. do
  317. {
  318. p_optiga_comms->upper_layer_handler = optiga_comms_event_handler;
  319. optiga_comms_status = OPTIGA_COMMS_BUSY;
  320. i4Status = optiga_comms_transceive(p_optiga_comms,rgbErrorCmd,&wBufferLength,
  321. rgbErrorCmd,&wBufferLength);
  322. if(OPTIGA_COMMS_SUCCESS != i4Status)
  323. {
  324. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  325. break;
  326. }
  327. //wait for completion
  328. while(optiga_comms_status == OPTIGA_COMMS_BUSY){
  329. #ifdef USE_CMDLIB_WITH_RTOS
  330. pal_os_timer_delay_in_milliseconds(1);
  331. #endif
  332. };
  333. if(optiga_comms_status != OPTIGA_COMMS_SUCCESS)
  334. {
  335. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  336. break;
  337. }
  338. if(0 == rgbErrorCmd[OFFSET_RESP_STATUS])
  339. { //If response Header
  340. i4Status = (int32_t)(CMD_DEV_ERROR | rgbErrorCmd[OFFSET_PAYLOAD]);
  341. }
  342. else
  343. {
  344. //In this case, execution error is returned.
  345. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  346. }
  347. }while(FALSE);
  348. return i4Status;
  349. }
  350. /**
  351. * \brief Formats data as per Security Chip application and send using the communication functions.
  352. */
  353. _STATIC_H int32_t TransceiveAPDU(sApduData_d *PpsApduData,uint8_t bGetError)
  354. {
  355. //lint --e{818} suppress "PpsResponse is out parameter"
  356. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  357. uint16_t wTotalLength;
  358. do
  359. {
  360. if(NULL == PpsApduData || NULL == p_optiga_comms)
  361. {
  362. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  363. break;
  364. }
  365. PpsApduData->prgbAPDUBuffer[OFFSET_CMD] = PpsApduData->bCmd;
  366. PpsApduData->prgbAPDUBuffer[OFFSET_PARAM] = PpsApduData->bParam;
  367. //copy length
  368. PpsApduData->prgbAPDUBuffer[OFFSET_LENGTH] = (uint8_t)(PpsApduData->wPayloadLength >> BITS_PER_BYTE);
  369. PpsApduData->prgbAPDUBuffer[OFFSET_LENGTH+1] = (uint8_t)PpsApduData->wPayloadLength;
  370. //update total length to consider total header length
  371. wTotalLength = PpsApduData->wPayloadLength + LEN_APDUHEADER;
  372. p_optiga_comms->upper_layer_handler = optiga_comms_event_handler;
  373. optiga_comms_status = OPTIGA_COMMS_BUSY;
  374. i4Status = optiga_comms_transceive(p_optiga_comms,PpsApduData->prgbAPDUBuffer,&wTotalLength,
  375. PpsApduData->prgbRespBuffer,&PpsApduData->wResponseLength);
  376. if(OPTIGA_COMMS_SUCCESS != i4Status)
  377. {
  378. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  379. break;
  380. }
  381. //wait for completion
  382. do
  383. {
  384. #ifdef USE_CMDLIB_WITH_RTOS
  385. pal_os_timer_delay_in_milliseconds(1);
  386. #endif
  387. }while(optiga_comms_status == OPTIGA_COMMS_BUSY);
  388. if(optiga_comms_status != OPTIGA_COMMS_SUCCESS)
  389. {
  390. i4Status = (int32_t)CMD_DEV_EXEC_ERROR;
  391. break;
  392. }
  393. //return device error if not success
  394. if(0 != PpsApduData->prgbRespBuffer[OFFSET_RESP_STATUS])
  395. {
  396. if(TRUE == bGetError)
  397. {
  398. i4Status = CmdLib_GetDeviceError();
  399. }
  400. else
  401. {
  402. i4Status = (int32_t)CMD_LIB_ERROR;
  403. }
  404. break;
  405. }
  406. i4Status = CMD_LIB_OK;
  407. }while(FALSE);
  408. return i4Status;
  409. }
  410. /**
  411. * \brief Read the maximum size of communication buffer supported by the security chip by reading "Max comms buffer size" OID.
  412. */
  413. _STATIC_H int32_t GetMaxCommsBuffer()
  414. {
  415. #define GETDATA_MAX_COMMS_SIZE 10
  416. #define OID_MAX_COMMS_SIZE 0xE0C6
  417. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  418. sApduData_d sApduData;
  419. do
  420. {
  421. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,GETDATA_MAX_COMMS_SIZE);
  422. //Set the pointer to the response buffer
  423. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  424. //Set the CMD
  425. sApduData.bCmd = CMD_GETDATA;
  426. sApduData.bParam = PARAM_GET_DATA;
  427. sApduData.wPayloadLength = LEN_PL_OID;
  428. sApduData.wResponseLength = GETDATA_MAX_COMMS_SIZE;
  429. //copy OID
  430. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(OID_MAX_COMMS_SIZE >> BITS_PER_BYTE);
  431. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD +1] = (uint8_t)OID_MAX_COMMS_SIZE;
  432. i4Status = TransceiveAPDU(&sApduData,TRUE);
  433. if(CMD_LIB_OK != i4Status)
  434. {
  435. break;
  436. }
  437. //Assign value to MaxCommsBuffer
  438. wMaxCommsBuffer = (uint16_t )((sApduData.prgbRespBuffer[LEN_APDUHEADER] << 8) | (sApduData.prgbRespBuffer[LEN_APDUHEADER+1]));
  439. }while(FALSE);
  440. #undef GETDATA_MAX_COMMS_SIZE
  441. #undef OID_MAX_COMMS_SIZE
  442. return i4Status;
  443. }
  444. #ifdef MODULE_ENABLE_DTLS_MUTUAL_AUTH
  445. /**
  446. * \brief A common function for CmdLib_Encrypt and CmdLib_Decrypt.
  447. *
  448. */
  449. _STATIC_H int32_t CmdLib_EncDecHelper(sProcCryptoData_d *PpsCryptoVector, uint8_t PbCmd, uint8_t PbParam);
  450. /**
  451. * A common function for CmdLib_Encrypt and CmdLib_Decrypt.<br>
  452. * Forms the APDU required for encryption/decryption and sends to the security chip for processing.<br>
  453. *
  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,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_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. *
  985. * Notes:
  986. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  987. * - The function does not verify if the read access is permitted for the data object.<br>
  988. *
  989. * \retval #CMD_LIB_OK
  990. * \retval #CMD_LIB_ERROR
  991. */
  992. uint16_t CmdLib_GetMaxCommsBufferSize(Void)
  993. {
  994. return wMaxCommsBuffer;
  995. }
  996. #endif /* MODULE_ENABLE_READ_WRITE */
  997. /**
  998. * Gets the signature generated by Security Chip. The message to be signed is provided by the user.<br>
  999. * The following commands are issued in the sequence.<br>
  1000. * - SetAuthScheme : To set authentication scheme and the private key to be used <br>
  1001. * - SetAuthMsg : To write the message to Security Chip that must be digitally signed.<br>
  1002. * - GetAuthMsg : To read the digitally signed message from Security Chip.<br>
  1003. *
  1004. * <br>
  1005. * Notes: <br>
  1006. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1007. * - The function just returns the signature without verifying it.
  1008. * - The private key to be used in set auth scheme is passed in \ref #sAuthMsg_d.wOIDDevPrivKey.
  1009. * - The \ref #sAuthMsg_d.prgbRnd and \ref #sAuthMsg_d.wRndLength carry the challenge to be signed.
  1010. * - 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>
  1011. *
  1012. *\param[in] PpsAuthMsg Pointer to Get Signature Object inputs
  1013. *\param[in,out] PpsResponse Pointer to Response structure
  1014. *
  1015. * \retval #CMD_LIB_OK
  1016. * \retval #CMD_LIB_ERROR
  1017. * \retval #CMD_DEV_ERROR
  1018. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1019. * \retval #CMD_LIB_NULL_PARAM
  1020. * \retval #CMD_LIB_INVALID_LEN
  1021. */
  1022. int32_t CmdLib_GetSignature(const sAuthMsg_d *PpsAuthMsg, sCmdResponse_d *PpsResponse)
  1023. {
  1024. /// @cond hidden
  1025. #define STACK_ALLOC
  1026. #define GETSIGN_APDU_BUF_LEN 270 //4 (cmd header) + 256 (Max Payload) + additional 10
  1027. /// @endcond
  1028. //lint --e{818} suppress "PpsResponse is out parameter"
  1029. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1030. sApduData_d sApduData;
  1031. sAuthScheme_d sAuthScheme;
  1032. do
  1033. {
  1034. //To use stack memory for APDU buffer, define STACK_ALLOC locally else heap memory is used
  1035. #ifdef STACK_ALLOC
  1036. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,GETSIGN_APDU_BUF_LEN);
  1037. #else
  1038. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,GETSIGN_APDU_BUF_LEN);
  1039. #endif
  1040. if((NULL == PpsAuthMsg)||(NULL == PpsAuthMsg->prgbRnd)||
  1041. (NULL == PpsResponse)||(NULL == PpsResponse->prgbBuffer))
  1042. {
  1043. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1044. break;
  1045. }
  1046. //Check if Challenge length is in between 8 to 256
  1047. if((CHALLENGE_MIN_LEN > PpsAuthMsg->wRndLength) || (CHALLENGE_MAX_LEN < PpsAuthMsg->wRndLength))
  1048. {
  1049. i4Status = (int32_t)CMD_LIB_INVALID_LEN;
  1050. break;
  1051. }
  1052. //Set the pointer to the response buffer
  1053. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1054. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1055. //Set Auth scheme
  1056. sAuthScheme.eAuthScheme = eECDSA;
  1057. sAuthScheme.wDevicePrivKey = PpsAuthMsg->wOIDDevPrivKey;
  1058. i4Status = CmdLib_SetAuthScheme(&sAuthScheme);
  1059. if(CMD_LIB_OK != i4Status)
  1060. {
  1061. break;
  1062. }
  1063. //Set Auth msg
  1064. sApduData.bCmd = CMD_SETAUTH_MSG;
  1065. sApduData.bParam = PARAM_SET_AUTH_MSG;
  1066. sApduData.wPayloadLength = PpsAuthMsg->wRndLength;
  1067. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1068. //copy the random number
  1069. OCP_MEMCPY(sApduData.prgbAPDUBuffer+OFFSET_PAYLOAD,PpsAuthMsg->prgbRnd,PpsAuthMsg->wRndLength);
  1070. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1071. if(CMD_LIB_OK != i4Status)
  1072. {
  1073. break;
  1074. }
  1075. //Get Auth msg
  1076. sApduData.bCmd = CMD_GETAUTH_MSG;
  1077. sApduData.bParam = PARAM_GET_AUTH_MSG;
  1078. sApduData.wPayloadLength = 0;
  1079. sApduData.wResponseLength = GETSIGN_APDU_BUF_LEN;
  1080. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1081. if(CMD_LIB_OK != i4Status)
  1082. {
  1083. break;
  1084. }
  1085. //strip 4 byte apdu header
  1086. sApduData.wResponseLength -= LEN_APDUHEADER;
  1087. PpsResponse->wRespLength = sApduData.wResponseLength;
  1088. if(PpsResponse->wBufferLength < sApduData.wResponseLength)
  1089. {
  1090. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1091. break;
  1092. }
  1093. OCP_MEMCPY(PpsResponse->prgbBuffer,sApduData.prgbAPDUBuffer+LEN_APDUHEADER,sApduData.wResponseLength);
  1094. }while(FALSE);
  1095. #ifndef STACK_ALLOC
  1096. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1097. #else
  1098. #undef STACK_ALLOC
  1099. #endif
  1100. ///@cond hidden
  1101. #undef GETSIGN_APDU_BUF_LEN
  1102. ///@endcond
  1103. return i4Status;
  1104. }
  1105. /**
  1106. * Gets random bytes generated by the Security Chip.<br>
  1107. *
  1108. * <br>
  1109. * Notes: <br>
  1110. * - Command chaining is not supported in this API.<br>
  1111. * - 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>
  1112. *
  1113. *\param[in] PpsRng Pointer to sRngOptions_d to specify random number generation
  1114. *\param[in,out] PpsResponse Pointer to sCmdResponse_d to store random number
  1115. *
  1116. * \retval #CMD_LIB_OK
  1117. * \retval #CMD_LIB_ERROR
  1118. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1119. * \retval #CMD_LIB_LENZERO_ERROR
  1120. * \retval #CMD_DEV_ERROR
  1121. * \retval #CMD_LIB_NULL_PARAM
  1122. */
  1123. int32_t CmdLib_GetRandom(const sRngOptions_d *PpsRng, sCmdResponse_d *PpsResponse)
  1124. {
  1125. //lint --e{818} suppress "PpsResponse is out parameter"
  1126. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1127. sApduData_d sApduData;
  1128. do
  1129. {
  1130. //Initial value set it to NULL
  1131. sApduData.prgbAPDUBuffer = NULL;
  1132. if((NULL == PpsRng)||(NULL == PpsResponse)||(NULL == PpsResponse->prgbBuffer))
  1133. {
  1134. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1135. break;
  1136. }
  1137. if(0x00 == PpsResponse->wBufferLength)
  1138. {
  1139. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  1140. break;
  1141. }
  1142. //If the length of requested random bytes is more than the maximum comms buffer size
  1143. if((wMaxCommsBuffer) < (LEN_APDUHEADER + PpsRng->wRandomDataLen))
  1144. {
  1145. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1146. break;
  1147. }
  1148. PpsResponse->wRespLength = 0;
  1149. sApduData.bCmd = CMD_GET_RND;
  1150. sApduData.bParam = (uint8_t)PpsRng->eRngType;
  1151. sApduData.wPayloadLength = LEN_PL_OID;
  1152. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer, (LEN_APDUHEADER + PpsRng->wRandomDataLen));
  1153. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsRng->wRandomDataLen >> BITS_PER_BYTE);
  1154. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsRng->wRandomDataLen;
  1155. sApduData.wResponseLength = (LEN_APDUHEADER + PpsRng->wRandomDataLen);
  1156. //Set the pointer to the response buffer
  1157. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1158. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1159. if(CMD_LIB_OK != i4Status)
  1160. {
  1161. break;
  1162. }
  1163. //strip 4 byte apdu header
  1164. sApduData.wResponseLength -= LEN_APDUHEADER;
  1165. if(PpsResponse->wBufferLength < sApduData.wResponseLength)
  1166. {
  1167. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1168. break;
  1169. }
  1170. OCP_MEMCPY(PpsResponse->prgbBuffer,sApduData.prgbAPDUBuffer+LEN_APDUHEADER,sApduData.wResponseLength);
  1171. PpsResponse->wRespLength = sApduData.wResponseLength;
  1172. }while(FALSE);
  1173. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1174. return i4Status;
  1175. }
  1176. /**
  1177. * Sets the Authentication Scheme by issuing SetAuthScheme command to Security Chip.
  1178. *
  1179. * <br>
  1180. * Notes: <br>
  1181. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1182. * - Currently only 1 session OID (0xE100) is supported by the security chip.
  1183. *
  1184. *\param[in] PpsAuthVector Pointer to Authentication Scheme data
  1185. *
  1186. * \retval #CMD_LIB_OK
  1187. * \retval #CMD_LIB_ERROR
  1188. * \retval #CMD_LIB_INVALID_PARAM
  1189. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1190. * \retval #CMD_DEV_ERROR
  1191. * \retval #CMD_LIB_NULL_PARAM
  1192. */
  1193. int32_t CmdLib_SetAuthScheme(const sAuthScheme_d *PpsAuthVector)
  1194. {
  1195. /// @cond hidden
  1196. #define SET_AUTH_SCHEME_APDU_BUF_LEN 10
  1197. /// @endcond
  1198. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1199. sApduData_d sApduData;
  1200. uint16_t wPayloadSize;
  1201. do
  1202. {
  1203. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer, SET_AUTH_SCHEME_APDU_BUF_LEN);
  1204. if(NULL == PpsAuthVector)
  1205. {
  1206. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1207. break;
  1208. }
  1209. //verify the param
  1210. if(eDTLSClient == PpsAuthVector->eAuthScheme)
  1211. {
  1212. //Verify the range of session ID
  1213. if((SESSION_ID_LOWER_VALUE > PpsAuthVector->wSessionKeyId)
  1214. || (SESSION_ID_HIGHER_VALUE < PpsAuthVector->wSessionKeyId))
  1215. {
  1216. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  1217. break;
  1218. }
  1219. wPayloadSize = 4;
  1220. }
  1221. else if(eECDSA == PpsAuthVector->eAuthScheme)
  1222. {
  1223. wPayloadSize = 2;
  1224. }
  1225. else
  1226. {
  1227. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  1228. break;
  1229. }
  1230. //Set the pointer to the response buffer
  1231. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1232. //Form the command
  1233. //Assign Cmd,param,payload length
  1234. sApduData.bCmd = CMD_SETAUTH_SCM;
  1235. sApduData.bParam = (uint8_t)PpsAuthVector->eAuthScheme;
  1236. sApduData.wPayloadLength = wPayloadSize;
  1237. //Assign the device private key OID at payload offset
  1238. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsAuthVector->wDevicePrivKey >> BITS_PER_BYTE);
  1239. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+1] = (uint8_t)PpsAuthVector->wDevicePrivKey;
  1240. sApduData.wResponseLength = SET_AUTH_SCHEME_APDU_BUF_LEN;
  1241. if(eDTLSClient == PpsAuthVector->eAuthScheme)
  1242. {
  1243. //Assign the session OID
  1244. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+2] = (uint8_t)(PpsAuthVector->wSessionKeyId >> BITS_PER_BYTE);
  1245. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD+3] = (uint8_t)PpsAuthVector->wSessionKeyId;
  1246. }
  1247. //Transmit the Data
  1248. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1249. if(CMD_LIB_OK != i4Status)
  1250. {
  1251. break;
  1252. }
  1253. }while(FALSE);
  1254. /// @cond hidden
  1255. #undef SET_AUTH_SCHEME_APDU_BUF_LEN
  1256. /// @endcond
  1257. return i4Status;
  1258. }
  1259. #ifdef MODULE_ENABLE_TOOLBOX
  1260. /**
  1261. * Calculates the hash of input data by using the Security Chip.<br>
  1262. *
  1263. * Input:<br>
  1264. * - Provide the required type of input data for hashing. Use \ref sCalcHash_d.eHashDataType with the following options,
  1265. * - eDataStream : Indicates, sDataStream is considered as hash input.
  1266. * - eOIDData : Indicates, sOIDData is considered for hash input.
  1267. *
  1268. * - Provide the input to import/export the hash context. Use \ref sContextInfo_d.eContextAction with the following options,
  1269. * - #eImport : Import hash context to perform the hash.
  1270. * - #eExport : Export current active hash context.
  1271. * - #eImportExport : Import hash context and Export back the context after hashing.
  1272. * - #eUnused : Context data import/export feature is not used. This option is also recommended for #eHashSequence_d as #eStartFinalizeHash or #eTerminateHash.
  1273. *
  1274. * Output:<br>
  1275. * - Successful API execution,
  1276. * - Hash is returned in sOutHash only if #eHashSequence_d is #eStartFinalizeHash,#eIntermediateHash or #eFinalizeHash.<br>
  1277. * - Hash context data is returned only if \ref sContextInfo_d.eContextAction is #eExport or #eImportExport.<br>
  1278. *
  1279. * Notes: <br>
  1280. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1281. * - #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.
  1282. * - Sequences for generating a hash successfully can be as follows:<br>
  1283. * - #eStartHash,#eFinalizeHash<br>
  1284. * - #eStartHash,#eContinueHash (single or multiple),#eFinalizeHash<br>
  1285. * - #eStartFinalizeHash<br>
  1286. * - #eStartHash,#eIntermediateHash,#eContinueHash,#eFinalizeHash<br>
  1287. *
  1288. * - 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.
  1289. * - This API does not maintain any state of hashing operations.<br>
  1290. * - 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>
  1291. * 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
  1292. * TLV encoding must be considered as explained below.<br>
  1293. *
  1294. * Read the maximum communication buffer size using the API #CmdLib_GetMaxCommsBufferSize() and store in a variable <b>"wMaxCommsBuffer"</b><br>
  1295. * 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>
  1296. *
  1297. * - Only hash calculation : <br>
  1298. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Available_Size = (wMaxCommsBuffer - #CALC_HASH_FIXED_OVERHEAD_SIZE)<br>
  1299. * - Import context to security chip and calculate hash : <br>
  1300. * &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>
  1301. * - Calulate hash and export context out of security chip : <br>
  1302. * &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>
  1303. * - Import context to security chip, calculate hash and export context out of security chip :<br>
  1304. * &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>
  1305. *
  1306. *
  1307. * \param[in,out] PpsCalcHash Pointer to #sCalcHash_d that contains information to calculate hash
  1308. *
  1309. * \retval #CMD_LIB_OK
  1310. * \retval #CMD_LIB_ERROR
  1311. * \retval #CMD_LIB_NULL_PARAM
  1312. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1313. * \retval #CMD_DEV_EXEC_ERROR
  1314. * \retval #CMD_DEV_ERROR
  1315. */
  1316. int32_t CmdLib_CalcHash(sCalcHash_d* PpsCalcHash)
  1317. {
  1318. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1319. sApduData_d sApduData;
  1320. eDataType_d eHashDataType;
  1321. uint16_t wMemoryAllocLen;
  1322. uint16_t wInDataLen;
  1323. sHashinfo_d* psHashinfo;
  1324. uint16_t wOptTagLen = 0;
  1325. uint16_t wOptTagOffset = 0;
  1326. uint16_t wOffset;
  1327. uint16_t wBufferLen;
  1328. do
  1329. {
  1330. //Initial value set it to NULL
  1331. sApduData.prgbAPDUBuffer = NULL;
  1332. //Check for NULL inputs
  1333. if(NULL == PpsCalcHash)
  1334. {
  1335. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1336. break;
  1337. }
  1338. i4Status = Get_HashInfo(PpsCalcHash->eHashAlg, &psHashinfo);
  1339. if(CMD_LIB_OK != i4Status)
  1340. {
  1341. break;
  1342. }
  1343. //For eHashSequence_d as eFinalizeHash,validate sOutData
  1344. if(((eFinalizeHash == PpsCalcHash->eHashSequence) || (eStartFinalizeHash == PpsCalcHash->eHashSequence) ||
  1345. (eIntermediateHash == PpsCalcHash->eHashSequence)) && (NULL == PpsCalcHash->sOutHash.prgbBuffer))
  1346. {
  1347. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1348. break;
  1349. }
  1350. //Validate the Context data buffer if optional tag is provided
  1351. if((eUnused != PpsCalcHash->sContextInfo.eContextAction) && (NULL == PpsCalcHash->sContextInfo.pbContextData))
  1352. {
  1353. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1354. break;
  1355. }
  1356. /// @cond hidden
  1357. #define INDATA_LEN_OID (BYTES_OID + BYTES_LENGTH + BYTES_OFFSET)
  1358. #define NIBBLE_LEN 4
  1359. /// @endcond
  1360. eHashDataType = PpsCalcHash->eHashDataType;
  1361. //For eHashDataType_d as eDataStream, validate psDataStream
  1362. if(eTerminateHash == PpsCalcHash->eHashSequence)
  1363. {
  1364. wInDataLen = 0;
  1365. eHashDataType = eDataStream;
  1366. }
  1367. else if(eDataStream == eHashDataType)
  1368. {
  1369. if(NULL == PpsCalcHash->sDataStream.prgbStream)
  1370. {
  1371. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1372. break;
  1373. }
  1374. //Set the total data length as input length
  1375. wInDataLen = PpsCalcHash->sDataStream.wLen;
  1376. }
  1377. else
  1378. {
  1379. //Set the total data length as 6 bytes (2 byte OID + 2 bytes Offset + 2 bytes Length)
  1380. wInDataLen = INDATA_LEN_OID;
  1381. }
  1382. //Calculate the offset and length for optional tags in the command APDU
  1383. if(eUnused != PpsCalcHash->sContextInfo.eContextAction)
  1384. {
  1385. wOptTagLen = (eExport != PpsCalcHash->sContextInfo.eContextAction)? (CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE + PpsCalcHash->sContextInfo.dwContextLen) : (CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE);
  1386. //Total length of optional tag which includes tag, length and data
  1387. if(eImportExport == PpsCalcHash->sContextInfo.eContextAction)
  1388. {
  1389. wOptTagLen += CALC_HASH_IMPORT_OR_EXPORT_OVERHEAD_SIZE;
  1390. }
  1391. wOptTagOffset = (eDataStream == PpsCalcHash->eHashDataType)? (OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + wInDataLen) :
  1392. (OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + INDATA_LEN_OID);
  1393. }
  1394. //Validate the size of input data with the Communication buffer
  1395. if((wInDataLen + wOptTagLen + CALC_HASH_FIXED_OVERHEAD_SIZE) > wMaxCommsBuffer)
  1396. {
  1397. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1398. break;
  1399. }
  1400. //Form data
  1401. sApduData.bCmd = CMD_CALCHASH;
  1402. sApduData.bParam = (uint8_t)PpsCalcHash->eHashAlg;
  1403. wMemoryAllocLen = CALC_HASH_FIXED_OVERHEAD_SIZE + wInDataLen + wOptTagLen;
  1404. wBufferLen = CALC_HASH_FIXED_OVERHEAD_SIZE;
  1405. //Check to validate sufficient memory to store the output
  1406. //If Hash is the output
  1407. if((eFinalizeHash == PpsCalcHash->eHashSequence) || (eStartFinalizeHash == PpsCalcHash->eHashSequence) ||
  1408. (eIntermediateHash == PpsCalcHash->eHashSequence))
  1409. {
  1410. wBufferLen += psHashinfo->bHashLen;
  1411. }
  1412. //If context data is output
  1413. if((eExport == PpsCalcHash->sContextInfo.eContextAction) || (eImportExport == PpsCalcHash->sContextInfo.eContextAction))
  1414. {
  1415. wBufferLen += psHashinfo->wHashCntx;
  1416. }
  1417. if(wBufferLen > wMemoryAllocLen)
  1418. {
  1419. wMemoryAllocLen = wBufferLen;
  1420. }
  1421. // Allocate the memory
  1422. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer, wMemoryAllocLen);
  1423. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(((uint8_t)eHashDataType << NIBBLE_LEN) | (uint8_t) PpsCalcHash->eHashSequence);
  1424. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ] = (uint8_t)(wInDataLen >> 8);
  1425. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + 1] = (uint8_t)wInDataLen ;
  1426. if(eTerminateHash != PpsCalcHash->eHashSequence)
  1427. {
  1428. //If the DataType is Data stream, copy the input data to the buffer
  1429. if(eDataStream == eHashDataType)
  1430. {
  1431. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH], PpsCalcHash->sDataStream.prgbStream,
  1432. wInDataLen);
  1433. }
  1434. else
  1435. {
  1436. //If the Data type is OID, copy the OID information to the buffer
  1437. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH] = (uint8_t)(PpsCalcHash->sOIDData.wOID >> 8);
  1438. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + 1] = (uint8_t)PpsCalcHash->sOIDData.wOID;
  1439. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + BYTES_OID] = (uint8_t)(PpsCalcHash->sOIDData.wOffset >> 8);
  1440. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + BYTES_LENGTH + BYTES_OID + 1] = (uint8_t)PpsCalcHash->sOIDData.wOffset;
  1441. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + INDATA_LEN_OID] = (uint8_t)(PpsCalcHash->sOIDData.wLength >> 8);
  1442. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + BYTES_SEQ + INDATA_LEN_OID + 1] = (uint8_t)(PpsCalcHash->sOIDData.wLength);
  1443. }
  1444. /// @cond hidden
  1445. #define OFFSET_EXPORT_CNTXTAG (wOptTagOffset + BYTES_SEQ+ BYTES_LENGTH + PpsCalcHash->sContextInfo.dwContextLen)
  1446. /// @endcond
  1447. //If the optional tag is either eImport or eImportAndExport, 0x06 tag is sent as part of command APDU
  1448. if((eImportExport == PpsCalcHash->sContextInfo.eContextAction) ||
  1449. (eImport == PpsCalcHash->sContextInfo.eContextAction))
  1450. {
  1451. sApduData.prgbAPDUBuffer[wOptTagOffset] = (uint8_t)eImport;
  1452. sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ] = (uint8_t)(PpsCalcHash->sContextInfo.dwContextLen >> 8);
  1453. sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ + 1] = (uint8_t)(PpsCalcHash->sContextInfo.dwContextLen);
  1454. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wOptTagOffset + BYTES_SEQ + BYTES_LENGTH], PpsCalcHash->sContextInfo.pbContextData,
  1455. PpsCalcHash->sContextInfo.dwContextLen);
  1456. }
  1457. //If the optional tag is either eExport or eImportAndeExport, 0x07 tag is sent as part of command APDU
  1458. if((eImportExport == PpsCalcHash->sContextInfo.eContextAction) ||
  1459. (eExport == PpsCalcHash->sContextInfo.eContextAction))
  1460. {
  1461. wOffset = (eExport == PpsCalcHash->sContextInfo.eContextAction)?wOptTagOffset : OFFSET_EXPORT_CNTXTAG;
  1462. sApduData.prgbAPDUBuffer[wOffset] = (uint8_t)eExport;
  1463. sApduData.prgbAPDUBuffer[wOffset + BYTES_SEQ] = 0x00;
  1464. sApduData.prgbAPDUBuffer[wOffset + BYTES_SEQ + 1] =0x00;
  1465. }
  1466. }
  1467. //set data payload length is 3(BYTES_SEQ + BYTES_LENGTH) plus length of data to write
  1468. sApduData.wPayloadLength = BYTES_SEQ + BYTES_LENGTH + wInDataLen + wOptTagLen;
  1469. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1470. sApduData.wResponseLength = wMemoryAllocLen;
  1471. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1472. if(CMD_LIB_OK != i4Status)
  1473. {
  1474. break;
  1475. }
  1476. /// @cond hidden
  1477. #define TAG_HASH_OUTPUT 0x01
  1478. #define TAG_CONTEXT_OUTPUT 0x06
  1479. /// @endcond
  1480. sApduData.wResponseLength -= LEN_APDUHEADER;
  1481. //Validate the output buffer size if tag received on reponse is 0x01 and
  1482. //copy the hash data to sOutput buffer
  1483. if((TAG_HASH_OUTPUT == (*(sApduData.prgbRespBuffer + LEN_APDUHEADER))) && (sApduData.wResponseLength != 0))
  1484. {
  1485. //Length check for sOutData
  1486. if((psHashinfo->bHashLen) > PpsCalcHash->sOutHash.wBufferLength)
  1487. {
  1488. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1489. break;
  1490. }
  1491. PpsCalcHash->sOutHash.wRespLength = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + BYTES_SEQ);
  1492. OCP_MEMCPY(PpsCalcHash->sOutHash.prgbBuffer, (sApduData.prgbRespBuffer + CALC_HASH_FIXED_OVERHEAD_SIZE), PpsCalcHash->sOutHash.wRespLength);
  1493. }
  1494. //Validate the Context buffer size if the 0x06 context data tag is there in response and
  1495. //copy the context data to pbContextData buffer
  1496. if((TAG_CONTEXT_OUTPUT == (*(sApduData.prgbRespBuffer + LEN_APDUHEADER))) && (sApduData.wResponseLength != 0))
  1497. {
  1498. //Length check for Context Data
  1499. if((psHashinfo->wHashCntx) > PpsCalcHash->sContextInfo.dwContextLen)
  1500. {
  1501. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1502. break;
  1503. }
  1504. PpsCalcHash->sContextInfo.dwContextLen = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + BYTES_SEQ);
  1505. OCP_MEMCPY(PpsCalcHash->sContextInfo.pbContextData, (sApduData.prgbRespBuffer + CALC_HASH_FIXED_OVERHEAD_SIZE), PpsCalcHash->sContextInfo.dwContextLen);
  1506. }
  1507. }while(FALSE);
  1508. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1509. /// @cond hidden
  1510. #undef INDATA_LEN_OID
  1511. #undef NIBBLE_LEN
  1512. #undef OFFSET_EXPORT_CNTXTAG
  1513. #undef TAG_HASH_OUTPUT
  1514. #undef TAG_CONTEXT_OUTPUT
  1515. /// @endcond
  1516. return i4Status;
  1517. }
  1518. /**
  1519. * Verifies the signature over the input digest by using the Security Chip.<br>
  1520. *
  1521. * Input:<br>
  1522. * - For eVerifyDataType
  1523. * - #eDataStream indicates that sPubKeyInput is considered for signature verification.<br>
  1524. * - #eOIDData indicates that wOIDPubKey is considered for signature verification.<br>
  1525. *
  1526. * Output:<br>
  1527. * - Successful signature verification returns #CMD_LIB_OK.<br>
  1528. *
  1529. * Notes: <br>
  1530. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.<br>
  1531. * - 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.
  1532. *
  1533. * \param[in] PpsVerifySign Pointer to information for verifying signature
  1534. * \param[in,out] PpsDigest pointer to a blob which holds the Digest
  1535. * \param[in,out] PpsSignature pointer to a blob which holds the Signature to be verified
  1536. *
  1537. * \retval #CMD_LIB_OK
  1538. * \retval #CMD_LIB_ERROR
  1539. * \retval #CMD_LIB_NULL_PARAM
  1540. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1541. * \retval #CMD_DEV_EXEC_ERROR
  1542. * \retval #CMD_DEV_ERROR
  1543. */
  1544. int32_t CmdLib_VerifySign(const sVerifyOption_d* PpsVerifySign,const sbBlob_d * PpsDigest,const sbBlob_d * PpsSignature)
  1545. {
  1546. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1547. sApduData_d sApduData = {0};
  1548. uint16_t wWritePosition = OFFSET_PAYLOAD;
  1549. uint16_t wCalApduLen = 0;
  1550. /// @cond hidden
  1551. ///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)]
  1552. #define DATA_STREAM_APDU_INDATA_LEN 13
  1553. ///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)]
  1554. #define OID_APDU_INDATA_LEN 11
  1555. /// @endcond
  1556. do
  1557. {
  1558. //NULL checks
  1559. if((NULL == PpsVerifySign) || (NULL == PpsDigest->prgbStream) ||
  1560. (NULL == PpsSignature->prgbStream))
  1561. {
  1562. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1563. break;
  1564. }
  1565. if(eDataStream == PpsVerifySign->eVerifyDataType)
  1566. {
  1567. //NULL checks
  1568. if(NULL == PpsVerifySign->sPubKeyInput.sDataStream.prgbStream)
  1569. {
  1570. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1571. break;
  1572. }
  1573. wCalApduLen = OFFSET_PAYLOAD + DATA_STREAM_APDU_INDATA_LEN + PpsDigest->wLen + PpsSignature->wLen + PpsVerifySign->sPubKeyInput.sDataStream.wLen;
  1574. }
  1575. if(eOIDData == PpsVerifySign->eVerifyDataType)
  1576. {
  1577. wCalApduLen = OFFSET_PAYLOAD + OID_APDU_INDATA_LEN + PpsDigest->wLen + PpsSignature->wLen;
  1578. }
  1579. if((wMaxCommsBuffer) < wCalApduLen)
  1580. {
  1581. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1582. break;
  1583. }
  1584. //Allocating Heap memory
  1585. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1586. //Set the pointer to the response buffer
  1587. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1588. sApduData.wResponseLength = wMaxCommsBuffer;
  1589. //Set digest tag, length, data
  1590. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = TAG_DIGEST;
  1591. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsDigest->wLen);
  1592. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDigest->prgbStream,PpsDigest->wLen);
  1593. wWritePosition += TAG_VALUE_OFFSET+ PpsDigest->wLen;
  1594. //Set signature tag, length, data
  1595. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_SIGNATURE;
  1596. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsSignature->wLen);
  1597. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsSignature->prgbStream,PpsSignature->wLen);
  1598. wWritePosition += TAG_VALUE_OFFSET + PpsSignature->wLen;
  1599. if(eDataStream == PpsVerifySign->eVerifyDataType)
  1600. {
  1601. //Set TLV values for external public key
  1602. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_ALGO_IDENTIFIER;
  1603. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_ALGO_IDENTIFIER);
  1604. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsVerifySign->sPubKeyInput.eAlgId;
  1605. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET + BYTES_SEQ] = (uint8_t)TAG_PUB_KEY;
  1606. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET + BYTES_OFFSET], PpsVerifySign->sPubKeyInput.sDataStream.wLen);
  1607. wWritePosition += TAG_VALUE_OFFSET + BYTES_OFFSET + BYTES_OFFSET;
  1608. OCP_MEMCPY(&sApduData.prgbAPDUBuffer[wWritePosition],PpsVerifySign->sPubKeyInput.sDataStream.prgbStream ,PpsVerifySign->sPubKeyInput.sDataStream.wLen);
  1609. //Total payload length
  1610. sApduData.wPayloadLength = (uint16_t)(wWritePosition + PpsVerifySign->sPubKeyInput.sDataStream.wLen - OFFSET_PAYLOAD);
  1611. }
  1612. if(eOIDData == PpsVerifySign->eVerifyDataType)
  1613. {
  1614. //Set TLV values for public key OID
  1615. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_PUB_KEY_OID;
  1616. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_PUB_KEY);
  1617. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsVerifySign->wOIDPubKey);
  1618. //Total payload length
  1619. sApduData.wPayloadLength = (uint16_t)(wWritePosition + TAG_VALUE_OFFSET + BYTES_OFFSET - OFFSET_PAYLOAD);
  1620. }
  1621. //Form Command
  1622. sApduData.bCmd = CMD_VERIFYSIGN;
  1623. sApduData.bParam = (uint8_t)PpsVerifySign->eSignScheme;
  1624. //Transmit data
  1625. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1626. if(CMD_LIB_OK != i4Status)
  1627. {
  1628. break;
  1629. }
  1630. }while(FALSE);
  1631. //Free the allocated memory for buffer
  1632. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1633. /// @cond hidden
  1634. #undef DATA_STREAM_APDU_INDATA_LEN
  1635. #undef OID_APDU_INDATA_LEN
  1636. /// @endcond
  1637. return i4Status;
  1638. }
  1639. /**
  1640. * Generates a key pair by using the Security Chip.<br>
  1641. *
  1642. * Input:
  1643. * - Provide the required option for exporting the generated keys. Use \ref sKeyPairOption_d.eKeyExport
  1644. * - #eStorePrivKeyOnly indicates that only private key is stored in the OID and public key is exported.
  1645. * - #eExportKeyPair indicates that both public and private keys are exported.
  1646. *
  1647. * Output:
  1648. * - Successful API execution,
  1649. * - Public key is returned in \ref sOutKeyPair_d.sPublicKey.
  1650. * - Private key is returned in \ref sOutKeyPair_d.sPrivateKey , if input is #eExportKeyPair.
  1651. *
  1652. * Notes:
  1653. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1654. * - Values of #eKeyUsage_d can be logically 'ORed' and passed to \ref sKeyPairOption_d.eKeyUsage.
  1655. * - 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.
  1656. *
  1657. * \param[in] PpsKeyPairOption Pointer to #sKeyPairOption_d to provide input for key pair generation
  1658. * \param[in,out] PpsOutKeyPair Pointer to #sOutKeyPair_d that contains generated key pair
  1659. *
  1660. * \retval #CMD_LIB_OK
  1661. * \retval #CMD_LIB_ERROR
  1662. * \retval #CMD_LIB_NULL_PARAM
  1663. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1664. * \retval #CMD_DEV_EXEC_ERROR
  1665. * \retval #CMD_DEV_ERROR
  1666. */
  1667. int32_t CmdLib_GenerateKeyPair(const sKeyPairOption_d* PpsKeyPairOption,sOutKeyPair_d* PpsOutKeyPair)
  1668. {
  1669. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1670. uint16_t wWritePosition = LEN_APDUHEADER;
  1671. uint16_t wCalApduLen;
  1672. uint16_t wLen;
  1673. uint16_t wParsLen;
  1674. uint8_t bMultiplier;
  1675. sApduData_d sApduData = {0};
  1676. uint8_t wAlgoLen;
  1677. sbBlob_d * psBlobKey = NULL;
  1678. /// @cond hidden
  1679. ///Tag for public key
  1680. #define TAG_PUBLIC_KEY 0x02
  1681. ///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)]
  1682. #define PRIV_KEY_APDU_INDATA_LEN 9
  1683. /// Encoding bytes for private and public key
  1684. #define KEY_PAIR_INDATA_LEN 4
  1685. /// @endcond
  1686. do
  1687. {
  1688. //NULL checks
  1689. if((NULL == PpsKeyPairOption) || (NULL == PpsOutKeyPair) || (NULL == PpsOutKeyPair->sPublicKey.prgbStream))
  1690. {
  1691. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1692. break;
  1693. }
  1694. wCalApduLen = LEN_APDUHEADER + PRIV_KEY_APDU_INDATA_LEN;
  1695. bMultiplier = 2;
  1696. if(eExportKeyPair == PpsKeyPairOption->eKeyExport)
  1697. {
  1698. //NULL checks
  1699. if(NULL == PpsOutKeyPair->sPrivateKey.prgbStream)
  1700. {
  1701. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1702. break;
  1703. }
  1704. wCalApduLen = LEN_APDUHEADER + KEY_PAIR_INDATA_LEN + TAG_VALUE_OFFSET + TAG_VALUE_OFFSET;
  1705. bMultiplier = 3;
  1706. }
  1707. //Get key size using algorithm identifier
  1708. i4Status = Get_KeySize(PpsKeyPairOption->eAlgId, &wAlgoLen);
  1709. if(CMD_LIB_OK != i4Status)
  1710. {
  1711. break;
  1712. }
  1713. wCalApduLen += ((wAlgoLen * bMultiplier) + 2);
  1714. //Allocating Heap memory
  1715. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1716. //Set the pointer to the response buffer
  1717. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1718. sApduData.wResponseLength = wCalApduLen;
  1719. if(eStorePrivKeyOnly == PpsKeyPairOption->eKeyExport)
  1720. {
  1721. //Set private key OID tag, length, data
  1722. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  1723. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_PRI_KEY);
  1724. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsKeyPairOption->wOIDPrivKey);
  1725. wWritePosition += TAG_VALUE_OFFSET+ BYTES_OFFSET;
  1726. //Set key usage identifier tag, length, data
  1727. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_KEY_USAGE_IDENTIFIER;
  1728. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_KEY_USAGE_IDENTIFIER);
  1729. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsKeyPairOption->eKeyUsage;
  1730. wWritePosition += TAG_VALUE_OFFSET + BYTES_SEQ;
  1731. }
  1732. if(eExportKeyPair == PpsKeyPairOption->eKeyExport)
  1733. {
  1734. //Set TLV values for extract key pair
  1735. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_KEY_PAIR;
  1736. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_KEY_PAIR);
  1737. wWritePosition += TAG_VALUE_OFFSET;
  1738. }
  1739. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1740. //Form Command
  1741. sApduData.bCmd = CMD_GENERATE_KEY_PAIR;
  1742. sApduData.bParam = (uint8_t)PpsKeyPairOption->eAlgId;
  1743. //Transmit data
  1744. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1745. if(CMD_LIB_OK != i4Status)
  1746. {
  1747. break;
  1748. }
  1749. wParsLen = LEN_APDUHEADER;
  1750. do
  1751. {
  1752. wLen = Utility_GetUint16(&sApduData.prgbRespBuffer[wParsLen+BYTES_SEQ]);
  1753. psBlobKey = (TAG_PUBLIC_KEY == sApduData.prgbRespBuffer[wParsLen])?&(PpsOutKeyPair->sPublicKey):&(PpsOutKeyPair->sPrivateKey);
  1754. if(wLen > psBlobKey->wLen)
  1755. {
  1756. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1757. break;
  1758. }
  1759. //Copy public key to output buffer
  1760. OCP_MEMCPY(psBlobKey->prgbStream,&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wParsLen] ,wLen);
  1761. psBlobKey->wLen = wLen;
  1762. wParsLen += (wLen + TAG_VALUE_OFFSET);
  1763. } while (wParsLen != sApduData.wResponseLength);
  1764. } while(FALSE);
  1765. //Free the allocated memory for buffer
  1766. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1767. /// @cond hidden
  1768. #undef TAG_PUBLIC_KEY
  1769. #undef PRIV_KEY_APDU_INDATA_LEN
  1770. #undef KEY_PAIR_INDATA_LEN
  1771. /// @endcond
  1772. return i4Status;
  1773. }
  1774. /**
  1775. * Calculates signature on a digest by using the Security Chip.<br>
  1776. *
  1777. * Input:
  1778. * - Provide the signature scheme. Use \ref sCalcSignOptions_d.eSignScheme.
  1779. * - Provide the digest to be signed. Use \ref sCalcSignOptions_d.sDigestToSign.
  1780. * - Provide the OID of the private key. Use \ref sCalcSignOptions_d.wOIDSignKey.
  1781. *
  1782. * Output:
  1783. * - Successful API execution,
  1784. * - Signature is returned in PpsSignature.<br>
  1785. *
  1786. * Notes:
  1787. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1788. * - 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.
  1789. * - If the memory buffer in PpsSignature is not sufficient to store the generated signature,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  1790. *
  1791. * \param[in] PpsCalcSign Pointer to #sCalcSignOptions_d to provide input for signature generation
  1792. * \param[in,out] PpsSignature Pointer to #sbBlob_d that contains generated signature
  1793. *
  1794. * \retval #CMD_LIB_OK
  1795. * \retval #CMD_LIB_ERROR
  1796. * \retval #CMD_LIB_NULL_PARAM
  1797. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1798. * \retval #CMD_DEV_EXEC_ERROR
  1799. * \retval #CMD_DEV_ERROR
  1800. */
  1801. int32_t CmdLib_CalculateSign(const sCalcSignOptions_d *PpsCalcSign,sbBlob_d *PpsSignature)
  1802. {
  1803. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1804. uint16_t wWritePosition = LEN_APDUHEADER;
  1805. uint16_t wCalApduLen;
  1806. sApduData_d sApduData = {0};
  1807. do
  1808. {
  1809. //NULL checks
  1810. if((NULL == PpsCalcSign) || (NULL == PpsSignature->prgbStream) || (NULL == PpsCalcSign->sDigestToSign.prgbStream))
  1811. {
  1812. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1813. break;
  1814. }
  1815. /// @cond hidden
  1816. ///Minimum length of APDU InData in case of calculate sign. [TLV Header(3) of OID + OID (2) + TLV Header(3) for digest ]
  1817. #define CALSIGN_APDU_LEN 8
  1818. ///Tag for Signature length
  1819. #define SIGNATURE_LEN 0x77
  1820. ///Total value required while sending the command
  1821. #define TX_LEN (CALSIGN_APDU_LEN + PpsCalcSign->sDigestToSign.wLen)
  1822. /// @endcond
  1823. //Calculate the size of memory to be allocated
  1824. wCalApduLen = LEN_APDUHEADER + (TX_LEN > SIGNATURE_LEN ? TX_LEN : SIGNATURE_LEN);
  1825. if((wMaxCommsBuffer) < wCalApduLen)
  1826. {
  1827. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1828. break;
  1829. }
  1830. //Allocating Heap memory
  1831. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1832. //Set the pointer to the response buffer
  1833. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1834. sApduData.wResponseLength = wCalApduLen;
  1835. //Set digest tag, length, data
  1836. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_DIGEST;
  1837. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], PpsCalcSign->sDigestToSign.wLen);
  1838. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsCalcSign->sDigestToSign.prgbStream,PpsCalcSign->sDigestToSign.wLen);
  1839. wWritePosition += TAG_VALUE_OFFSET + PpsCalcSign->sDigestToSign.wLen;
  1840. //Set OID of signature key tag, length, data
  1841. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_SIG_KEY;
  1842. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_OID_SIG_KEY);
  1843. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsCalcSign->wOIDSignKey);
  1844. wWritePosition += TAG_VALUE_OFFSET + LEN_OID_SIG_KEY;
  1845. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1846. //Form Command
  1847. sApduData.bCmd = CMD_CALC_SIGN;
  1848. sApduData.bParam = (uint8_t)PpsCalcSign->eSignScheme;
  1849. //Transmit data
  1850. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1851. if(CMD_LIB_OK != i4Status)
  1852. {
  1853. break;
  1854. }
  1855. sApduData.wResponseLength -= LEN_APDUHEADER;
  1856. if(sApduData.wResponseLength > PpsSignature->wLen)
  1857. {
  1858. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1859. break;
  1860. }
  1861. //Copy signature to output buffer
  1862. OCP_MEMCPY(PpsSignature->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  1863. PpsSignature->wLen = sApduData.wResponseLength;
  1864. }while(FALSE);
  1865. //Free the allocated memory for buffer
  1866. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  1867. /// @cond hidden
  1868. #undef CALSIGN_APDU_LEN
  1869. #undef SIGNATURE_LEN
  1870. #undef TX_LEN
  1871. /// @endcond
  1872. return i4Status;
  1873. }
  1874. /**
  1875. * Generates a shared secret by using the Security Chip.<br>
  1876. *
  1877. * Input:
  1878. * - Provide the key agreement algorithm for generating shared secret. Use \ref sCalcSSecOptions_d.eKeyAgreementType.
  1879. * - Provide the OID of private key. Use \ref sCalcSSecOptions_d.wOIDPrivKey.
  1880. * - Provide the algorithm identifier of the public key. Use \ref sCalcSSecOptions_d.ePubKeyAlgId.
  1881. * - Provide the public key. Use \ref sCalcSSecOptions_d.sPubKey.
  1882. * - Provide the OID to store the shared secret. Use \ref sCalcSSecOptions_d.wOIDSharedSecret.
  1883. * - 0x0000 indicates that the shared secret is exported.
  1884. *
  1885. * Output:
  1886. * - Successful API execution,
  1887. * - Calculated shared secret is returned in PpsSecret if \ref sCalcSSecOptions_d.wOIDSharedSecret is 0x0000.
  1888. *
  1889. * Notes:
  1890. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  1891. * - 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.
  1892. * - If the memory buffer in PpsSecret is not sufficient to store the calculated secret,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  1893. *
  1894. * \param[in] PpsCalcSSec Pointer to #sCalcSSecOptions_d to provide input for shared secret calculation
  1895. * \param[in,out] PpsSecret Pointer to #sbBlob_d that contains calculated shared secret
  1896. *
  1897. * \retval #CMD_LIB_OK
  1898. * \retval #CMD_LIB_ERROR
  1899. * \retval #CMD_LIB_NULL_PARAM
  1900. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  1901. * \retval #CMD_DEV_EXEC_ERROR
  1902. * \retval #CMD_DEV_ERROR
  1903. */
  1904. int32_t CmdLib_CalculateSharedSecret(const sCalcSSecOptions_d *PpsCalcSSec,sbBlob_d *PpsSecret)
  1905. {
  1906. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  1907. uint16_t wWritePosition = LEN_APDUHEADER;
  1908. uint16_t wCalApduLen = 0;
  1909. sApduData_d sApduData = {0};
  1910. do
  1911. {
  1912. //NULL checks
  1913. if((NULL == PpsCalcSSec) || (NULL == PpsCalcSSec->sPubKey.prgbStream))
  1914. {
  1915. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1916. break;
  1917. }
  1918. /// @cond hidden
  1919. ///Minimum length of APDU InData in case of calculate shared secret.
  1920. ///[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 ]
  1921. #define CALCSSEC_APDU_LEN 15
  1922. ///Tag for public key
  1923. #define TAG_PUBLIC_KEY 0x06
  1924. ///Len for privet key oid
  1925. #define LEN_EXPORT_SHAR_SEC 0x0000
  1926. ///Len for share sec oid
  1927. #define LEN_OID_SHARE_SEC 0x0002
  1928. ///Share sec OID zero value
  1929. #define OID_SHARE_SEC_ZERO 0x0000
  1930. ///Tag for export share secret
  1931. #define TAG_EXPORT_SHARE_SEC 0x07
  1932. ///Tag for share secret oid
  1933. #define TAG_OID_SHARE_SEC 0x08
  1934. ///Minimum length of APDU
  1935. #define TX_LEN (CALCSSEC_APDU_LEN + PpsCalcSSec->sPubKey.wLen + 2)
  1936. /// @endcond
  1937. //Considering the size of Indata for allocating memory as this size is also sufficient for storing the response
  1938. wCalApduLen = LEN_APDUHEADER + TX_LEN;
  1939. //NULL checks
  1940. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  1941. {
  1942. if(NULL == PpsSecret->prgbStream)
  1943. {
  1944. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  1945. break;
  1946. }
  1947. wCalApduLen -=2;
  1948. }
  1949. //Check max comms buffer size
  1950. if((wMaxCommsBuffer) < wCalApduLen)
  1951. {
  1952. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  1953. break;
  1954. }
  1955. //Allocating Heap memory
  1956. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  1957. //Set the pointer to the response buffer
  1958. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  1959. sApduData.wResponseLength = wCalApduLen;
  1960. //Set privet key tag, length, data
  1961. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  1962. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_PRI_KEY);
  1963. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsCalcSSec->wOIDPrivKey);
  1964. wWritePosition += TAG_VALUE_OFFSET + LEN_PRI_KEY;
  1965. //Set public key algoId tag, length, data
  1966. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_ALGO_IDENTIFIER;
  1967. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_ALGO_IDENTIFIER);
  1968. sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET] = (uint8_t)PpsCalcSSec->ePubKeyAlgId;
  1969. wWritePosition += TAG_VALUE_OFFSET + LEN_ALGO_IDENTIFIER;
  1970. //Set public key tag, length, data
  1971. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_PUBLIC_KEY;
  1972. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],PpsCalcSSec->sPubKey.wLen);
  1973. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsCalcSSec->sPubKey.prgbStream,PpsCalcSSec->sPubKey.wLen);
  1974. wWritePosition += TAG_VALUE_OFFSET + PpsCalcSSec->sPubKey.wLen;
  1975. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  1976. {
  1977. //Set export share sec tag, length, data
  1978. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_SHARE_SEC;
  1979. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_SHAR_SEC);
  1980. wWritePosition += TAG_VALUE_OFFSET;
  1981. }
  1982. else
  1983. {
  1984. //Set OID of signature key tag, length, data
  1985. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_SHARE_SEC;
  1986. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_OID_SHARE_SEC);
  1987. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsCalcSSec->wOIDSharedSecret);
  1988. wWritePosition += TAG_VALUE_OFFSET + LEN_OID_SHARE_SEC;
  1989. }
  1990. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  1991. //Form Command
  1992. sApduData.bCmd = CMD_CALC_SHARED_SEC;
  1993. sApduData.bParam = (uint8_t)PpsCalcSSec->eKeyAgreementType;
  1994. //Transmit data
  1995. i4Status = TransceiveAPDU(&sApduData,TRUE);
  1996. if(CMD_LIB_OK != i4Status)
  1997. {
  1998. break;
  1999. }
  2000. sApduData.wResponseLength -= LEN_APDUHEADER;
  2001. if(OID_SHARE_SEC_ZERO == PpsCalcSSec->wOIDSharedSecret)
  2002. {
  2003. if(sApduData.wResponseLength > PpsSecret->wLen)
  2004. {
  2005. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2006. break;
  2007. }
  2008. //Copy signature to output buffer
  2009. OCP_MEMCPY(PpsSecret->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  2010. PpsSecret->wLen = sApduData.wResponseLength;
  2011. }
  2012. }while(FALSE);
  2013. //Free the allocated memory for buffer
  2014. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2015. /// @cond hidden
  2016. #undef CALCSSEC_APDU_LEN
  2017. #undef TAG_PUBLIC_KEY
  2018. #undef LEN_EXPORT_SHAR_SEC
  2019. #undef LEN_OID_SHARE_SEC
  2020. #undef OID_SHARE_SEC_ZERO
  2021. #undef TAG_EXPORT_SHARE_SEC
  2022. #undef TAG_OID_SHARE_SEC
  2023. #undef TX_LEN
  2024. /// @endcond
  2025. return i4Status;
  2026. }
  2027. /**
  2028. * Derives a session key by using the Security Chip.<br>
  2029. *
  2030. * Input:
  2031. * - Provide the key derivation method. Use \ref sDeriveKeyOptions_d.eKDM.
  2032. * - Provide the OID of the shared secret. Use \ref sDeriveKeyOptions_d.wOIDSharedSecret.
  2033. * - Provide the input seed. Use \ref sDeriveKeyOptions_d.sSeed.
  2034. * - Provide the length for derived key. Use \ref sDeriveKeyOptions_d.wDerivedKeyLen.
  2035. * - Provide the OID to store the derived key. Use \ref sDeriveKeyOptions_d.wOIDDerivedKey.
  2036. * - 0x0000 indicates that the derived key is exported.
  2037. *
  2038. * Output:
  2039. * - Successful API execution,
  2040. * - Derived key is returned in PpsKey if \ref sDeriveKeyOptions_d.wOIDDerivedKey is 0x0000.
  2041. *
  2042. * Notes:
  2043. * - Application on security chip must be opened using #CmdLib_OpenApplication before using this API.
  2044. * - 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.
  2045. * - If the memory buffer in PpsKey is not sufficient to store the derived key,#CMD_LIB_INSUFFICIENT_MEMORY is returned.
  2046. *
  2047. * \param[in] PpsDeriveKey Pointer to #sDeriveKeyOptions_d to provide input for session key generation
  2048. * \param[in,out] PpsKey Pointer to #sbBlob_d that contains the derived key
  2049. *
  2050. * \retval #CMD_LIB_OK
  2051. * \retval #CMD_LIB_ERROR
  2052. * \retval #CMD_LIB_NULL_PARAM
  2053. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2054. * \retval #CMD_DEV_EXEC_ERROR
  2055. * \retval #CMD_DEV_ERROR
  2056. */
  2057. int32_t CmdLib_DeriveKey(const sDeriveKeyOptions_d *PpsDeriveKey,sbBlob_d *PpsKey)
  2058. {
  2059. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2060. uint16_t wWritePosition = LEN_APDUHEADER;
  2061. uint16_t wCalApduLen = 0;
  2062. sApduData_d sApduData = {0};
  2063. do
  2064. {
  2065. //NULL checks
  2066. if((NULL == PpsDeriveKey) || (NULL == PpsDeriveKey->sSeed.prgbStream))
  2067. {
  2068. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2069. break;
  2070. }
  2071. /// @cond hidden
  2072. ///Minimum length of APDU InData in case of calculate shared secret.
  2073. ///[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 ]
  2074. #define DERIVEKEY_APDU_LEN 16
  2075. ///Tag for derive key
  2076. #define TAG_DERIVE_KEY 0x03
  2077. ///Len for export derive key
  2078. #define LEN_EXPORT_DERIVE_KEY 0x0000
  2079. ///Len for share sec oid
  2080. #define LEN_DERIVE_KEY 0x0002
  2081. ///Derive key OID zero value
  2082. #define OID_DERIVE_SEC_ZERO 0x0000
  2083. ///Tag for export derive share secret
  2084. #define TAG_EXPORT_DERIVE_KEY 0x07
  2085. ///Tag for derive key oid
  2086. #define TAG_OID_DERIVE_KEY 0x08
  2087. ///Minimum length of APDU
  2088. #define TX_LEN (DERIVEKEY_APDU_LEN + 2)
  2089. /// @endcond
  2090. //Considering the size of Indata for allocating memory as this size is also sufficient for storing the response
  2091. wCalApduLen = LEN_APDUHEADER + TX_LEN + (PpsDeriveKey->sSeed.wLen > PpsDeriveKey->wDerivedKeyLen ? PpsDeriveKey->sSeed.wLen : PpsDeriveKey->wDerivedKeyLen);
  2092. //NULL checks
  2093. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2094. {
  2095. if(NULL == PpsKey->prgbStream)
  2096. {
  2097. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2098. break;
  2099. }
  2100. wCalApduLen -= 2;
  2101. }
  2102. //Check max comms buffer size
  2103. if((wMaxCommsBuffer) < wCalApduLen)
  2104. {
  2105. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2106. break;
  2107. }
  2108. //Allocating Heap memory
  2109. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,wCalApduLen);
  2110. //Set the pointer to the response buffer
  2111. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2112. sApduData.wResponseLength = wCalApduLen;
  2113. //Set share secret key tag, length, data
  2114. sApduData.prgbAPDUBuffer[LEN_APDUHEADER] = TAG_OID;
  2115. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_SHARED_SECRET_OID);
  2116. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDeriveKey->wOIDSharedSecret);
  2117. wWritePosition += TAG_VALUE_OFFSET + LEN_PRI_KEY;
  2118. //Set public key algoId tag, length, data
  2119. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_SEED;
  2120. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],PpsDeriveKey->sSeed.wLen);
  2121. OCP_MEMCPY(&sApduData.prgbRespBuffer[TAG_VALUE_OFFSET + wWritePosition],PpsDeriveKey->sSeed.prgbStream,PpsDeriveKey->sSeed.wLen);
  2122. wWritePosition += TAG_VALUE_OFFSET + PpsDeriveKey->sSeed.wLen;
  2123. //Set public key tag, length, data
  2124. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_DERIVE_KEY;
  2125. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET],LEN_DERIVE_KEY);
  2126. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET],PpsDeriveKey->wDerivedKeyLen);
  2127. wWritePosition += TAG_VALUE_OFFSET + LEN_DERIVE_KEY;
  2128. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2129. {
  2130. //Set export share sec tag, length, data
  2131. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_EXPORT_DERIVE_KEY;
  2132. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_EXPORT_DERIVE_KEY);
  2133. wWritePosition += TAG_VALUE_OFFSET;
  2134. }
  2135. else
  2136. {
  2137. //Set OID of signature key tag, length, data
  2138. sApduData.prgbAPDUBuffer[wWritePosition] = TAG_OID_DERIVE_KEY;
  2139. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_LENGTH_OFFSET], LEN_DERIVE_KEY);
  2140. Utility_SetUint16(&sApduData.prgbAPDUBuffer[wWritePosition + TAG_VALUE_OFFSET], PpsDeriveKey->wOIDDerivedKey);
  2141. wWritePosition += TAG_VALUE_OFFSET + LEN_DERIVE_KEY;
  2142. }
  2143. sApduData.wPayloadLength = (uint16_t)(wWritePosition - LEN_APDUHEADER);
  2144. //Form Command
  2145. sApduData.bCmd = CMD_DERIVE_KEY;
  2146. sApduData.bParam = (uint8_t)PpsDeriveKey->eKDM;
  2147. //Transmit data
  2148. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2149. if(CMD_LIB_OK != i4Status)
  2150. {
  2151. break;
  2152. }
  2153. sApduData.wResponseLength -= LEN_APDUHEADER;
  2154. if(OID_DERIVE_SEC_ZERO == PpsDeriveKey->wOIDDerivedKey)
  2155. {
  2156. if(sApduData.wResponseLength > PpsKey->wLen)
  2157. {
  2158. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2159. break;
  2160. }
  2161. //Copy signature to output buffer
  2162. OCP_MEMCPY(PpsKey->prgbStream,&sApduData.prgbRespBuffer[LEN_APDUHEADER],sApduData.wResponseLength);
  2163. PpsKey->wLen = sApduData.wResponseLength;
  2164. }
  2165. }while(FALSE);
  2166. //Free the allocated memory for buffer
  2167. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2168. /// @cond hidden
  2169. #undef DERIVEKEY_APDU_LEN
  2170. #undef TAG_DERIVE_KEY
  2171. #undef LEN_EXPORT_DERIVE_KEY
  2172. #undef LEN_DERIVE_KEY
  2173. #undef OID_DERIVE_SEC_ZERO
  2174. #undef TAG_EXPORT_DERIVE_KEY
  2175. #undef TAG_OID_DERIVE_KEY
  2176. #undef TX_LEN
  2177. /// @endcond
  2178. return i4Status;
  2179. }
  2180. #endif/*MODULE_ENABLE_TOOLBOX*/
  2181. #ifdef MODULE_ENABLE_DTLS_MUTUAL_AUTH
  2182. /**
  2183. * Gets Handshake message from Security Chip.<br>
  2184. *
  2185. *
  2186. * Notes: <br>
  2187. * - User should provide a callback through #sCallBack_d.
  2188. * - This callback allows the caller to allocate memory for the message and keep copying data into the memory in case of lengthy messages.
  2189. * - Allocated buffer is returned to user in #sCBGetMsg_d.
  2190. * - The callback should return #CMD_LIB_OK for successful allocation of memory else #CMD_LIB_ERROR in case of error.<br>
  2191. *
  2192. * - Any Message specific data must be provided by the user in the union puMsgParams.<br>
  2193. * The union is defined as #uMsgParams_d.
  2194. *
  2195. * - The user must provide correct data in puMsgParams.This function does not <br>
  2196. * validate the content of the message specific data.
  2197. * E.g For sending gmt_unix_time for Client Hello message,uMsgParams_d.sMsgParamCH_d.dwUnixTime must be set.
  2198. * If puMsgParams is set to NULL,then random dwUnixTime will be considered for Client Hello message <br>
  2199. * and certificate will not be send for Client Certificate message.
  2200. *
  2201. * The psBlobInBuffer pointer which is member of sProcMsgData_d should be set to NULL
  2202. *
  2203. * \param[in,out] PpsGMsgVector Pointer to DTLS Handshake Message parameters
  2204. *
  2205. * \retval #CMD_LIB_OK
  2206. * \retval #CMD_LIB_ERROR
  2207. * \retval #CMD_LIB_INVALID_PARAM
  2208. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2209. * \retval #CMD_DEV_ERROR
  2210. * \retval #CMD_LIB_NULL_PARAM
  2211. */
  2212. int32_t CmdLib_GetMessage(const sProcMsgData_d *PpsGMsgVector)
  2213. {
  2214. ///@cond hidden
  2215. #define STACK_ALLOC
  2216. ///@endcond
  2217. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2218. sApduData_d sApduData;
  2219. uint8_t bFragSeq ;
  2220. uint16_t wRespLen;
  2221. sbBlob_d sBlobMessage;
  2222. do
  2223. {
  2224. //To use stack memory for APDU buffer, define STACK_ALLOC locally else heap memory is used
  2225. #ifdef STACK_ALLOC
  2226. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,MAX_APDU_BUFF_LEN);
  2227. #else
  2228. INIT_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer,MAX_APDU_BUFF_LEN);
  2229. #endif
  2230. //NULL checks
  2231. if((NULL == PpsGMsgVector) || (NULL == PpsGMsgVector->psCallBack) ||
  2232. (NULL == PpsGMsgVector->psCallBack->pfAcceptMessage) || (NULL == PpsGMsgVector->psCallBack->fvParams))
  2233. {
  2234. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2235. break;
  2236. }
  2237. //Verify the range of the param
  2238. if((eClientHello != PpsGMsgVector->eParam) && (eClientHelloWithCookie != PpsGMsgVector->eParam) &&
  2239. (eClientCertificate != PpsGMsgVector->eParam) && (eClientKeyExchange != PpsGMsgVector->eParam) &&
  2240. (eCertificateVerify != PpsGMsgVector->eParam) && (eClientFinished != PpsGMsgVector->eParam))
  2241. {
  2242. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  2243. break;
  2244. }
  2245. //Verify the Session OID reference
  2246. if((SESSION_ID_LOWER_VALUE > PpsGMsgVector->wSessionKeyOID) ||
  2247. (SESSION_ID_HIGHER_VALUE < PpsGMsgVector->wSessionKeyOID))
  2248. {
  2249. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2250. break;
  2251. }
  2252. //Set the fragment sequence to start
  2253. bFragSeq = (uint8_t)eStart;
  2254. //Set the pointer to the response buffer
  2255. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2256. while((eFragSeq_d)bFragSeq != eFinal)
  2257. {
  2258. //Form data and assign to apdu structure
  2259. //Assign cmd,param,length
  2260. sApduData.bCmd = CMD_GETMSG;
  2261. sApduData.bParam = (uint8_t)PpsGMsgVector->eParam;
  2262. //Total payload length is Session ID Length
  2263. sApduData.wPayloadLength = BYTES_SESSIONID;
  2264. //Form the data in order in the buffer
  2265. //Add the session ID to the buffer
  2266. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsGMsgVector->wSessionKeyOID >> BITS_PER_BYTE);
  2267. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsGMsgVector->wSessionKeyOID;
  2268. sApduData.wResponseLength = MAX_APDU_BUFF_LEN;
  2269. if(((uint8_t)eClientHello == sApduData.bParam) && (NULL != PpsGMsgVector->puMsgParams))
  2270. {
  2271. sApduData.wPayloadLength += LEN_TAG_ENCODING + BYTES_GMT_TIME;
  2272. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_GMTUNIX_TIME;
  2273. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = 0x00;
  2274. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = BYTES_GMT_TIME;
  2275. Utility_SetUint32 (&sApduData.prgbAPDUBuffer[OFFSET_TAG_DATA],PpsGMsgVector->puMsgParams->sMsgParamCH_d.dwUnixTime);
  2276. }
  2277. else if(((uint8_t)eClientCertificate == sApduData.bParam) && (NULL != PpsGMsgVector->puMsgParams))
  2278. {
  2279. sApduData.wPayloadLength += LEN_TAG_ENCODING + BYTES_OID;
  2280. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_CERTIFICATE_OID;
  2281. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = 0x00;
  2282. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = BYTES_OID;
  2283. Utility_SetUint16 (&sApduData.prgbAPDUBuffer[OFFSET_TAG_DATA],PpsGMsgVector->puMsgParams->sMsgParamCert_d.wCertOID);
  2284. }
  2285. //Transmit data
  2286. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2287. if(CMD_LIB_OK != i4Status)
  2288. {
  2289. break;
  2290. }
  2291. //Remove 4 byte apdu header + tag encoding
  2292. sApduData.wResponseLength -= (LEN_APDUHEADER + LEN_TAG_ENCODING);
  2293. //Verify the TLV encoding
  2294. //Verify the Tag
  2295. if(TAG_UNPROTECTED != (*(sApduData.prgbRespBuffer + LEN_APDUHEADER) & MASK_HIGHER_NIBBLE))
  2296. {
  2297. i4Status = (int32_t)CMD_LIB_INVALID_TAG;
  2298. break;
  2299. }
  2300. //Extract the fragment sequence information
  2301. bFragSeq = *(sApduData.prgbRespBuffer + LEN_APDUHEADER) & MASK_LOWER_NIBBLE;
  2302. //extract the tag length field
  2303. wRespLen = Utility_GetUint16(sApduData.prgbRespBuffer + LEN_APDUHEADER + 1);
  2304. //Length validation for response length with the tag length
  2305. if(sApduData.wResponseLength != wRespLen)
  2306. {
  2307. i4Status = (int32_t)CMD_LIB_INVALID_TAGLEN;
  2308. break;
  2309. }
  2310. //Assign the handshake message pointer to the sblob
  2311. sBlobMessage.prgbStream = sApduData.prgbRespBuffer + LEN_APDUHEADER + LEN_TAG_ENCODING;
  2312. //Assign the response length(only Handshake message) excluding the tag encoding
  2313. sBlobMessage.wLen = sApduData.wResponseLength;
  2314. //Call back function to allocate the memory for handshake message based the response length
  2315. i4Status = PpsGMsgVector->psCallBack->pfAcceptMessage(PpsGMsgVector->psCallBack->fvParams, &sBlobMessage);
  2316. if(i4Status != CMD_LIB_OK)
  2317. {
  2318. i4Status = (int32_t)CMD_LIB_ERROR;
  2319. break;
  2320. }
  2321. }
  2322. //Note: If data is encoded with eContinue then loop to get complete data till eFinal is encoded
  2323. //The response pointer should be updated for each loop and check for buffer overflow
  2324. }while(FALSE);
  2325. //Free the allocated memory for buffer
  2326. #ifndef STACK_ALLOC
  2327. FREE_HEAP_APDUBUFFER(sApduData.prgbAPDUBuffer);
  2328. #else
  2329. #undef STACK_ALLOC
  2330. #endif
  2331. return i4Status;
  2332. }
  2333. /**
  2334. * Sends Handshake message to Security Chip for processing.<br>
  2335. *
  2336. *
  2337. * Notes: <br>
  2338. * - Input buffer must be provided by the user.<br>
  2339. * - Clearing of the buffers is the responsibility of the user.
  2340. *
  2341. * - The input pointer should contain sufficient memory to accommodate <br>
  2342. * APDU header and data formatting.
  2343. *
  2344. * - The API will not recopy the Authentication message data but add the header and data<br>
  2345. * formatting information before it, in the same input buffer.
  2346. *
  2347. * The puMsgParams and psCallBack pointer which is member of sProcMsgData_d should be set to NULL
  2348. *
  2349. * \param[in] PpsPMsgVector Pointer to DTLS Handshake Message parameters
  2350. *
  2351. * \retval #CMD_LIB_OK
  2352. * \retval #CMD_LIB_ERROR
  2353. * \retval #CMD_LIB_INVALID_PARAM
  2354. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2355. * \retval #CMD_DEV_ERROR
  2356. * \retval #CMD_LIB_NULL_PARAM
  2357. */
  2358. int32_t CmdLib_PutMessage(const sProcMsgData_d *PpsPMsgVector)
  2359. {
  2360. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2361. sApduData_d sApduData;
  2362. do
  2363. {
  2364. //NULL checks
  2365. if((NULL == PpsPMsgVector) || (NULL == PpsPMsgVector->psBlobInBuffer) ||
  2366. (NULL == PpsPMsgVector->psBlobInBuffer->prgbStream))
  2367. {
  2368. i4Status = (int32_t)CMD_LIB_NULL_PARAM;
  2369. break;
  2370. }
  2371. //Zero length checks
  2372. if(0x00 == PpsPMsgVector->psBlobInBuffer->wLen)
  2373. {
  2374. i4Status = (int32_t)CMD_LIB_LENZERO_ERROR;
  2375. break;
  2376. }
  2377. //Verify the range of the param
  2378. if(((eServerCertificate > PpsPMsgVector->eParam) || (eServerHelloDone < PpsPMsgVector->eParam)) &&
  2379. ((eServerHello != PpsPMsgVector->eParam) && (eHelloVerifyRequest != PpsPMsgVector->eParam) &&
  2380. (eServerFinished != PpsPMsgVector->eParam)))
  2381. {
  2382. i4Status = (int32_t)CMD_LIB_INVALID_PARAM;
  2383. break;
  2384. }
  2385. //Verify the Session OID reference
  2386. if((SESSION_ID_LOWER_VALUE > PpsPMsgVector->wSessionKeyOID) ||
  2387. (SESSION_ID_HIGHER_VALUE < PpsPMsgVector->wSessionKeyOID))
  2388. {
  2389. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2390. break;
  2391. }
  2392. //Length of data + OverHeadLen should not to be more than wMaxCommsBuffer
  2393. //Currently, chaining is not supported by Command library and security chip.Hence, this length check is performed.
  2394. if(PpsPMsgVector->psBlobInBuffer->wLen > (wMaxCommsBuffer) )
  2395. {
  2396. i4Status = (int32_t)CMD_LIB_INSUFFICIENT_MEMORY;
  2397. break;
  2398. }
  2399. //Assign In memory pointer to the APDU Buffer in the Apdu structure
  2400. sApduData.prgbAPDUBuffer = PpsPMsgVector->psBlobInBuffer->prgbStream;
  2401. //Set the pointer to the response buffer
  2402. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2403. //Form data and assign to apdu structure
  2404. //Assign cmd,param,length
  2405. sApduData.bCmd = CMD_PUTMSG;
  2406. sApduData.bParam = (uint8_t)PpsPMsgVector->eParam;
  2407. //Total payload length is sum of length of Session ID , Tag, Tag length and the data
  2408. sApduData.wPayloadLength = PpsPMsgVector->psBlobInBuffer->wLen - OFFSET_PAYLOAD;
  2409. //Add the session ID to the buffer
  2410. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)(PpsPMsgVector->wSessionKeyOID >> BITS_PER_BYTE);
  2411. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PpsPMsgVector->wSessionKeyOID;
  2412. //Add the encoding tag to the buffer
  2413. sApduData.prgbAPDUBuffer[OFFSET_TAG] = TAG_UNPROTECTED;
  2414. sApduData.prgbAPDUBuffer[OFFSET_TAG] |= (uint8_t)eFinal;
  2415. //Add the tag length to the buffer
  2416. //lint --e{702} suppress "Acknowledging the shift. Reviewed it"
  2417. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN] = (uint8_t)(((PpsPMsgVector->psBlobInBuffer->wLen) - (OFFSET_PAYLOAD + BYTES_SESSIONID + LEN_TAG_ENCODING)) >> BITS_PER_BYTE);
  2418. sApduData.prgbAPDUBuffer[OFFSET_TAG_LEN + 1] = (uint8_t)(PpsPMsgVector->psBlobInBuffer->wLen - (OFFSET_PAYLOAD + BYTES_SESSIONID + LEN_TAG_ENCODING));
  2419. sApduData.wResponseLength = PpsPMsgVector->psBlobInBuffer->wLen;
  2420. //Transmit data
  2421. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2422. if(CMD_LIB_OK != i4Status)
  2423. {
  2424. break;
  2425. }
  2426. }while(FALSE);
  2427. return i4Status;
  2428. }
  2429. /**
  2430. *
  2431. * Closes the DTLS session as indicated by the Session OID.<br>
  2432. *
  2433. *
  2434. * \param[in] PwSessionRefId session OID to be closed
  2435. *
  2436. * \retval #CMD_LIB_OK
  2437. * \retval #CMD_LIB_ERROR
  2438. * \retval #CMD_LIB_INVALID_SESSIONID
  2439. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2440. */
  2441. int32_t CmdLib_CloseSession(uint16_t PwSessionRefId)
  2442. {
  2443. /// @cond hidden
  2444. #define CLOSE_SESSION_APDU_BUF_LEN 6
  2445. /// @endcond
  2446. int32_t i4Status = (int32_t)CMD_LIB_ERROR;
  2447. sApduData_d sApduData;
  2448. do
  2449. {
  2450. INIT_STACK_APDUBUFFER(sApduData.prgbAPDUBuffer,CLOSE_SESSION_APDU_BUF_LEN);
  2451. //Verify the session id
  2452. if((SESSION_ID_LOWER_VALUE > PwSessionRefId) ||
  2453. (SESSION_ID_HIGHER_VALUE < PwSessionRefId))
  2454. {
  2455. i4Status = (int32_t)CMD_LIB_INVALID_SESSIONID;
  2456. break;
  2457. }
  2458. //Set the pointer to the response buffer
  2459. sApduData.prgbRespBuffer = sApduData.prgbAPDUBuffer;
  2460. //Form the command
  2461. //Assign Cmd,param,payload length
  2462. sApduData.bCmd = CMD_GETMSG;
  2463. sApduData.bParam = (uint8_t)eCloseSession;
  2464. //Total payload length is equal to session ID length
  2465. sApduData.wPayloadLength = BYTES_SESSIONID;
  2466. //Assign the session key
  2467. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD] = (uint8_t)( PwSessionRefId >> BITS_PER_BYTE);
  2468. sApduData.prgbAPDUBuffer[OFFSET_PAYLOAD + 1] = (uint8_t)PwSessionRefId;
  2469. sApduData.wResponseLength = CLOSE_SESSION_APDU_BUF_LEN;
  2470. //Transmit the Data
  2471. i4Status = TransceiveAPDU(&sApduData,TRUE);
  2472. if(CMD_LIB_OK != i4Status)
  2473. {
  2474. break;
  2475. }
  2476. }while(FALSE);
  2477. /// @cond hidden
  2478. #undef CLOSE_SESSION_APDU_BUF_LEN
  2479. /// @endcond
  2480. return i4Status;
  2481. }
  2482. /**
  2483. * Encrypts data by issuing ProcUpLink command to Security Chip.<br>
  2484. *
  2485. *
  2486. * Notes: <br>
  2487. * - Input and Output buffers must be provided by the user.
  2488. *Buffer deallocation is the responsibility of the user.<br>
  2489. *
  2490. * - The input data in #sbBlob_d sInData should contain sufficient memory to accommodate APDU header,
  2491. *data formatting,Plaintext.<br>
  2492. *The Plaintext and any specific data for encryption should start after an overhead of #OVERHEAD_UPDOWNLINK.<br>
  2493. *
  2494. * - wInDataLength in #sProcCryptoData_d should be greater than zero.<br>
  2495. *
  2496. * - Ciphertext is returned in #sCmdResponse_d* sOutData from zero offset.<br>
  2497. *
  2498. * - In addition to the Ciphertext, the length of buffer in sOutData
  2499. *should be sufficient to accommodate Response APDU header and data formatting. This is defined as #OVERHEAD_ENCDEC_RESPONSE<br>
  2500. *The total length of the Ciphertext is returned in wRespLength of #sCmdResponse_d.<br>
  2501. *
  2502. * - The current implementation of Security chip does not support command chaining.
  2503. *The maximum value of wInDataLength depends on the value supported by the security chip.<br>
  2504. *
  2505. * - Currently,the security chip supports only 0xE100 as session key OID.
  2506. *
  2507. * \param[in,out] PpsEncVector Pointer to structure containing Plaintext and Ciphertext
  2508. *
  2509. * \retval #CMD_LIB_OK
  2510. * \retval #CMD_LIB_ERROR
  2511. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2512. * \retval #CMD_LIB_INVALID_SESSIONID
  2513. * \retval #CMD_LIB_INVALID_LEN
  2514. * \retval #CMD_DEV_ERROR
  2515. * \retval #CMD_LIB_NULL_PARAM
  2516. */
  2517. int32_t CmdLib_Encrypt(sProcCryptoData_d *PpsEncVector)
  2518. {
  2519. return CmdLib_EncDecHelper(PpsEncVector,CMD_ENCDATA,PARAM_ENC_DATA);
  2520. }
  2521. /**
  2522. * Decrypts data by issuing ProcDownLink command to Security Chip.<br>
  2523. *
  2524. *
  2525. * Notes: <br>
  2526. * - Input and Output buffers must be provided by the user.
  2527. *Buffer deallocation is the responsibility of the user.<br>
  2528. *
  2529. * - The input data in #sbBlob_d sInData should contain sufficient memory to accommodate APDU header,
  2530. *data formatting,Ciphertext.<br>
  2531. *The Ciphertext and any specific data for decryption should start after an overhead of #OVERHEAD_UPDOWNLINK.<br>
  2532. *
  2533. * - wInDataLength in #sProcCryptoData_d should be greater than zero.<br>
  2534. *
  2535. * - Plaintext is returned in #sCmdResponse_d* sOutData from zero offset.<br>
  2536. *
  2537. * - In addition to the Plaintext, the length of buffer in sOutData
  2538. *should be sufficient to accommodate Response APDU header and data formatting. This is defined as #OVERHEAD_ENCDEC_RESPONSE<br>
  2539. *The total length of the Plaintext is returned in wRespLength of #sCmdResponse_d.<br>
  2540. *
  2541. * - The current implementation of Security chip does not support command chaining.
  2542. *The maximum value of wInDataLength depends on the value supported by the security chip.<br>
  2543. *
  2544. * - Currently,the security chip supports only 0xE100 as session key OID.
  2545. *
  2546. * \param[in,out] PpsDecVector Pointer to structure containing Ciphertext and Plaintext
  2547. *
  2548. * \retval #CMD_LIB_OK
  2549. * \retval #CMD_LIB_ERROR
  2550. * \retval #CMD_LIB_INSUFFICIENT_MEMORY
  2551. * \retval #CMD_LIB_INVALID_SESSIONID
  2552. * \retval #CMD_LIB_INVALID_LEN
  2553. * \retval #CMD_DEV_ERROR
  2554. * \retval #CMD_LIB_DECRYPT_FAILURE
  2555. * \retval #CMD_LIB_NULL_PARAM
  2556. */
  2557. int32_t CmdLib_Decrypt(sProcCryptoData_d *PpsDecVector)
  2558. {
  2559. return CmdLib_EncDecHelper(PpsDecVector,CMD_DECDATA,PARAM_DEC_DATA);
  2560. }
  2561. #endif /* MODULE_ENABLE_DTLS_MUTUAL_AUTH*/
  2562. /**
  2563. * @}
  2564. */