ua_securitypolicy_basic128rsa15.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2018 (c) Mark Giraud, Fraunhofer IOSB
  6. */
  7. #include <mbedtls/aes.h>
  8. #include <mbedtls/md.h>
  9. #include <mbedtls/sha1.h>
  10. #include <mbedtls/x509_crt.h>
  11. #include <mbedtls/ctr_drbg.h>
  12. #include <mbedtls/entropy.h>
  13. #include <mbedtls/entropy_poll.h>
  14. #include <mbedtls/error.h>
  15. #include <ua_plugin_pki.h>
  16. #include "ua_securitypolicy_basic128rsa15.h"
  17. #include "ua_types.h"
  18. #include "ua_types_generated_handling.h"
  19. /* Notes:
  20. * mbedTLS' AES allows in-place encryption and decryption. Sow we don't have to
  21. * allocate temp buffers.
  22. * https://tls.mbed.org/discussions/generic/in-place-decryption-with-aes256-same-input-output-buffer
  23. */
  24. #define UA_SECURITYPOLICY_BASIC128RSA15_RSAPADDING_LEN 11
  25. #define UA_SHA1_LENGTH 20
  26. #define UA_SECURITYPOLICY_BASIC128RSA15_SYM_KEY_LENGTH 16
  27. #define UA_SECURITYPOLICY_BASIC128RSA15_MINASYMKEYLENGTH 128
  28. #define UA_SECURITYPOLICY_BASIC128RSA15_MAXASYMKEYLENGTH 256
  29. #define UA_LOG_MBEDERR \
  30. char errBuff[300]; \
  31. mbedtls_strerror(mbedErr, errBuff, 300); \
  32. UA_LOG_WARNING(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY, \
  33. "mbedTLS returned an error: %s", errBuff); \
  34. #define UA_MBEDTLS_ERRORHANDLING(errorcode) \
  35. if(mbedErr) { \
  36. UA_LOG_MBEDERR \
  37. retval = errorcode; \
  38. }
  39. #define UA_MBEDTLS_ERRORHANDLING_RETURN(errorcode) \
  40. if(mbedErr) { \
  41. UA_LOG_MBEDERR \
  42. return errorcode; \
  43. }
  44. typedef struct {
  45. const UA_SecurityPolicy *securityPolicy;
  46. UA_ByteString localCertThumbprint;
  47. mbedtls_ctr_drbg_context drbgContext;
  48. mbedtls_entropy_context entropyContext;
  49. mbedtls_md_context_t sha1MdContext;
  50. mbedtls_pk_context localPrivateKey;
  51. } Basic128Rsa15_PolicyContext;
  52. typedef struct {
  53. Basic128Rsa15_PolicyContext *policyContext;
  54. UA_ByteString localSymSigningKey;
  55. UA_ByteString localSymEncryptingKey;
  56. UA_ByteString localSymIv;
  57. UA_ByteString remoteSymSigningKey;
  58. UA_ByteString remoteSymEncryptingKey;
  59. UA_ByteString remoteSymIv;
  60. mbedtls_x509_crt remoteCertificate;
  61. } Basic128Rsa15_ChannelContext;
  62. /********************/
  63. /* AsymmetricModule */
  64. /********************/
  65. static UA_StatusCode
  66. asym_verify_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  67. Basic128Rsa15_ChannelContext *cc,
  68. const UA_ByteString *message,
  69. const UA_ByteString *signature) {
  70. if(securityPolicy == NULL || message == NULL || signature == NULL || cc == NULL)
  71. return UA_STATUSCODE_BADINTERNALERROR;
  72. /* Compute the sha1 hash */
  73. unsigned char hash[UA_SHA1_LENGTH];
  74. mbedtls_sha1(message->data, message->length, hash);
  75. /* Set the RSA settings */
  76. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  77. mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, 0);
  78. /* Verify */
  79. int mbedErr = mbedtls_pk_verify(&cc->remoteCertificate.pk,
  80. MBEDTLS_MD_SHA1, hash, UA_SHA1_LENGTH,
  81. signature->data, signature->length);
  82. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  83. return UA_STATUSCODE_GOOD;
  84. }
  85. static UA_StatusCode
  86. asym_sign_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  87. Basic128Rsa15_ChannelContext *cc,
  88. const UA_ByteString *message,
  89. UA_ByteString *signature) {
  90. if(securityPolicy == NULL || message == NULL || signature == NULL || cc == NULL)
  91. return UA_STATUSCODE_BADINTERNALERROR;
  92. unsigned char hash[UA_SHA1_LENGTH];
  93. mbedtls_sha1(message->data, message->length, hash);
  94. Basic128Rsa15_PolicyContext *pc = cc->policyContext;
  95. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(pc->localPrivateKey);
  96. mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, 0);
  97. size_t sigLen = 0;
  98. int mbedErr = mbedtls_pk_sign(&pc->localPrivateKey,
  99. MBEDTLS_MD_SHA1, hash,
  100. UA_SHA1_LENGTH, signature->data,
  101. &sigLen, mbedtls_ctr_drbg_random,
  102. &pc->drbgContext);
  103. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADINTERNALERROR);
  104. return UA_STATUSCODE_GOOD;
  105. }
  106. static size_t
  107. asym_getLocalSignatureSize_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  108. const Basic128Rsa15_ChannelContext *cc) {
  109. if(securityPolicy == NULL || cc == NULL)
  110. return 0;
  111. return mbedtls_pk_rsa(cc->policyContext->localPrivateKey)->len;
  112. }
  113. static size_t
  114. asym_getRemoteSignatureSize_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  115. const Basic128Rsa15_ChannelContext *cc) {
  116. if(securityPolicy == NULL || cc == NULL)
  117. return 0;
  118. return mbedtls_pk_rsa(cc->remoteCertificate.pk)->len;
  119. }
  120. static UA_StatusCode
  121. asym_encrypt_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  122. Basic128Rsa15_ChannelContext *cc,
  123. UA_ByteString *data) {
  124. if(securityPolicy == NULL || cc == NULL || data == NULL)
  125. return UA_STATUSCODE_BADINTERNALERROR;
  126. const size_t plainTextBlockSize = securityPolicy->channelModule.
  127. getRemoteAsymPlainTextBlockSize(cc);
  128. if(data->length % plainTextBlockSize != 0)
  129. return UA_STATUSCODE_BADINTERNALERROR;
  130. mbedtls_rsa_context *remoteRsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  131. mbedtls_rsa_set_padding(remoteRsaContext, MBEDTLS_RSA_PKCS_V15, 0);
  132. UA_ByteString encrypted;
  133. const size_t bufferOverhead = securityPolicy->channelModule.
  134. getRemoteAsymEncryptionBufferLengthOverhead(cc, data->length);
  135. UA_StatusCode retval = UA_ByteString_allocBuffer(&encrypted, data->length + bufferOverhead);
  136. if(retval != UA_STATUSCODE_GOOD)
  137. return retval;
  138. size_t lenDataToEncrypt = data->length;
  139. size_t inOffset = 0;
  140. size_t offset = 0;
  141. size_t outLength = 0;
  142. Basic128Rsa15_PolicyContext *pc = cc->policyContext;
  143. while(lenDataToEncrypt >= plainTextBlockSize) {
  144. int mbedErr = mbedtls_pk_encrypt(&cc->remoteCertificate.pk,
  145. data->data + inOffset, plainTextBlockSize,
  146. encrypted.data + offset, &outLength,
  147. encrypted.length - offset,
  148. mbedtls_ctr_drbg_random,
  149. &pc->drbgContext);
  150. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADINTERNALERROR);
  151. if(retval != UA_STATUSCODE_GOOD) {
  152. UA_ByteString_deleteMembers(&encrypted);
  153. return retval;
  154. }
  155. inOffset += plainTextBlockSize;
  156. offset += outLength;
  157. lenDataToEncrypt -= plainTextBlockSize;
  158. }
  159. memcpy(data->data, encrypted.data, offset);
  160. UA_ByteString_deleteMembers(&encrypted);
  161. return UA_STATUSCODE_GOOD;
  162. }
  163. static UA_StatusCode
  164. asym_decrypt_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  165. Basic128Rsa15_ChannelContext *cc,
  166. UA_ByteString *data) {
  167. if(securityPolicy == NULL || cc == NULL || data == NULL)
  168. return UA_STATUSCODE_BADINTERNALERROR;
  169. mbedtls_rsa_context *rsaContext =
  170. mbedtls_pk_rsa(cc->policyContext->localPrivateKey);
  171. if(data->length % rsaContext->len != 0)
  172. return UA_STATUSCODE_BADINTERNALERROR;
  173. UA_ByteString decrypted;
  174. UA_StatusCode retval = UA_ByteString_allocBuffer(&decrypted, data->length);
  175. if(retval != UA_STATUSCODE_GOOD)
  176. return retval;
  177. size_t lenDataToDecrypt = data->length;
  178. size_t inOffset = 0;
  179. size_t offset = 0;
  180. size_t outLength = 0;
  181. while(lenDataToDecrypt >= rsaContext->len) {
  182. int mbedErr = mbedtls_pk_decrypt(&cc->policyContext->localPrivateKey,
  183. data->data + inOffset, rsaContext->len,
  184. decrypted.data + offset, &outLength,
  185. decrypted.length - offset, NULL, NULL);
  186. if(mbedErr)
  187. UA_ByteString_deleteMembers(&decrypted); // TODO: Maybe change error macro to jump to cleanup?
  188. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  189. inOffset += rsaContext->len;
  190. offset += outLength;
  191. lenDataToDecrypt -= rsaContext->len;
  192. }
  193. if(lenDataToDecrypt == 0) {
  194. memcpy(data->data, decrypted.data, offset);
  195. data->length = offset;
  196. } else {
  197. retval = UA_STATUSCODE_BADINTERNALERROR;
  198. }
  199. UA_ByteString_deleteMembers(&decrypted);
  200. return retval;
  201. }
  202. static size_t
  203. asym_getRemoteEncryptionKeyLength(const UA_SecurityPolicy *securityPolicy,
  204. const Basic128Rsa15_ChannelContext *cc) {
  205. return mbedtls_pk_get_len(&cc->remoteCertificate.pk) * 8;
  206. }
  207. static UA_StatusCode
  208. asym_makeThumbprint_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  209. const UA_ByteString *certificate,
  210. UA_ByteString *thumbprint) {
  211. if(securityPolicy == NULL || certificate == NULL || thumbprint == NULL)
  212. return UA_STATUSCODE_BADINTERNALERROR;
  213. if(UA_ByteString_equal(certificate, &UA_BYTESTRING_NULL))
  214. return UA_STATUSCODE_BADINTERNALERROR;
  215. if(thumbprint->length != UA_SHA1_LENGTH)
  216. return UA_STATUSCODE_BADINTERNALERROR;
  217. mbedtls_sha1(certificate->data, certificate->length, thumbprint->data);
  218. return UA_STATUSCODE_GOOD;
  219. }
  220. static UA_StatusCode
  221. asymmetricModule_compareCertificateThumbprint_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  222. const UA_ByteString *certificateThumbprint) {
  223. if(securityPolicy == NULL || certificateThumbprint == NULL)
  224. return UA_STATUSCODE_BADINTERNALERROR;
  225. Basic128Rsa15_PolicyContext *pc = (Basic128Rsa15_PolicyContext *)securityPolicy->policyContext;
  226. if(!UA_ByteString_equal(certificateThumbprint, &pc->localCertThumbprint))
  227. return UA_STATUSCODE_BADCERTIFICATEINVALID;
  228. return UA_STATUSCODE_GOOD;
  229. }
  230. /*******************/
  231. /* SymmetricModule */
  232. /*******************/
  233. static void
  234. md_hmac(mbedtls_md_context_t *context, const UA_ByteString *key,
  235. const UA_ByteString *in, unsigned char out[20]) {
  236. mbedtls_md_hmac_starts(context, key->data, key->length);
  237. mbedtls_md_hmac_update(context, in->data, in->length);
  238. mbedtls_md_hmac_finish(context, out);
  239. }
  240. static UA_StatusCode
  241. sym_verify_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  242. Basic128Rsa15_ChannelContext *cc,
  243. const UA_ByteString *message,
  244. const UA_ByteString *signature) {
  245. if(securityPolicy == NULL || cc == NULL || message == NULL || signature == NULL)
  246. return UA_STATUSCODE_BADINTERNALERROR;
  247. /* Compute MAC */
  248. if(signature->length != UA_SHA1_LENGTH) {
  249. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  250. "Signature size does not have the desired size defined by the security policy");
  251. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  252. }
  253. Basic128Rsa15_PolicyContext *pc =
  254. (Basic128Rsa15_PolicyContext *)securityPolicy->policyContext;
  255. unsigned char mac[UA_SHA1_LENGTH];
  256. md_hmac(&pc->sha1MdContext, &cc->remoteSymSigningKey, message, mac);
  257. /* Compare with Signature */
  258. if(memcmp(signature->data, mac, UA_SHA1_LENGTH) != 0)
  259. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  260. return UA_STATUSCODE_GOOD;
  261. }
  262. static UA_StatusCode
  263. sym_sign_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  264. const Basic128Rsa15_ChannelContext *cc,
  265. const UA_ByteString *message,
  266. UA_ByteString *signature) {
  267. if(signature->length != UA_SHA1_LENGTH)
  268. return UA_STATUSCODE_BADINTERNALERROR;
  269. md_hmac(&cc->policyContext->sha1MdContext, &cc->localSymSigningKey,
  270. message, signature->data);
  271. return UA_STATUSCODE_GOOD;
  272. }
  273. static size_t
  274. sym_getSignatureSize_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  275. const void *channelContext) {
  276. return UA_SHA1_LENGTH;
  277. }
  278. static size_t
  279. sym_getEncryptionKeyLength_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  280. const void *channelContext) {
  281. return UA_SECURITYPOLICY_BASIC128RSA15_SYM_KEY_LENGTH;
  282. }
  283. static UA_StatusCode
  284. sym_encrypt_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  285. const Basic128Rsa15_ChannelContext *cc,
  286. UA_ByteString *data) {
  287. if(securityPolicy == NULL || cc == NULL || data == NULL)
  288. return UA_STATUSCODE_BADINTERNALERROR;
  289. if(cc->localSymIv.length != securityPolicy->symmetricModule.encryptionBlockSize)
  290. return UA_STATUSCODE_BADINTERNALERROR;
  291. if(data->length % cc->localSymEncryptingKey.length != 0) {
  292. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  293. "Length of data to encrypt is not a multiple of the encryptingKey length."
  294. "Padding might not have been calculated appropriatley.");
  295. return UA_STATUSCODE_BADINTERNALERROR;
  296. }
  297. /* Keylength in bits */
  298. unsigned int keylength = (unsigned int)(cc->localSymEncryptingKey.length * 8);
  299. mbedtls_aes_context aesContext;
  300. int mbedErr = mbedtls_aes_setkey_enc(&aesContext, cc->localSymEncryptingKey.data, keylength);
  301. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADINTERNALERROR);
  302. UA_ByteString ivCopy;
  303. UA_StatusCode retval = UA_ByteString_copy(&cc->localSymIv, &ivCopy);
  304. if(retval != UA_STATUSCODE_GOOD)
  305. return retval;
  306. mbedErr = mbedtls_aes_crypt_cbc(&aesContext, MBEDTLS_AES_ENCRYPT, data->length,
  307. ivCopy.data, data->data, data->data);
  308. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADINTERNALERROR);
  309. UA_ByteString_deleteMembers(&ivCopy);
  310. return retval;
  311. }
  312. static UA_StatusCode
  313. sym_decrypt_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  314. const Basic128Rsa15_ChannelContext *cc,
  315. UA_ByteString *data) {
  316. if(securityPolicy == NULL || cc == NULL || data == NULL)
  317. return UA_STATUSCODE_BADINTERNALERROR;
  318. if(cc->remoteSymIv.length != securityPolicy->symmetricModule.encryptionBlockSize)
  319. return UA_STATUSCODE_BADINTERNALERROR;
  320. if(data->length % securityPolicy->symmetricModule.encryptionBlockSize != 0) {
  321. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  322. "Length of data to decrypt is not a multiple of the encryptingBlock size.");
  323. return UA_STATUSCODE_BADINTERNALERROR;
  324. }
  325. unsigned int keylength = (unsigned int)(cc->remoteSymEncryptingKey.length * 8);
  326. mbedtls_aes_context aesContext;
  327. int mbedErr = mbedtls_aes_setkey_dec(&aesContext, cc->remoteSymEncryptingKey.data, keylength);
  328. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADINTERNALERROR);
  329. UA_ByteString ivCopy;
  330. UA_StatusCode retval = UA_ByteString_copy(&cc->remoteSymIv, &ivCopy);
  331. if(retval != UA_STATUSCODE_GOOD)
  332. return retval;
  333. mbedErr = mbedtls_aes_crypt_cbc(&aesContext, MBEDTLS_AES_DECRYPT, data->length,
  334. ivCopy.data, data->data, data->data);
  335. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADINTERNALERROR);
  336. UA_ByteString_deleteMembers(&ivCopy);
  337. return retval;
  338. }
  339. static void
  340. swapBuffers(UA_ByteString *const bufA, UA_ByteString *const bufB) {
  341. UA_ByteString tmp = *bufA;
  342. *bufA = *bufB;
  343. *bufB = tmp;
  344. }
  345. static UA_StatusCode
  346. sym_generateKey_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  347. const UA_ByteString *secret, const UA_ByteString *seed,
  348. UA_ByteString *out) {
  349. if(securityPolicy == NULL || secret == NULL || seed == NULL || out == NULL)
  350. return UA_STATUSCODE_BADINTERNALERROR;
  351. Basic128Rsa15_PolicyContext *pc =
  352. (Basic128Rsa15_PolicyContext *)securityPolicy->policyContext;
  353. size_t hashLen = 0;
  354. const mbedtls_md_info_t *mdInfo = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
  355. hashLen = (size_t)mbedtls_md_get_size(mdInfo);
  356. UA_ByteString A_and_seed;
  357. UA_ByteString_allocBuffer(&A_and_seed, hashLen + seed->length);
  358. memcpy(A_and_seed.data + hashLen, seed->data, seed->length);
  359. UA_ByteString ANext_and_seed;
  360. UA_ByteString_allocBuffer(&ANext_and_seed, hashLen + seed->length);
  361. memcpy(ANext_and_seed.data + hashLen, seed->data, seed->length);
  362. UA_ByteString A = {
  363. hashLen,
  364. A_and_seed.data
  365. };
  366. UA_ByteString ANext = {
  367. hashLen,
  368. ANext_and_seed.data
  369. };
  370. md_hmac(&pc->sha1MdContext, secret, seed, A.data);
  371. UA_StatusCode retval = 0;
  372. for(size_t offset = 0; offset < out->length; offset += hashLen) {
  373. UA_ByteString outSegment = {
  374. hashLen,
  375. out->data + offset
  376. };
  377. UA_Boolean bufferAllocated = UA_FALSE;
  378. // Not enough room in out buffer to write the hash.
  379. if(offset + hashLen > out->length) {
  380. outSegment.data = NULL;
  381. outSegment.length = 0;
  382. retval |= UA_ByteString_allocBuffer(&outSegment, hashLen);
  383. if(retval != UA_STATUSCODE_GOOD) {
  384. UA_ByteString_deleteMembers(&A_and_seed);
  385. UA_ByteString_deleteMembers(&ANext_and_seed);
  386. return retval;
  387. }
  388. bufferAllocated = UA_TRUE;
  389. }
  390. md_hmac(&pc->sha1MdContext, secret, &A_and_seed, outSegment.data);
  391. md_hmac(&pc->sha1MdContext, secret, &A, ANext.data);
  392. if(retval != UA_STATUSCODE_GOOD) {
  393. if(bufferAllocated)
  394. UA_ByteString_deleteMembers(&outSegment);
  395. UA_ByteString_deleteMembers(&A_and_seed);
  396. UA_ByteString_deleteMembers(&ANext_and_seed);
  397. return retval;
  398. }
  399. if(bufferAllocated) {
  400. memcpy(out->data + offset, outSegment.data, out->length - offset);
  401. UA_ByteString_deleteMembers(&outSegment);
  402. }
  403. swapBuffers(&ANext_and_seed, &A_and_seed);
  404. swapBuffers(&ANext, &A);
  405. }
  406. UA_ByteString_deleteMembers(&A_and_seed);
  407. UA_ByteString_deleteMembers(&ANext_and_seed);
  408. return UA_STATUSCODE_GOOD;
  409. }
  410. static UA_StatusCode
  411. sym_generateNonce_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  412. UA_ByteString *out) {
  413. if(securityPolicy == NULL || securityPolicy->policyContext == NULL || out == NULL)
  414. return UA_STATUSCODE_BADINTERNALERROR;
  415. Basic128Rsa15_PolicyContext *data =
  416. (Basic128Rsa15_PolicyContext *)securityPolicy->policyContext;
  417. int mbedErr = mbedtls_ctr_drbg_random(&data->drbgContext, out->data, out->length);
  418. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADUNEXPECTEDERROR);
  419. return UA_STATUSCODE_GOOD;
  420. }
  421. /*****************/
  422. /* ChannelModule */
  423. /*****************/
  424. /* Assumes that the certificate has been verified externally */
  425. static UA_StatusCode
  426. parseRemoteCertificate_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  427. const UA_ByteString *remoteCertificate) {
  428. if(remoteCertificate == NULL || cc == NULL)
  429. return UA_STATUSCODE_BADINTERNALERROR;
  430. const UA_SecurityPolicy *securityPolicy = cc->policyContext->securityPolicy;
  431. /* Parse the certificate */
  432. int mbedErr = mbedtls_x509_crt_parse(&cc->remoteCertificate, remoteCertificate->data,
  433. remoteCertificate->length);
  434. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  435. /* Check the key length */
  436. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  437. if(rsaContext->len < UA_SECURITYPOLICY_BASIC128RSA15_MINASYMKEYLENGTH ||
  438. rsaContext->len > UA_SECURITYPOLICY_BASIC128RSA15_MAXASYMKEYLENGTH)
  439. return UA_STATUSCODE_BADCERTIFICATEUSENOTALLOWED;
  440. return UA_STATUSCODE_GOOD;
  441. }
  442. static void
  443. channelContext_deleteContext_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc) {
  444. UA_ByteString_deleteMembers(&cc->localSymSigningKey);
  445. UA_ByteString_deleteMembers(&cc->localSymEncryptingKey);
  446. UA_ByteString_deleteMembers(&cc->localSymIv);
  447. UA_ByteString_deleteMembers(&cc->remoteSymSigningKey);
  448. UA_ByteString_deleteMembers(&cc->remoteSymEncryptingKey);
  449. UA_ByteString_deleteMembers(&cc->remoteSymIv);
  450. mbedtls_x509_crt_free(&cc->remoteCertificate);
  451. UA_free(cc);
  452. }
  453. static UA_StatusCode
  454. channelContext_newContext_sp_basic128rsa15(const UA_SecurityPolicy *securityPolicy,
  455. const UA_ByteString *remoteCertificate,
  456. void **pp_contextData) {
  457. if(securityPolicy == NULL || remoteCertificate == NULL || pp_contextData == NULL)
  458. return UA_STATUSCODE_BADINTERNALERROR;
  459. /* Allocate the channel context */
  460. *pp_contextData = UA_malloc(sizeof(Basic128Rsa15_ChannelContext));
  461. if(*pp_contextData == NULL)
  462. return UA_STATUSCODE_BADOUTOFMEMORY;
  463. Basic128Rsa15_ChannelContext *cc = (Basic128Rsa15_ChannelContext *)*pp_contextData;
  464. /* Initialize the channel context */
  465. cc->policyContext = (Basic128Rsa15_PolicyContext *)securityPolicy->policyContext;
  466. UA_ByteString_init(&cc->localSymSigningKey);
  467. UA_ByteString_init(&cc->localSymEncryptingKey);
  468. UA_ByteString_init(&cc->localSymIv);
  469. UA_ByteString_init(&cc->remoteSymSigningKey);
  470. UA_ByteString_init(&cc->remoteSymEncryptingKey);
  471. UA_ByteString_init(&cc->remoteSymIv);
  472. mbedtls_x509_crt_init(&cc->remoteCertificate);
  473. // TODO: this can be optimized so that we dont allocate memory before parsing the certificate
  474. UA_StatusCode retval = parseRemoteCertificate_sp_basic128rsa15(cc, remoteCertificate);
  475. if(retval != UA_STATUSCODE_GOOD) {
  476. channelContext_deleteContext_sp_basic128rsa15(cc);
  477. *pp_contextData = NULL;
  478. }
  479. return retval;
  480. }
  481. static UA_StatusCode
  482. channelContext_setLocalSymEncryptingKey_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  483. const UA_ByteString *key) {
  484. if(key == NULL || cc == NULL)
  485. return UA_STATUSCODE_BADINTERNALERROR;
  486. UA_ByteString_deleteMembers(&cc->localSymEncryptingKey);
  487. return UA_ByteString_copy(key, &cc->localSymEncryptingKey);
  488. }
  489. static UA_StatusCode
  490. channelContext_setLocalSymSigningKey_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  491. const UA_ByteString *key) {
  492. if(key == NULL || cc == NULL)
  493. return UA_STATUSCODE_BADINTERNALERROR;
  494. UA_ByteString_deleteMembers(&cc->localSymSigningKey);
  495. return UA_ByteString_copy(key, &cc->localSymSigningKey);
  496. }
  497. static UA_StatusCode
  498. channelContext_setLocalSymIv_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  499. const UA_ByteString *iv) {
  500. if(iv == NULL || cc == NULL)
  501. return UA_STATUSCODE_BADINTERNALERROR;
  502. UA_ByteString_deleteMembers(&cc->localSymIv);
  503. return UA_ByteString_copy(iv, &cc->localSymIv);
  504. }
  505. static UA_StatusCode
  506. channelContext_setRemoteSymEncryptingKey_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  507. const UA_ByteString *key) {
  508. if(key == NULL || cc == NULL)
  509. return UA_STATUSCODE_BADINTERNALERROR;
  510. UA_ByteString_deleteMembers(&cc->remoteSymEncryptingKey);
  511. return UA_ByteString_copy(key, &cc->remoteSymEncryptingKey);
  512. }
  513. static UA_StatusCode
  514. channelContext_setRemoteSymSigningKey_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  515. const UA_ByteString *key) {
  516. if(key == NULL || cc == NULL)
  517. return UA_STATUSCODE_BADINTERNALERROR;
  518. UA_ByteString_deleteMembers(&cc->remoteSymSigningKey);
  519. return UA_ByteString_copy(key, &cc->remoteSymSigningKey);
  520. }
  521. static UA_StatusCode
  522. channelContext_setRemoteSymIv_sp_basic128rsa15(Basic128Rsa15_ChannelContext *cc,
  523. const UA_ByteString *iv) {
  524. if(iv == NULL || cc == NULL)
  525. return UA_STATUSCODE_BADINTERNALERROR;
  526. UA_ByteString_deleteMembers(&cc->remoteSymIv);
  527. return UA_ByteString_copy(iv, &cc->remoteSymIv);
  528. }
  529. static UA_StatusCode
  530. channelContext_compareCertificate_sp_basic128rsa15(const Basic128Rsa15_ChannelContext *cc,
  531. const UA_ByteString *certificate) {
  532. if(cc == NULL || certificate == NULL)
  533. return UA_STATUSCODE_BADINTERNALERROR;
  534. const UA_SecurityPolicy *securityPolicy = cc->policyContext->securityPolicy;
  535. mbedtls_x509_crt cert;
  536. int mbedErr = mbedtls_x509_crt_parse(&cert, certificate->data, certificate->length);
  537. UA_MBEDTLS_ERRORHANDLING_RETURN(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  538. if(cert.raw.len != cc->remoteCertificate.raw.len)
  539. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  540. if(memcmp(cert.raw.p, cc->remoteCertificate.raw.p, cert.raw.len) != 0)
  541. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  542. return UA_STATUSCODE_GOOD;
  543. }
  544. static size_t
  545. channelContext_getRemoteAsymPlainTextBlockSize_sp_basic128rsa15(const Basic128Rsa15_ChannelContext *cc) {
  546. mbedtls_rsa_context *const rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  547. return rsaContext->len - UA_SECURITYPOLICY_BASIC128RSA15_RSAPADDING_LEN;
  548. }
  549. static size_t
  550. channelContext_getRemoteAsymEncryptionBufferLengthOverhead_sp_basic128rsa15(const Basic128Rsa15_ChannelContext *cc,
  551. size_t maxEncryptionLength) {
  552. const size_t maxNumberOfBlocks = maxEncryptionLength /
  553. channelContext_getRemoteAsymPlainTextBlockSize_sp_basic128rsa15(cc);
  554. return maxNumberOfBlocks * UA_SECURITYPOLICY_BASIC128RSA15_RSAPADDING_LEN;
  555. }
  556. static void
  557. deleteMembers_sp_basic128rsa15(UA_SecurityPolicy *securityPolicy) {
  558. if(securityPolicy == NULL)
  559. return;
  560. if(securityPolicy->policyContext == NULL)
  561. return;
  562. UA_ByteString_deleteMembers(&securityPolicy->localCertificate);
  563. /* delete all allocated members in the context */
  564. Basic128Rsa15_PolicyContext *pc = (Basic128Rsa15_PolicyContext *)
  565. securityPolicy->policyContext;
  566. mbedtls_ctr_drbg_free(&pc->drbgContext);
  567. mbedtls_entropy_free(&pc->entropyContext);
  568. mbedtls_pk_free(&pc->localPrivateKey);
  569. mbedtls_md_free(&pc->sha1MdContext);
  570. UA_ByteString_deleteMembers(&pc->localCertThumbprint);
  571. UA_LOG_DEBUG(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  572. "Deleted members of EndpointContext for sp_basic128rsa15");
  573. UA_free(pc);
  574. securityPolicy->policyContext = NULL;
  575. }
  576. static UA_StatusCode
  577. policyContext_newContext_sp_basic128rsa15(UA_SecurityPolicy *securityPolicy,
  578. const UA_ByteString localPrivateKey) {
  579. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  580. if(securityPolicy == NULL)
  581. return UA_STATUSCODE_BADINTERNALERROR;
  582. Basic128Rsa15_PolicyContext *pc = (Basic128Rsa15_PolicyContext *)
  583. UA_malloc(sizeof(Basic128Rsa15_PolicyContext));
  584. securityPolicy->policyContext = (void *)pc;
  585. if(!pc) {
  586. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  587. goto error;
  588. }
  589. /* Initialize the PolicyContext */
  590. memset(pc, 0, sizeof(Basic128Rsa15_PolicyContext));
  591. mbedtls_ctr_drbg_init(&pc->drbgContext);
  592. mbedtls_entropy_init(&pc->entropyContext);
  593. mbedtls_pk_init(&pc->localPrivateKey);
  594. mbedtls_md_init(&pc->sha1MdContext);
  595. pc->securityPolicy = securityPolicy;
  596. /* Initialized the message digest */
  597. const mbedtls_md_info_t *const mdInfo = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
  598. int mbedErr = mbedtls_md_setup(&pc->sha1MdContext, mdInfo, MBEDTLS_MD_SHA1);
  599. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADOUTOFMEMORY);
  600. if(retval != UA_STATUSCODE_GOOD)
  601. goto error;
  602. /* Add the system entropy source */
  603. mbedErr = mbedtls_entropy_add_source(&pc->entropyContext,
  604. mbedtls_platform_entropy_poll, NULL, 0,
  605. MBEDTLS_ENTROPY_SOURCE_STRONG);
  606. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  607. if(retval != UA_STATUSCODE_GOOD)
  608. goto error;
  609. /* Seed the RNG */
  610. char *personalization = "open62541-drbg";
  611. mbedErr = mbedtls_ctr_drbg_seed(&pc->drbgContext, mbedtls_entropy_func,
  612. &pc->entropyContext,
  613. (const unsigned char *)personalization, 14);
  614. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  615. if(retval != UA_STATUSCODE_GOOD)
  616. goto error;
  617. /* Set the private key */
  618. mbedErr = mbedtls_pk_parse_key(&pc->localPrivateKey,
  619. localPrivateKey.data, localPrivateKey.length,
  620. NULL, 0);
  621. UA_MBEDTLS_ERRORHANDLING(UA_STATUSCODE_BADSECURITYCHECKSFAILED);
  622. if(retval != UA_STATUSCODE_GOOD)
  623. goto error;
  624. /* Set the local certificate thumbprint */
  625. retval = UA_ByteString_allocBuffer(&pc->localCertThumbprint, UA_SHA1_LENGTH);
  626. if(retval != UA_STATUSCODE_GOOD)
  627. goto error;
  628. retval = asym_makeThumbprint_sp_basic128rsa15(pc->securityPolicy,
  629. &securityPolicy->localCertificate,
  630. &pc->localCertThumbprint);
  631. if(retval != UA_STATUSCODE_GOOD)
  632. goto error;
  633. return UA_STATUSCODE_GOOD;
  634. error:
  635. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  636. "Could not create securityContext");
  637. if(securityPolicy->policyContext != NULL)
  638. deleteMembers_sp_basic128rsa15(securityPolicy);
  639. return retval;
  640. }
  641. UA_StatusCode
  642. UA_SecurityPolicy_Basic128Rsa15(UA_SecurityPolicy *policy, UA_CertificateVerification *certificateVerification,
  643. const UA_ByteString localCertificate, const UA_ByteString localPrivateKey,
  644. UA_Logger logger) {
  645. memset(policy, 0, sizeof(UA_SecurityPolicy));
  646. policy->logger = logger;
  647. policy->policyUri = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15");
  648. UA_SecurityPolicyAsymmetricModule *const asymmetricModule = &policy->asymmetricModule;
  649. UA_SecurityPolicySymmetricModule *const symmetricModule = &policy->symmetricModule;
  650. UA_SecurityPolicyChannelModule *const channelModule = &policy->channelModule;
  651. /* Copy the certificate and add a NULL to the end */
  652. UA_StatusCode retval =
  653. UA_ByteString_allocBuffer(&policy->localCertificate, localCertificate.length + 1);
  654. if(retval != UA_STATUSCODE_GOOD)
  655. return retval;
  656. memcpy(policy->localCertificate.data, localCertificate.data, localCertificate.length);
  657. policy->localCertificate.data[localCertificate.length] = '\0';
  658. policy->localCertificate.length--;
  659. policy->certificateVerification = certificateVerification;
  660. /* AsymmetricModule */
  661. asymmetricModule->cryptoModule.signatureAlgorithmUri =
  662. UA_STRING("http://www.w3.org/2000/09/xmldsig#rsa-sha1\0");
  663. asymmetricModule->cryptoModule.verify =
  664. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  665. const UA_ByteString *, const UA_ByteString *))asym_verify_sp_basic128rsa15;
  666. asymmetricModule->cryptoModule.sign =
  667. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  668. const UA_ByteString *, UA_ByteString *))asym_sign_sp_basic128rsa15;
  669. asymmetricModule->cryptoModule.getLocalSignatureSize =
  670. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getLocalSignatureSize_sp_basic128rsa15;
  671. asymmetricModule->cryptoModule.getRemoteSignatureSize =
  672. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getRemoteSignatureSize_sp_basic128rsa15;
  673. asymmetricModule->cryptoModule.encryptionAlgorithmUri = UA_STRING("TODO: ALG URI");
  674. asymmetricModule->cryptoModule.encrypt =
  675. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))asym_encrypt_sp_basic128rsa15;
  676. asymmetricModule->cryptoModule.decrypt =
  677. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))
  678. asym_decrypt_sp_basic128rsa15;
  679. asymmetricModule->cryptoModule.getLocalEncryptionKeyLength = NULL; // TODO: Write function
  680. asymmetricModule->cryptoModule.getRemoteEncryptionKeyLength =
  681. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getRemoteEncryptionKeyLength;
  682. asymmetricModule->makeCertificateThumbprint = asym_makeThumbprint_sp_basic128rsa15;
  683. asymmetricModule->compareCertificateThumbprint =
  684. asymmetricModule_compareCertificateThumbprint_sp_basic128rsa15;
  685. /* SymmetricModule */
  686. symmetricModule->encryptionBlockSize = 16;
  687. symmetricModule->signingKeyLength = 16;
  688. symmetricModule->generateKey = sym_generateKey_sp_basic128rsa15;
  689. symmetricModule->generateNonce = sym_generateNonce_sp_basic128rsa15;
  690. symmetricModule->cryptoModule.signatureAlgorithmUri =
  691. UA_STRING("http://www.w3.org/2000/09/xmldsig#hmac-sha1\0");
  692. symmetricModule->cryptoModule.verify =
  693. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *, const UA_ByteString *,
  694. const UA_ByteString *))sym_verify_sp_basic128rsa15;
  695. symmetricModule->cryptoModule.sign =
  696. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  697. const UA_ByteString *, UA_ByteString *))sym_sign_sp_basic128rsa15;
  698. symmetricModule->cryptoModule.getLocalSignatureSize = sym_getSignatureSize_sp_basic128rsa15;
  699. symmetricModule->cryptoModule.getRemoteSignatureSize = sym_getSignatureSize_sp_basic128rsa15;
  700. symmetricModule->cryptoModule.encryptionAlgorithmUri = UA_STRING("TODO: ALG URI");
  701. symmetricModule->cryptoModule.encrypt =
  702. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))sym_encrypt_sp_basic128rsa15;
  703. symmetricModule->cryptoModule.decrypt =
  704. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))
  705. sym_decrypt_sp_basic128rsa15;
  706. symmetricModule->cryptoModule.getLocalEncryptionKeyLength = sym_getEncryptionKeyLength_sp_basic128rsa15;
  707. symmetricModule->cryptoModule.getRemoteEncryptionKeyLength = sym_getEncryptionKeyLength_sp_basic128rsa15;
  708. /* ChannelModule */
  709. channelModule->newContext = channelContext_newContext_sp_basic128rsa15;
  710. channelModule->deleteContext = (void (*)(void *))
  711. channelContext_deleteContext_sp_basic128rsa15;
  712. channelModule->setLocalSymEncryptingKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  713. channelContext_setLocalSymEncryptingKey_sp_basic128rsa15;
  714. channelModule->setLocalSymSigningKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  715. channelContext_setLocalSymSigningKey_sp_basic128rsa15;
  716. channelModule->setLocalSymIv = (UA_StatusCode (*)(void *, const UA_ByteString *))
  717. channelContext_setLocalSymIv_sp_basic128rsa15;
  718. channelModule->setRemoteSymEncryptingKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  719. channelContext_setRemoteSymEncryptingKey_sp_basic128rsa15;
  720. channelModule->setRemoteSymSigningKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  721. channelContext_setRemoteSymSigningKey_sp_basic128rsa15;
  722. channelModule->setRemoteSymIv = (UA_StatusCode (*)(void *, const UA_ByteString *))
  723. channelContext_setRemoteSymIv_sp_basic128rsa15;
  724. channelModule->compareCertificate = (UA_StatusCode (*)(const void *, const UA_ByteString *))
  725. channelContext_compareCertificate_sp_basic128rsa15;
  726. channelModule->getRemoteAsymPlainTextBlockSize = (size_t (*)(const void *))
  727. channelContext_getRemoteAsymPlainTextBlockSize_sp_basic128rsa15;
  728. channelModule->getRemoteAsymEncryptionBufferLengthOverhead = (size_t (*)(const void *, size_t))
  729. channelContext_getRemoteAsymEncryptionBufferLengthOverhead_sp_basic128rsa15;
  730. policy->deleteMembers = deleteMembers_sp_basic128rsa15;
  731. return policyContext_newContext_sp_basic128rsa15(policy, localPrivateKey);
  732. }