ua_securitypolicy_basic256sha256.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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. * Copyright 2018 (c) Daniel Feist, Precitec GmbH & Co. KG
  7. */
  8. #include <open62541/plugin/securitypolicy_default.h>
  9. #include <open62541/plugin/securitypolicy_mbedtls_common.h>
  10. #include <open62541/util.h>
  11. #ifdef UA_ENABLE_ENCRYPTION
  12. #include <mbedtls/aes.h>
  13. #include <mbedtls/ctr_drbg.h>
  14. #include <mbedtls/entropy.h>
  15. #include <mbedtls/entropy_poll.h>
  16. #include <mbedtls/error.h>
  17. #include <mbedtls/md.h>
  18. #include <mbedtls/sha1.h>
  19. #include <mbedtls/sha256.h>
  20. #include <mbedtls/version.h>
  21. #include <mbedtls/x509_crt.h>
  22. /* Notes:
  23. * mbedTLS' AES allows in-place encryption and decryption. Sow we don't have to
  24. * allocate temp buffers.
  25. * https://tls.mbed.org/discussions/generic/in-place-decryption-with-aes256-same-input-output-buffer
  26. */
  27. #define UA_SECURITYPOLICY_BASIC256SHA256_RSAPADDING_LEN 42
  28. #define UA_SHA1_LENGTH 20
  29. #define UA_SHA256_LENGTH 32
  30. #define UA_BASIC256SHA256_SYM_SIGNING_KEY_LENGTH 32
  31. #define UA_SECURITYPOLICY_BASIC256SHA256_SYM_KEY_LENGTH 32
  32. #define UA_SECURITYPOLICY_BASIC256SHA256_SYM_ENCRYPTION_BLOCK_SIZE 16
  33. #define UA_SECURITYPOLICY_BASIC256SHA256_SYM_PLAIN_TEXT_BLOCK_SIZE 16
  34. #define UA_SECURITYPOLICY_BASIC256SHA256_MINASYMKEYLENGTH 256
  35. #define UA_SECURITYPOLICY_BASIC256SHA256_MAXASYMKEYLENGTH 512
  36. typedef struct {
  37. const UA_SecurityPolicy *securityPolicy;
  38. UA_ByteString localCertThumbprint;
  39. mbedtls_ctr_drbg_context drbgContext;
  40. mbedtls_entropy_context entropyContext;
  41. mbedtls_md_context_t sha256MdContext;
  42. mbedtls_pk_context localPrivateKey;
  43. } Basic256Sha256_PolicyContext;
  44. typedef struct {
  45. Basic256Sha256_PolicyContext *policyContext;
  46. UA_ByteString localSymSigningKey;
  47. UA_ByteString localSymEncryptingKey;
  48. UA_ByteString localSymIv;
  49. UA_ByteString remoteSymSigningKey;
  50. UA_ByteString remoteSymEncryptingKey;
  51. UA_ByteString remoteSymIv;
  52. mbedtls_x509_crt remoteCertificate;
  53. } Basic256Sha256_ChannelContext;
  54. /********************/
  55. /* AsymmetricModule */
  56. /********************/
  57. /* VERIFY AsymmetricSignatureAlgorithm_RSA-PKCS15-SHA2-256 */
  58. static UA_StatusCode
  59. asym_verify_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  60. Basic256Sha256_ChannelContext *cc,
  61. const UA_ByteString *message,
  62. const UA_ByteString *signature) {
  63. if(securityPolicy == NULL || message == NULL || signature == NULL || cc == NULL)
  64. return UA_STATUSCODE_BADINTERNALERROR;
  65. unsigned char hash[UA_SHA256_LENGTH];
  66. #if MBEDTLS_VERSION_NUMBER >= 0x02070000
  67. // TODO check return status
  68. mbedtls_sha256_ret(message->data, message->length, hash, 0);
  69. #else
  70. mbedtls_sha256(message->data, message->length, hash, 0);
  71. #endif
  72. /* Set the RSA settings */
  73. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  74. mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256);
  75. /* For RSA keys, the default padding type is PKCS#1 v1.5 in mbedtls_pk_verify() */
  76. /* Alternatively, use more specific function mbedtls_rsa_rsassa_pkcs1_v15_verify(), i.e. */
  77. /* int mbedErr = mbedtls_rsa_rsassa_pkcs1_v15_verify(rsaContext, NULL, NULL,
  78. MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA256,
  79. UA_SHA256_LENGTH, hash,
  80. signature->data); */
  81. int mbedErr = mbedtls_pk_verify(&cc->remoteCertificate.pk,
  82. MBEDTLS_MD_SHA256, hash, UA_SHA256_LENGTH,
  83. signature->data, signature->length);
  84. if(mbedErr)
  85. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  86. return UA_STATUSCODE_GOOD;
  87. }
  88. /* AsymmetricSignatureAlgorithm_RSA-PKCS15-SHA2-256 */
  89. static UA_StatusCode
  90. asym_sign_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  91. Basic256Sha256_ChannelContext *cc,
  92. const UA_ByteString *message,
  93. UA_ByteString *signature) {
  94. if(securityPolicy == NULL || message == NULL || signature == NULL || cc == NULL)
  95. return UA_STATUSCODE_BADINTERNALERROR;
  96. unsigned char hash[UA_SHA256_LENGTH];
  97. #if MBEDTLS_VERSION_NUMBER >= 0x02070000
  98. // TODO check return status
  99. mbedtls_sha256_ret(message->data, message->length, hash, 0);
  100. #else
  101. mbedtls_sha256(message->data, message->length, hash, 0);
  102. #endif
  103. Basic256Sha256_PolicyContext *pc = cc->policyContext;
  104. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(pc->localPrivateKey);
  105. mbedtls_rsa_set_padding(rsaContext, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256);
  106. size_t sigLen = 0;
  107. /* For RSA keys, the default padding type is PKCS#1 v1.5 in mbedtls_pk_sign */
  108. /* Alternatively use more specific function mbedtls_rsa_rsassa_pkcs1_v15_sign() */
  109. int mbedErr = mbedtls_pk_sign(&pc->localPrivateKey,
  110. MBEDTLS_MD_SHA256, hash,
  111. UA_SHA256_LENGTH, signature->data,
  112. &sigLen, mbedtls_ctr_drbg_random,
  113. &pc->drbgContext);
  114. if(mbedErr)
  115. return UA_STATUSCODE_BADINTERNALERROR;
  116. return UA_STATUSCODE_GOOD;
  117. }
  118. static size_t
  119. asym_getLocalSignatureSize_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  120. const Basic256Sha256_ChannelContext *cc) {
  121. if(securityPolicy == NULL || cc == NULL)
  122. return 0;
  123. return mbedtls_pk_rsa(cc->policyContext->localPrivateKey)->len;
  124. }
  125. static size_t
  126. asym_getRemoteSignatureSize_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  127. const Basic256Sha256_ChannelContext *cc) {
  128. if(securityPolicy == NULL || cc == NULL)
  129. return 0;
  130. return mbedtls_pk_rsa(cc->remoteCertificate.pk)->len;
  131. }
  132. /* AsymmetricEncryptionAlgorithm_RSA-OAEP-SHA1 */
  133. static UA_StatusCode
  134. asym_encrypt_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  135. Basic256Sha256_ChannelContext *cc,
  136. UA_ByteString *data) {
  137. if(securityPolicy == NULL || cc == NULL || data == NULL)
  138. return UA_STATUSCODE_BADINTERNALERROR;
  139. const size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.
  140. encryptionAlgorithm.getRemotePlainTextBlockSize(securityPolicy, cc);
  141. mbedtls_rsa_context *remoteRsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  142. mbedtls_rsa_set_padding(remoteRsaContext, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA1);
  143. return mbedtls_encrypt_rsaOaep(remoteRsaContext, &cc->policyContext->drbgContext,
  144. data, plainTextBlockSize);
  145. }
  146. /* AsymmetricEncryptionAlgorithm_RSA-OAEP-SHA1 */
  147. static UA_StatusCode
  148. asym_decrypt_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  149. Basic256Sha256_ChannelContext *cc,
  150. UA_ByteString *data) {
  151. if(securityPolicy == NULL || cc == NULL || data == NULL)
  152. return UA_STATUSCODE_BADINTERNALERROR;
  153. return mbedtls_decrypt_rsaOaep(&cc->policyContext->localPrivateKey,
  154. &cc->policyContext->drbgContext, data);
  155. }
  156. static size_t
  157. asym_getRemoteEncryptionKeyLength_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  158. const Basic256Sha256_ChannelContext *cc) {
  159. return mbedtls_pk_get_len(&cc->remoteCertificate.pk) * 8;
  160. }
  161. static size_t
  162. asym_getRemoteBlockSize_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  163. const Basic256Sha256_ChannelContext *cc) {
  164. mbedtls_rsa_context *const rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  165. return rsaContext->len;
  166. }
  167. static size_t
  168. asym_getRemotePlainTextBlockSize_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  169. const Basic256Sha256_ChannelContext *cc) {
  170. mbedtls_rsa_context *const rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  171. return rsaContext->len - UA_SECURITYPOLICY_BASIC256SHA256_RSAPADDING_LEN;
  172. }
  173. static UA_StatusCode
  174. asym_makeThumbprint_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  175. const UA_ByteString *certificate,
  176. UA_ByteString *thumbprint) {
  177. if(securityPolicy == NULL || certificate == NULL || thumbprint == NULL)
  178. return UA_STATUSCODE_BADINTERNALERROR;
  179. return mbedtls_thumbprint_sha1(certificate, thumbprint);
  180. }
  181. static UA_StatusCode
  182. asymmetricModule_compareCertificateThumbprint_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  183. const UA_ByteString *certificateThumbprint) {
  184. if(securityPolicy == NULL || certificateThumbprint == NULL)
  185. return UA_STATUSCODE_BADINTERNALERROR;
  186. Basic256Sha256_PolicyContext *pc = (Basic256Sha256_PolicyContext *)securityPolicy->policyContext;
  187. if(!UA_ByteString_equal(certificateThumbprint, &pc->localCertThumbprint))
  188. return UA_STATUSCODE_BADCERTIFICATEINVALID;
  189. return UA_STATUSCODE_GOOD;
  190. }
  191. /*******************/
  192. /* SymmetricModule */
  193. /*******************/
  194. static UA_StatusCode
  195. sym_verify_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  196. Basic256Sha256_ChannelContext *cc,
  197. const UA_ByteString *message,
  198. const UA_ByteString *signature) {
  199. if(securityPolicy == NULL || cc == NULL || message == NULL || signature == NULL)
  200. return UA_STATUSCODE_BADINTERNALERROR;
  201. /* Compute MAC */
  202. if(signature->length != UA_SHA256_LENGTH) {
  203. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  204. "Signature size does not have the desired size defined by the security policy");
  205. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  206. }
  207. Basic256Sha256_PolicyContext *pc =
  208. (Basic256Sha256_PolicyContext *)securityPolicy->policyContext;
  209. unsigned char mac[UA_SHA256_LENGTH];
  210. mbedtls_hmac(&pc->sha256MdContext, &cc->remoteSymSigningKey, message, mac);
  211. /* Compare with Signature */
  212. if(!UA_constantTimeEqual(signature->data, mac, UA_SHA256_LENGTH))
  213. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  214. return UA_STATUSCODE_GOOD;
  215. }
  216. static UA_StatusCode
  217. sym_sign_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  218. const Basic256Sha256_ChannelContext *cc,
  219. const UA_ByteString *message,
  220. UA_ByteString *signature) {
  221. if(signature->length != UA_SHA256_LENGTH)
  222. return UA_STATUSCODE_BADINTERNALERROR;
  223. mbedtls_hmac(&cc->policyContext->sha256MdContext, &cc->localSymSigningKey,
  224. message, signature->data);
  225. return UA_STATUSCODE_GOOD;
  226. }
  227. static size_t
  228. sym_getSignatureSize_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  229. const void *channelContext) {
  230. return UA_SHA256_LENGTH;
  231. }
  232. static size_t
  233. sym_getSigningKeyLength_sp_basic256sha256(const UA_SecurityPolicy *const securityPolicy,
  234. const void *const channelContext) {
  235. return UA_BASIC256SHA256_SYM_SIGNING_KEY_LENGTH;
  236. }
  237. static size_t
  238. sym_getEncryptionKeyLength_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  239. const void *channelContext) {
  240. return UA_SECURITYPOLICY_BASIC256SHA256_SYM_KEY_LENGTH;
  241. }
  242. static size_t
  243. sym_getEncryptionBlockSize_sp_basic256sha256(const UA_SecurityPolicy *const securityPolicy,
  244. const void *const channelContext) {
  245. return UA_SECURITYPOLICY_BASIC256SHA256_SYM_ENCRYPTION_BLOCK_SIZE;
  246. }
  247. static size_t
  248. sym_getPlainTextBlockSize_sp_basic256sha256(const UA_SecurityPolicy *const securityPolicy,
  249. const void *const channelContext) {
  250. return UA_SECURITYPOLICY_BASIC256SHA256_SYM_PLAIN_TEXT_BLOCK_SIZE;
  251. }
  252. static UA_StatusCode
  253. sym_encrypt_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  254. const Basic256Sha256_ChannelContext *cc,
  255. UA_ByteString *data) {
  256. if(securityPolicy == NULL || cc == NULL || data == NULL)
  257. return UA_STATUSCODE_BADINTERNALERROR;
  258. if(cc->localSymIv.length != securityPolicy->symmetricModule.cryptoModule.
  259. encryptionAlgorithm.getLocalBlockSize(securityPolicy, cc))
  260. return UA_STATUSCODE_BADINTERNALERROR;
  261. size_t plainTextBlockSize = securityPolicy->symmetricModule.cryptoModule.
  262. encryptionAlgorithm.getLocalPlainTextBlockSize(securityPolicy, cc);
  263. if(data->length % plainTextBlockSize != 0) {
  264. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  265. "Length of data to encrypt is not a multiple of the plain text block size."
  266. "Padding might not have been calculated appropriately.");
  267. return UA_STATUSCODE_BADINTERNALERROR;
  268. }
  269. /* Keylength in bits */
  270. unsigned int keylength = (unsigned int)(cc->localSymEncryptingKey.length * 8);
  271. mbedtls_aes_context aesContext;
  272. int mbedErr = mbedtls_aes_setkey_enc(&aesContext, cc->localSymEncryptingKey.data, keylength);
  273. if(mbedErr)
  274. return UA_STATUSCODE_BADINTERNALERROR;
  275. UA_ByteString ivCopy;
  276. UA_StatusCode retval = UA_ByteString_copy(&cc->localSymIv, &ivCopy);
  277. if(retval != UA_STATUSCODE_GOOD)
  278. return retval;
  279. mbedErr = mbedtls_aes_crypt_cbc(&aesContext, MBEDTLS_AES_ENCRYPT, data->length,
  280. ivCopy.data, data->data, data->data);
  281. if(mbedErr)
  282. retval = UA_STATUSCODE_BADINTERNALERROR;
  283. UA_ByteString_deleteMembers(&ivCopy);
  284. return retval;
  285. }
  286. static UA_StatusCode
  287. sym_decrypt_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  288. const Basic256Sha256_ChannelContext *cc,
  289. UA_ByteString *data) {
  290. if(securityPolicy == NULL || cc == NULL || data == NULL)
  291. return UA_STATUSCODE_BADINTERNALERROR;
  292. size_t encryptionBlockSize = securityPolicy->symmetricModule.cryptoModule.
  293. encryptionAlgorithm.getRemoteBlockSize(securityPolicy, cc);
  294. if(cc->remoteSymIv.length != encryptionBlockSize)
  295. return UA_STATUSCODE_BADINTERNALERROR;
  296. if(data->length % encryptionBlockSize != 0) {
  297. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  298. "Length of data to decrypt is not a multiple of the encryptingBlock size.");
  299. return UA_STATUSCODE_BADINTERNALERROR;
  300. }
  301. unsigned int keylength = (unsigned int)(cc->remoteSymEncryptingKey.length * 8);
  302. mbedtls_aes_context aesContext;
  303. int mbedErr = mbedtls_aes_setkey_dec(&aesContext, cc->remoteSymEncryptingKey.data, keylength);
  304. if(mbedErr)
  305. return UA_STATUSCODE_BADINTERNALERROR;
  306. UA_ByteString ivCopy;
  307. UA_StatusCode retval = UA_ByteString_copy(&cc->remoteSymIv, &ivCopy);
  308. if(retval != UA_STATUSCODE_GOOD)
  309. return retval;
  310. mbedErr = mbedtls_aes_crypt_cbc(&aesContext, MBEDTLS_AES_DECRYPT, data->length,
  311. ivCopy.data, data->data, data->data);
  312. if(mbedErr)
  313. retval = UA_STATUSCODE_BADINTERNALERROR;
  314. UA_ByteString_deleteMembers(&ivCopy);
  315. return retval;
  316. }
  317. static UA_StatusCode
  318. sym_generateKey_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  319. const UA_ByteString *secret, const UA_ByteString *seed,
  320. UA_ByteString *out) {
  321. if(securityPolicy == NULL || secret == NULL || seed == NULL || out == NULL)
  322. return UA_STATUSCODE_BADINTERNALERROR;
  323. Basic256Sha256_PolicyContext *pc =
  324. (Basic256Sha256_PolicyContext *)securityPolicy->policyContext;
  325. return mbedtls_generateKey(&pc->sha256MdContext, secret, seed, out);
  326. }
  327. static UA_StatusCode
  328. sym_generateNonce_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  329. UA_ByteString *out) {
  330. if(securityPolicy == NULL || securityPolicy->policyContext == NULL || out == NULL)
  331. return UA_STATUSCODE_BADINTERNALERROR;
  332. Basic256Sha256_PolicyContext *pc =
  333. (Basic256Sha256_PolicyContext *)securityPolicy->policyContext;
  334. int mbedErr = mbedtls_ctr_drbg_random(&pc->drbgContext, out->data, out->length);
  335. if(mbedErr)
  336. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  337. return UA_STATUSCODE_GOOD;
  338. }
  339. /*****************/
  340. /* ChannelModule */
  341. /*****************/
  342. /* Assumes that the certificate has been verified externally */
  343. static UA_StatusCode
  344. parseRemoteCertificate_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  345. const UA_ByteString *remoteCertificate) {
  346. if(remoteCertificate == NULL || cc == NULL)
  347. return UA_STATUSCODE_BADINTERNALERROR;
  348. /* Parse the certificate */
  349. int mbedErr = mbedtls_x509_crt_parse(&cc->remoteCertificate, remoteCertificate->data,
  350. remoteCertificate->length);
  351. if(mbedErr)
  352. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  353. /* Check the key length */
  354. mbedtls_rsa_context *rsaContext = mbedtls_pk_rsa(cc->remoteCertificate.pk);
  355. if(rsaContext->len < UA_SECURITYPOLICY_BASIC256SHA256_MINASYMKEYLENGTH ||
  356. rsaContext->len > UA_SECURITYPOLICY_BASIC256SHA256_MAXASYMKEYLENGTH)
  357. return UA_STATUSCODE_BADCERTIFICATEUSENOTALLOWED;
  358. return UA_STATUSCODE_GOOD;
  359. }
  360. static void
  361. channelContext_deleteContext_sp_basic256sha256(Basic256Sha256_ChannelContext *cc) {
  362. UA_ByteString_deleteMembers(&cc->localSymSigningKey);
  363. UA_ByteString_deleteMembers(&cc->localSymEncryptingKey);
  364. UA_ByteString_deleteMembers(&cc->localSymIv);
  365. UA_ByteString_deleteMembers(&cc->remoteSymSigningKey);
  366. UA_ByteString_deleteMembers(&cc->remoteSymEncryptingKey);
  367. UA_ByteString_deleteMembers(&cc->remoteSymIv);
  368. mbedtls_x509_crt_free(&cc->remoteCertificate);
  369. UA_free(cc);
  370. }
  371. static UA_StatusCode
  372. channelContext_newContext_sp_basic256sha256(const UA_SecurityPolicy *securityPolicy,
  373. const UA_ByteString *remoteCertificate,
  374. void **pp_contextData) {
  375. if(securityPolicy == NULL || remoteCertificate == NULL || pp_contextData == NULL)
  376. return UA_STATUSCODE_BADINTERNALERROR;
  377. /* Allocate the channel context */
  378. *pp_contextData = UA_malloc(sizeof(Basic256Sha256_ChannelContext));
  379. if(*pp_contextData == NULL)
  380. return UA_STATUSCODE_BADOUTOFMEMORY;
  381. Basic256Sha256_ChannelContext *cc = (Basic256Sha256_ChannelContext *)*pp_contextData;
  382. /* Initialize the channel context */
  383. cc->policyContext = (Basic256Sha256_PolicyContext *)securityPolicy->policyContext;
  384. UA_ByteString_init(&cc->localSymSigningKey);
  385. UA_ByteString_init(&cc->localSymEncryptingKey);
  386. UA_ByteString_init(&cc->localSymIv);
  387. UA_ByteString_init(&cc->remoteSymSigningKey);
  388. UA_ByteString_init(&cc->remoteSymEncryptingKey);
  389. UA_ByteString_init(&cc->remoteSymIv);
  390. mbedtls_x509_crt_init(&cc->remoteCertificate);
  391. // TODO: this can be optimized so that we dont allocate memory before parsing the certificate
  392. UA_StatusCode retval = parseRemoteCertificate_sp_basic256sha256(cc, remoteCertificate);
  393. if(retval != UA_STATUSCODE_GOOD) {
  394. channelContext_deleteContext_sp_basic256sha256(cc);
  395. *pp_contextData = NULL;
  396. }
  397. return retval;
  398. }
  399. static UA_StatusCode
  400. channelContext_setLocalSymEncryptingKey_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  401. const UA_ByteString *key) {
  402. if(key == NULL || cc == NULL)
  403. return UA_STATUSCODE_BADINTERNALERROR;
  404. UA_ByteString_deleteMembers(&cc->localSymEncryptingKey);
  405. return UA_ByteString_copy(key, &cc->localSymEncryptingKey);
  406. }
  407. static UA_StatusCode
  408. channelContext_setLocalSymSigningKey_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  409. const UA_ByteString *key) {
  410. if(key == NULL || cc == NULL)
  411. return UA_STATUSCODE_BADINTERNALERROR;
  412. UA_ByteString_deleteMembers(&cc->localSymSigningKey);
  413. return UA_ByteString_copy(key, &cc->localSymSigningKey);
  414. }
  415. static UA_StatusCode
  416. channelContext_setLocalSymIv_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  417. const UA_ByteString *iv) {
  418. if(iv == NULL || cc == NULL)
  419. return UA_STATUSCODE_BADINTERNALERROR;
  420. UA_ByteString_deleteMembers(&cc->localSymIv);
  421. return UA_ByteString_copy(iv, &cc->localSymIv);
  422. }
  423. static UA_StatusCode
  424. channelContext_setRemoteSymEncryptingKey_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  425. const UA_ByteString *key) {
  426. if(key == NULL || cc == NULL)
  427. return UA_STATUSCODE_BADINTERNALERROR;
  428. UA_ByteString_deleteMembers(&cc->remoteSymEncryptingKey);
  429. return UA_ByteString_copy(key, &cc->remoteSymEncryptingKey);
  430. }
  431. static UA_StatusCode
  432. channelContext_setRemoteSymSigningKey_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  433. const UA_ByteString *key) {
  434. if(key == NULL || cc == NULL)
  435. return UA_STATUSCODE_BADINTERNALERROR;
  436. UA_ByteString_deleteMembers(&cc->remoteSymSigningKey);
  437. return UA_ByteString_copy(key, &cc->remoteSymSigningKey);
  438. }
  439. static UA_StatusCode
  440. channelContext_setRemoteSymIv_sp_basic256sha256(Basic256Sha256_ChannelContext *cc,
  441. const UA_ByteString *iv) {
  442. if(iv == NULL || cc == NULL)
  443. return UA_STATUSCODE_BADINTERNALERROR;
  444. UA_ByteString_deleteMembers(&cc->remoteSymIv);
  445. return UA_ByteString_copy(iv, &cc->remoteSymIv);
  446. }
  447. static UA_StatusCode
  448. channelContext_compareCertificate_sp_basic256sha256(const Basic256Sha256_ChannelContext *cc,
  449. const UA_ByteString *certificate) {
  450. if(cc == NULL || certificate == NULL)
  451. return UA_STATUSCODE_BADINTERNALERROR;
  452. mbedtls_x509_crt cert;
  453. mbedtls_x509_crt_init(&cert);
  454. int mbedErr = mbedtls_x509_crt_parse(&cert, certificate->data, certificate->length);
  455. if(mbedErr)
  456. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  457. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  458. if(cert.raw.len != cc->remoteCertificate.raw.len ||
  459. memcmp(cert.raw.p, cc->remoteCertificate.raw.p, cert.raw.len) != 0)
  460. retval = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  461. mbedtls_x509_crt_free(&cert);
  462. return retval;
  463. }
  464. static void
  465. deleteMembers_sp_basic256sha256(UA_SecurityPolicy *securityPolicy) {
  466. if(securityPolicy == NULL)
  467. return;
  468. if(securityPolicy->policyContext == NULL)
  469. return;
  470. UA_ByteString_deleteMembers(&securityPolicy->localCertificate);
  471. /* delete all allocated members in the context */
  472. Basic256Sha256_PolicyContext *pc = (Basic256Sha256_PolicyContext *)
  473. securityPolicy->policyContext;
  474. mbedtls_ctr_drbg_free(&pc->drbgContext);
  475. mbedtls_entropy_free(&pc->entropyContext);
  476. mbedtls_pk_free(&pc->localPrivateKey);
  477. mbedtls_md_free(&pc->sha256MdContext);
  478. UA_ByteString_deleteMembers(&pc->localCertThumbprint);
  479. UA_LOG_DEBUG(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  480. "Deleted members of EndpointContext for sp_basic256sha256");
  481. UA_free(pc);
  482. securityPolicy->policyContext = NULL;
  483. }
  484. static UA_StatusCode
  485. updateCertificateAndPrivateKey_sp_basic256sha256(UA_SecurityPolicy *securityPolicy,
  486. const UA_ByteString newCertificate,
  487. const UA_ByteString newPrivateKey) {
  488. if(securityPolicy == NULL)
  489. return UA_STATUSCODE_BADINTERNALERROR;
  490. if(securityPolicy->policyContext == NULL)
  491. return UA_STATUSCODE_BADINTERNALERROR;
  492. Basic256Sha256_PolicyContext *pc =
  493. (Basic256Sha256_PolicyContext *) securityPolicy->policyContext;
  494. UA_ByteString_deleteMembers(&securityPolicy->localCertificate);
  495. UA_StatusCode retval = UA_ByteString_allocBuffer(&securityPolicy->localCertificate,
  496. newCertificate.length + 1);
  497. if(retval != UA_STATUSCODE_GOOD)
  498. return retval;
  499. memcpy(securityPolicy->localCertificate.data, newCertificate.data, newCertificate.length);
  500. securityPolicy->localCertificate.data[newCertificate.length] = '\0';
  501. securityPolicy->localCertificate.length--;
  502. /* Set the new private key */
  503. mbedtls_pk_free(&pc->localPrivateKey);
  504. mbedtls_pk_init(&pc->localPrivateKey);
  505. int mbedErr = mbedtls_pk_parse_key(&pc->localPrivateKey, newPrivateKey.data,
  506. newPrivateKey.length, NULL, 0);
  507. if(mbedErr) {
  508. retval = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  509. goto error;
  510. }
  511. retval = asym_makeThumbprint_sp_basic256sha256(pc->securityPolicy,
  512. &securityPolicy->localCertificate,
  513. &pc->localCertThumbprint);
  514. if(retval != UA_STATUSCODE_GOOD)
  515. goto error;
  516. return retval;
  517. error:
  518. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  519. "Could not update certificate and private key");
  520. if(securityPolicy->policyContext != NULL)
  521. deleteMembers_sp_basic256sha256(securityPolicy);
  522. return retval;
  523. }
  524. static UA_StatusCode
  525. policyContext_newContext_sp_basic256sha256(UA_SecurityPolicy *securityPolicy,
  526. const UA_ByteString localPrivateKey) {
  527. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  528. if(securityPolicy == NULL)
  529. return UA_STATUSCODE_BADINTERNALERROR;
  530. if (localPrivateKey.length == 0) {
  531. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  532. "Can not initialize security policy. Private key is empty.");
  533. return UA_STATUSCODE_BADINVALIDARGUMENT;
  534. }
  535. Basic256Sha256_PolicyContext *pc = (Basic256Sha256_PolicyContext *)
  536. UA_malloc(sizeof(Basic256Sha256_PolicyContext));
  537. securityPolicy->policyContext = (void *)pc;
  538. if(!pc) {
  539. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  540. goto error;
  541. }
  542. /* Initialize the PolicyContext */
  543. memset(pc, 0, sizeof(Basic256Sha256_PolicyContext));
  544. mbedtls_ctr_drbg_init(&pc->drbgContext);
  545. mbedtls_entropy_init(&pc->entropyContext);
  546. mbedtls_pk_init(&pc->localPrivateKey);
  547. mbedtls_md_init(&pc->sha256MdContext);
  548. pc->securityPolicy = securityPolicy;
  549. /* Initialized the message digest */
  550. const mbedtls_md_info_t *const mdInfo = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
  551. int mbedErr = mbedtls_md_setup(&pc->sha256MdContext, mdInfo, MBEDTLS_MD_SHA256);
  552. if(mbedErr) {
  553. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  554. goto error;
  555. }
  556. /* Add the system entropy source */
  557. mbedErr = mbedtls_entropy_add_source(&pc->entropyContext,
  558. mbedtls_platform_entropy_poll, NULL, 0,
  559. MBEDTLS_ENTROPY_SOURCE_STRONG);
  560. if(mbedErr) {
  561. retval = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  562. goto error;
  563. }
  564. /* Seed the RNG */
  565. char *personalization = "open62541-drbg";
  566. mbedErr = mbedtls_ctr_drbg_seed(&pc->drbgContext, mbedtls_entropy_func,
  567. &pc->entropyContext,
  568. (const unsigned char *)personalization, 14);
  569. if(mbedErr) {
  570. retval = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  571. goto error;
  572. }
  573. /* Set the private key */
  574. mbedErr = mbedtls_pk_parse_key(&pc->localPrivateKey, localPrivateKey.data,
  575. localPrivateKey.length, NULL, 0);
  576. if(mbedErr) {
  577. retval = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  578. goto error;
  579. }
  580. /* Set the local certificate thumbprint */
  581. retval = UA_ByteString_allocBuffer(&pc->localCertThumbprint, UA_SHA1_LENGTH);
  582. if(retval != UA_STATUSCODE_GOOD)
  583. goto error;
  584. retval = asym_makeThumbprint_sp_basic256sha256(pc->securityPolicy,
  585. &securityPolicy->localCertificate,
  586. &pc->localCertThumbprint);
  587. if(retval != UA_STATUSCODE_GOOD)
  588. goto error;
  589. return UA_STATUSCODE_GOOD;
  590. error:
  591. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  592. "Could not create securityContext: %s", UA_StatusCode_name(retval));
  593. if(securityPolicy->policyContext != NULL)
  594. deleteMembers_sp_basic256sha256(securityPolicy);
  595. return retval;
  596. }
  597. UA_StatusCode
  598. UA_SecurityPolicy_Basic256Sha256(UA_SecurityPolicy *policy,
  599. UA_CertificateVerification *certificateVerification,
  600. const UA_ByteString localCertificate,
  601. const UA_ByteString localPrivateKey, const UA_Logger *logger) {
  602. memset(policy, 0, sizeof(UA_SecurityPolicy));
  603. policy->logger = logger;
  604. policy->policyUri = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
  605. UA_SecurityPolicyAsymmetricModule *const asymmetricModule = &policy->asymmetricModule;
  606. UA_SecurityPolicySymmetricModule *const symmetricModule = &policy->symmetricModule;
  607. UA_SecurityPolicyChannelModule *const channelModule = &policy->channelModule;
  608. /* Copy the certificate and add a NULL to the end */
  609. UA_StatusCode retval =
  610. UA_ByteString_allocBuffer(&policy->localCertificate, localCertificate.length + 1);
  611. if(retval != UA_STATUSCODE_GOOD)
  612. return retval;
  613. memcpy(policy->localCertificate.data, localCertificate.data, localCertificate.length);
  614. policy->localCertificate.data[localCertificate.length] = '\0';
  615. policy->localCertificate.length--;
  616. policy->certificateVerification = certificateVerification;
  617. /* AsymmetricModule */
  618. UA_SecurityPolicySignatureAlgorithm *asym_signatureAlgorithm =
  619. &asymmetricModule->cryptoModule.signatureAlgorithm;
  620. asym_signatureAlgorithm->uri =
  621. UA_STRING("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256\0");
  622. asym_signatureAlgorithm->verify =
  623. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  624. const UA_ByteString *, const UA_ByteString *))asym_verify_sp_basic256sha256;
  625. asym_signatureAlgorithm->sign =
  626. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  627. const UA_ByteString *, UA_ByteString *))asym_sign_sp_basic256sha256;
  628. asym_signatureAlgorithm->getLocalSignatureSize =
  629. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getLocalSignatureSize_sp_basic256sha256;
  630. asym_signatureAlgorithm->getRemoteSignatureSize =
  631. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getRemoteSignatureSize_sp_basic256sha256;
  632. asym_signatureAlgorithm->getLocalKeyLength = NULL; // TODO: Write function
  633. asym_signatureAlgorithm->getRemoteKeyLength = NULL; // TODO: Write function
  634. UA_SecurityPolicyEncryptionAlgorithm *asym_encryptionAlgorithm =
  635. &asymmetricModule->cryptoModule.encryptionAlgorithm;
  636. asym_encryptionAlgorithm->uri = UA_STRING("http://www.w3.org/2001/04/xmlenc#rsa-oaep\0");
  637. asym_encryptionAlgorithm->encrypt =
  638. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))asym_encrypt_sp_basic256sha256;
  639. asym_encryptionAlgorithm->decrypt =
  640. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))
  641. asym_decrypt_sp_basic256sha256;
  642. asym_encryptionAlgorithm->getLocalKeyLength = NULL; // TODO: Write function
  643. asym_encryptionAlgorithm->getRemoteKeyLength =
  644. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getRemoteEncryptionKeyLength_sp_basic256sha256;
  645. asym_encryptionAlgorithm->getLocalBlockSize = NULL; // TODO: Write function
  646. asym_encryptionAlgorithm->getRemoteBlockSize = (size_t (*)(const UA_SecurityPolicy *,
  647. const void *))asym_getRemoteBlockSize_sp_basic256sha256;
  648. asym_encryptionAlgorithm->getLocalPlainTextBlockSize = NULL; // TODO: Write function
  649. asym_encryptionAlgorithm->getRemotePlainTextBlockSize =
  650. (size_t (*)(const UA_SecurityPolicy *, const void *))asym_getRemotePlainTextBlockSize_sp_basic256sha256;
  651. asymmetricModule->makeCertificateThumbprint = asym_makeThumbprint_sp_basic256sha256;
  652. asymmetricModule->compareCertificateThumbprint =
  653. asymmetricModule_compareCertificateThumbprint_sp_basic256sha256;
  654. /* SymmetricModule */
  655. symmetricModule->generateKey = sym_generateKey_sp_basic256sha256;
  656. symmetricModule->generateNonce = sym_generateNonce_sp_basic256sha256;
  657. UA_SecurityPolicySignatureAlgorithm *sym_signatureAlgorithm =
  658. &symmetricModule->cryptoModule.signatureAlgorithm;
  659. sym_signatureAlgorithm->uri =
  660. UA_STRING("http://www.w3.org/2000/09/xmldsig#hmac-sha1\0");
  661. sym_signatureAlgorithm->verify =
  662. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *, const UA_ByteString *,
  663. const UA_ByteString *))sym_verify_sp_basic256sha256;
  664. sym_signatureAlgorithm->sign =
  665. (UA_StatusCode (*)(const UA_SecurityPolicy *, void *,
  666. const UA_ByteString *, UA_ByteString *))sym_sign_sp_basic256sha256;
  667. sym_signatureAlgorithm->getLocalSignatureSize = sym_getSignatureSize_sp_basic256sha256;
  668. sym_signatureAlgorithm->getRemoteSignatureSize = sym_getSignatureSize_sp_basic256sha256;
  669. sym_signatureAlgorithm->getLocalKeyLength =
  670. (size_t (*)(const UA_SecurityPolicy *,
  671. const void *))sym_getSigningKeyLength_sp_basic256sha256;
  672. sym_signatureAlgorithm->getRemoteKeyLength =
  673. (size_t (*)(const UA_SecurityPolicy *,
  674. const void *))sym_getSigningKeyLength_sp_basic256sha256;
  675. UA_SecurityPolicyEncryptionAlgorithm *sym_encryptionAlgorithm =
  676. &symmetricModule->cryptoModule.encryptionAlgorithm;
  677. sym_encryptionAlgorithm->uri = UA_STRING("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
  678. sym_encryptionAlgorithm->encrypt =
  679. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))sym_encrypt_sp_basic256sha256;
  680. sym_encryptionAlgorithm->decrypt =
  681. (UA_StatusCode(*)(const UA_SecurityPolicy *, void *, UA_ByteString *))sym_decrypt_sp_basic256sha256;
  682. sym_encryptionAlgorithm->getLocalKeyLength = sym_getEncryptionKeyLength_sp_basic256sha256;
  683. sym_encryptionAlgorithm->getRemoteKeyLength = sym_getEncryptionKeyLength_sp_basic256sha256;
  684. sym_encryptionAlgorithm->getLocalBlockSize =
  685. (size_t (*)(const UA_SecurityPolicy *, const void *))sym_getEncryptionBlockSize_sp_basic256sha256;
  686. sym_encryptionAlgorithm->getRemoteBlockSize =
  687. (size_t (*)(const UA_SecurityPolicy *, const void *))sym_getEncryptionBlockSize_sp_basic256sha256;
  688. sym_encryptionAlgorithm->getLocalPlainTextBlockSize =
  689. (size_t (*)(const UA_SecurityPolicy *, const void *))sym_getPlainTextBlockSize_sp_basic256sha256;
  690. sym_encryptionAlgorithm->getRemotePlainTextBlockSize =
  691. (size_t (*)(const UA_SecurityPolicy *, const void *))sym_getPlainTextBlockSize_sp_basic256sha256;
  692. symmetricModule->secureChannelNonceLength = 32;
  693. // Use the same signature algorithm as the asymmetric component for certificate signing (see standard)
  694. policy->certificateSigningAlgorithm = policy->asymmetricModule.cryptoModule.signatureAlgorithm;
  695. /* ChannelModule */
  696. channelModule->newContext = channelContext_newContext_sp_basic256sha256;
  697. channelModule->deleteContext = (void (*)(void *))
  698. channelContext_deleteContext_sp_basic256sha256;
  699. channelModule->setLocalSymEncryptingKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  700. channelContext_setLocalSymEncryptingKey_sp_basic256sha256;
  701. channelModule->setLocalSymSigningKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  702. channelContext_setLocalSymSigningKey_sp_basic256sha256;
  703. channelModule->setLocalSymIv = (UA_StatusCode (*)(void *, const UA_ByteString *))
  704. channelContext_setLocalSymIv_sp_basic256sha256;
  705. channelModule->setRemoteSymEncryptingKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  706. channelContext_setRemoteSymEncryptingKey_sp_basic256sha256;
  707. channelModule->setRemoteSymSigningKey = (UA_StatusCode (*)(void *, const UA_ByteString *))
  708. channelContext_setRemoteSymSigningKey_sp_basic256sha256;
  709. channelModule->setRemoteSymIv = (UA_StatusCode (*)(void *, const UA_ByteString *))
  710. channelContext_setRemoteSymIv_sp_basic256sha256;
  711. channelModule->compareCertificate = (UA_StatusCode (*)(const void *, const UA_ByteString *))
  712. channelContext_compareCertificate_sp_basic256sha256;
  713. policy->updateCertificateAndPrivateKey = updateCertificateAndPrivateKey_sp_basic256sha256;
  714. policy->deleteMembers = deleteMembers_sp_basic256sha256;
  715. return policyContext_newContext_sp_basic256sha256(policy, localPrivateKey);
  716. }
  717. #endif