ua_securitypolicy_basic128rsa15.c 36 KB

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