ua_securitypolicy_basic128rsa15.c 36 KB

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