e_afalg.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. /*
  2. * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /* We need to use some deprecated APIs */
  10. #define OPENSSL_SUPPRESS_DEPRECATED
  11. /* Required for vmsplice */
  12. #ifndef _GNU_SOURCE
  13. # define _GNU_SOURCE
  14. #endif
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <openssl/engine.h>
  19. #include <openssl/async.h>
  20. #include <openssl/err.h>
  21. #include "internal/nelem.h"
  22. #include <sys/socket.h>
  23. #include <linux/version.h>
  24. #define K_MAJ 4
  25. #define K_MIN1 1
  26. #define K_MIN2 0
  27. #if LINUX_VERSION_CODE < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
  28. !defined(AF_ALG)
  29. # ifndef PEDANTIC
  30. # warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
  31. # warning "Skipping Compilation of AFALG engine"
  32. # endif
  33. void engine_load_afalg_int(void);
  34. void engine_load_afalg_int(void)
  35. {
  36. }
  37. #else
  38. # include <linux/if_alg.h>
  39. # include <fcntl.h>
  40. # include <sys/utsname.h>
  41. # include <linux/aio_abi.h>
  42. # include <sys/syscall.h>
  43. # include <errno.h>
  44. # include "e_afalg.h"
  45. # include "e_afalg_err.c"
  46. # ifndef SOL_ALG
  47. # define SOL_ALG 279
  48. # endif
  49. # ifdef ALG_ZERO_COPY
  50. # ifndef SPLICE_F_GIFT
  51. # define SPLICE_F_GIFT (0x08)
  52. # endif
  53. # endif
  54. # define ALG_AES_IV_LEN 16
  55. # define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
  56. # define ALG_OP_TYPE unsigned int
  57. # define ALG_OP_LEN (sizeof(ALG_OP_TYPE))
  58. # ifdef OPENSSL_NO_DYNAMIC_ENGINE
  59. void engine_load_afalg_int(void);
  60. # endif
  61. /* Local Linkage Functions */
  62. static int afalg_init_aio(afalg_aio *aio);
  63. static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
  64. unsigned char *buf, size_t len);
  65. static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
  66. const char *ciphername);
  67. static int afalg_destroy(ENGINE *e);
  68. static int afalg_init(ENGINE *e);
  69. static int afalg_finish(ENGINE *e);
  70. static const EVP_CIPHER *afalg_aes_cbc(int nid);
  71. static cbc_handles *get_cipher_handle(int nid);
  72. static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
  73. const int **nids, int nid);
  74. static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
  75. const unsigned char *iv, int enc);
  76. static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
  77. const unsigned char *in, size_t inl);
  78. static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
  79. static int afalg_chk_platform(void);
  80. /* Engine Id and Name */
  81. static const char *engine_afalg_id = "afalg";
  82. static const char *engine_afalg_name = "AFALG engine support";
  83. static int afalg_cipher_nids[] = {
  84. NID_aes_128_cbc,
  85. NID_aes_192_cbc,
  86. NID_aes_256_cbc,
  87. };
  88. static cbc_handles cbc_handle[] = {{AES_KEY_SIZE_128, NULL},
  89. {AES_KEY_SIZE_192, NULL},
  90. {AES_KEY_SIZE_256, NULL}};
  91. static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
  92. {
  93. return syscall(__NR_io_setup, n, ctx);
  94. }
  95. static ossl_inline int eventfd(int n)
  96. {
  97. return syscall(__NR_eventfd2, n, 0);
  98. }
  99. static ossl_inline int io_destroy(aio_context_t ctx)
  100. {
  101. return syscall(__NR_io_destroy, ctx);
  102. }
  103. static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
  104. {
  105. return syscall(__NR_io_submit, ctx, n, iocb);
  106. }
  107. static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
  108. struct io_event *events,
  109. struct timespec *timeout)
  110. {
  111. #if defined(__NR_io_getevents)
  112. return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
  113. #elif defined(__NR_io_pgetevents_time64)
  114. /* Let's only support the 64 suffix syscalls for 64-bit time_t.
  115. * This simplifies the code for us as we don't need to use a 64-bit
  116. * version of timespec with a 32-bit time_t and handle converting
  117. * between 64-bit and 32-bit times and check for overflows.
  118. */
  119. if (sizeof(timeout->tv_sec) == 8)
  120. return syscall(__NR_io_pgetevents_time64, ctx, min, max, events, timeout, NULL);
  121. else {
  122. errno = ENOSYS;
  123. return -1;
  124. }
  125. #else
  126. # error "We require either the io_getevents syscall or __NR_io_pgetevents_time64."
  127. #endif
  128. }
  129. static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
  130. OSSL_ASYNC_FD waitfd, void *custom)
  131. {
  132. close(waitfd);
  133. }
  134. static int afalg_setup_async_event_notification(afalg_aio *aio)
  135. {
  136. ASYNC_JOB *job;
  137. ASYNC_WAIT_CTX *waitctx;
  138. void *custom = NULL;
  139. int ret;
  140. if ((job = ASYNC_get_current_job()) != NULL) {
  141. /* Async mode */
  142. waitctx = ASYNC_get_wait_ctx(job);
  143. if (waitctx == NULL) {
  144. ALG_WARN("%s(%d): ASYNC_get_wait_ctx error", __FILE__, __LINE__);
  145. return 0;
  146. }
  147. /* Get waitfd from ASYNC_WAIT_CTX if it is already set */
  148. ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
  149. &aio->efd, &custom);
  150. if (ret == 0) {
  151. /*
  152. * waitfd is not set in ASYNC_WAIT_CTX, create a new one
  153. * and set it. efd will be signaled when AIO operation completes
  154. */
  155. aio->efd = eventfd(0);
  156. if (aio->efd == -1) {
  157. ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__,
  158. __LINE__);
  159. AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
  160. AFALG_R_EVENTFD_FAILED);
  161. return 0;
  162. }
  163. ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
  164. aio->efd, custom,
  165. afalg_waitfd_cleanup);
  166. if (ret == 0) {
  167. ALG_WARN("%s(%d): Failed to set wait fd", __FILE__, __LINE__);
  168. close(aio->efd);
  169. return 0;
  170. }
  171. /* make fd non-blocking in async mode */
  172. if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
  173. ALG_WARN("%s(%d): Failed to set event fd as NONBLOCKING",
  174. __FILE__, __LINE__);
  175. }
  176. }
  177. aio->mode = MODE_ASYNC;
  178. } else {
  179. /* Sync mode */
  180. aio->efd = eventfd(0);
  181. if (aio->efd == -1) {
  182. ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__, __LINE__);
  183. AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
  184. AFALG_R_EVENTFD_FAILED);
  185. return 0;
  186. }
  187. aio->mode = MODE_SYNC;
  188. }
  189. return 1;
  190. }
  191. static int afalg_init_aio(afalg_aio *aio)
  192. {
  193. int r = -1;
  194. /* Initialise for AIO */
  195. aio->aio_ctx = 0;
  196. r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
  197. if (r < 0) {
  198. ALG_PERR("%s(%d): io_setup error : ", __FILE__, __LINE__);
  199. AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
  200. return 0;
  201. }
  202. memset(aio->cbt, 0, sizeof(aio->cbt));
  203. aio->efd = -1;
  204. aio->mode = MODE_UNINIT;
  205. return 1;
  206. }
  207. static int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
  208. size_t len)
  209. {
  210. int r;
  211. int retry = 0;
  212. unsigned int done = 0;
  213. struct iocb *cb;
  214. struct timespec timeout;
  215. struct io_event events[MAX_INFLIGHTS];
  216. u_int64_t eval = 0;
  217. timeout.tv_sec = 0;
  218. timeout.tv_nsec = 0;
  219. /* if efd has not been initialised yet do it here */
  220. if (aio->mode == MODE_UNINIT) {
  221. r = afalg_setup_async_event_notification(aio);
  222. if (r == 0)
  223. return 0;
  224. }
  225. cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
  226. memset(cb, '\0', sizeof(*cb));
  227. cb->aio_fildes = sfd;
  228. cb->aio_lio_opcode = IOCB_CMD_PREAD;
  229. /*
  230. * The pointer has to be converted to unsigned value first to avoid
  231. * sign extension on cast to 64 bit value in 32-bit builds
  232. */
  233. cb->aio_buf = (size_t)buf;
  234. cb->aio_offset = 0;
  235. cb->aio_data = 0;
  236. cb->aio_nbytes = len;
  237. cb->aio_flags = IOCB_FLAG_RESFD;
  238. cb->aio_resfd = aio->efd;
  239. /*
  240. * Perform AIO read on AFALG socket, this in turn performs an async
  241. * crypto operation in kernel space
  242. */
  243. r = io_read(aio->aio_ctx, 1, &cb);
  244. if (r < 0) {
  245. ALG_PWARN("%s(%d): io_read failed : ", __FILE__, __LINE__);
  246. return 0;
  247. }
  248. do {
  249. /* While AIO read is being performed pause job */
  250. ASYNC_pause_job();
  251. /* Check for completion of AIO read */
  252. r = read(aio->efd, &eval, sizeof(eval));
  253. if (r < 0) {
  254. if (errno == EAGAIN || errno == EWOULDBLOCK)
  255. continue;
  256. ALG_PERR("%s(%d): read failed for event fd : ", __FILE__, __LINE__);
  257. return 0;
  258. } else if (r == 0 || eval <= 0) {
  259. ALG_WARN("%s(%d): eventfd read %d bytes, eval = %lu\n", __FILE__,
  260. __LINE__, r, eval);
  261. }
  262. if (eval > 0) {
  263. /* Get results of AIO read */
  264. r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
  265. events, &timeout);
  266. if (r > 0) {
  267. /*
  268. * events.res indicates the actual status of the operation.
  269. * Handle the error condition first.
  270. */
  271. if (events[0].res < 0) {
  272. /*
  273. * Underlying operation cannot be completed at the time
  274. * of previous submission. Resubmit for the operation.
  275. */
  276. if (events[0].res == -EBUSY && retry++ < 3) {
  277. r = io_read(aio->aio_ctx, 1, &cb);
  278. if (r < 0) {
  279. ALG_PERR("%s(%d): retry %d for io_read failed : ",
  280. __FILE__, __LINE__, retry);
  281. return 0;
  282. }
  283. continue;
  284. } else {
  285. /*
  286. * Retries exceed for -EBUSY or unrecoverable error
  287. * condition for this instance of operation.
  288. */
  289. ALG_WARN
  290. ("%s(%d): Crypto Operation failed with code %lld\n",
  291. __FILE__, __LINE__, events[0].res);
  292. return 0;
  293. }
  294. }
  295. /* Operation successful. */
  296. done = 1;
  297. } else if (r < 0) {
  298. ALG_PERR("%s(%d): io_getevents failed : ", __FILE__, __LINE__);
  299. return 0;
  300. } else {
  301. ALG_WARN("%s(%d): io_geteventd read 0 bytes\n", __FILE__,
  302. __LINE__);
  303. }
  304. }
  305. } while (!done);
  306. return 1;
  307. }
  308. static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
  309. const ALG_OP_TYPE op)
  310. {
  311. cmsg->cmsg_level = SOL_ALG;
  312. cmsg->cmsg_type = ALG_SET_OP;
  313. cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
  314. memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
  315. }
  316. static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
  317. const unsigned int len)
  318. {
  319. struct af_alg_iv *aiv;
  320. cmsg->cmsg_level = SOL_ALG;
  321. cmsg->cmsg_type = ALG_SET_IV;
  322. cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
  323. aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
  324. aiv->ivlen = len;
  325. memcpy(aiv->iv, iv, len);
  326. }
  327. static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
  328. const int klen)
  329. {
  330. int ret;
  331. ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
  332. if (ret < 0) {
  333. ALG_PERR("%s(%d): Failed to set socket option : ", __FILE__, __LINE__);
  334. AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
  335. return 0;
  336. }
  337. return 1;
  338. }
  339. static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
  340. const char *ciphername)
  341. {
  342. struct sockaddr_alg sa;
  343. int r = -1;
  344. actx->bfd = actx->sfd = -1;
  345. memset(&sa, 0, sizeof(sa));
  346. sa.salg_family = AF_ALG;
  347. OPENSSL_strlcpy((char *) sa.salg_type, ciphertype, sizeof(sa.salg_type));
  348. OPENSSL_strlcpy((char *) sa.salg_name, ciphername, sizeof(sa.salg_name));
  349. actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
  350. if (actx->bfd == -1) {
  351. ALG_PERR("%s(%d): Failed to open socket : ", __FILE__, __LINE__);
  352. AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
  353. goto err;
  354. }
  355. r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
  356. if (r < 0) {
  357. ALG_PERR("%s(%d): Failed to bind socket : ", __FILE__, __LINE__);
  358. AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
  359. goto err;
  360. }
  361. actx->sfd = accept(actx->bfd, NULL, 0);
  362. if (actx->sfd < 0) {
  363. ALG_PERR("%s(%d): Socket Accept Failed : ", __FILE__, __LINE__);
  364. AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
  365. goto err;
  366. }
  367. return 1;
  368. err:
  369. if (actx->bfd >= 0)
  370. close(actx->bfd);
  371. if (actx->sfd >= 0)
  372. close(actx->sfd);
  373. actx->bfd = actx->sfd = -1;
  374. return 0;
  375. }
  376. static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
  377. size_t inl, const unsigned char *iv,
  378. unsigned int enc)
  379. {
  380. struct msghdr msg;
  381. struct cmsghdr *cmsg;
  382. struct iovec iov;
  383. ssize_t sbytes;
  384. # ifdef ALG_ZERO_COPY
  385. int ret;
  386. # endif
  387. char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
  388. memset(&msg, 0, sizeof(msg));
  389. memset(cbuf, 0, sizeof(cbuf));
  390. msg.msg_control = cbuf;
  391. msg.msg_controllen = sizeof(cbuf);
  392. /*
  393. * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
  394. * kernel as part of sendmsg()'s ancillary data
  395. */
  396. cmsg = CMSG_FIRSTHDR(&msg);
  397. afalg_set_op_sk(cmsg, enc);
  398. cmsg = CMSG_NXTHDR(&msg, cmsg);
  399. afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
  400. /* iov that describes input data */
  401. iov.iov_base = (unsigned char *)in;
  402. iov.iov_len = inl;
  403. msg.msg_flags = MSG_MORE;
  404. # ifdef ALG_ZERO_COPY
  405. /*
  406. * ZERO_COPY mode
  407. * Works best when buffer is 4k aligned
  408. * OPENS: out of place processing (i.e. out != in)
  409. */
  410. /* Input data is not sent as part of call to sendmsg() */
  411. msg.msg_iovlen = 0;
  412. msg.msg_iov = NULL;
  413. /* Sendmsg() sends iv and cipher direction to the kernel */
  414. sbytes = sendmsg(actx->sfd, &msg, 0);
  415. if (sbytes < 0) {
  416. ALG_PERR("%s(%d): sendmsg failed for zero copy cipher operation : ",
  417. __FILE__, __LINE__);
  418. return 0;
  419. }
  420. /*
  421. * vmsplice and splice are used to pin the user space input buffer for
  422. * kernel space processing avoiding copies from user to kernel space
  423. */
  424. ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
  425. if (ret < 0) {
  426. ALG_PERR("%s(%d): vmsplice failed : ", __FILE__, __LINE__);
  427. return 0;
  428. }
  429. ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
  430. if (ret < 0) {
  431. ALG_PERR("%s(%d): splice failed : ", __FILE__, __LINE__);
  432. return 0;
  433. }
  434. # else
  435. msg.msg_iovlen = 1;
  436. msg.msg_iov = &iov;
  437. /* Sendmsg() sends iv, cipher direction and input data to the kernel */
  438. sbytes = sendmsg(actx->sfd, &msg, 0);
  439. if (sbytes < 0) {
  440. ALG_PERR("%s(%d): sendmsg failed for cipher operation : ", __FILE__,
  441. __LINE__);
  442. return 0;
  443. }
  444. if (sbytes != (ssize_t) inl) {
  445. ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
  446. inl);
  447. return 0;
  448. }
  449. # endif
  450. return 1;
  451. }
  452. static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
  453. const unsigned char *iv, int enc)
  454. {
  455. int ciphertype;
  456. int ret;
  457. afalg_ctx *actx;
  458. const char *ciphername;
  459. if (ctx == NULL || key == NULL) {
  460. ALG_WARN("%s(%d): Null Parameter\n", __FILE__, __LINE__);
  461. return 0;
  462. }
  463. if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
  464. ALG_WARN("%s(%d): Cipher object NULL\n", __FILE__, __LINE__);
  465. return 0;
  466. }
  467. actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
  468. if (actx == NULL) {
  469. ALG_WARN("%s(%d): Cipher data NULL\n", __FILE__, __LINE__);
  470. return 0;
  471. }
  472. ciphertype = EVP_CIPHER_CTX_nid(ctx);
  473. switch (ciphertype) {
  474. case NID_aes_128_cbc:
  475. case NID_aes_192_cbc:
  476. case NID_aes_256_cbc:
  477. ciphername = "cbc(aes)";
  478. break;
  479. default:
  480. ALG_WARN("%s(%d): Unsupported Cipher type %d\n", __FILE__, __LINE__,
  481. ciphertype);
  482. return 0;
  483. }
  484. if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
  485. ALG_WARN("%s(%d): Unsupported IV length :%d\n", __FILE__, __LINE__,
  486. EVP_CIPHER_CTX_iv_length(ctx));
  487. return 0;
  488. }
  489. /* Setup AFALG socket for crypto processing */
  490. ret = afalg_create_sk(actx, "skcipher", ciphername);
  491. if (ret < 1)
  492. return 0;
  493. ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
  494. if (ret < 1)
  495. goto err;
  496. /* Setup AIO ctx to allow async AFALG crypto processing */
  497. if (afalg_init_aio(&actx->aio) == 0)
  498. goto err;
  499. # ifdef ALG_ZERO_COPY
  500. pipe(actx->zc_pipe);
  501. # endif
  502. actx->init_done = MAGIC_INIT_NUM;
  503. return 1;
  504. err:
  505. close(actx->sfd);
  506. close(actx->bfd);
  507. return 0;
  508. }
  509. static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
  510. const unsigned char *in, size_t inl)
  511. {
  512. afalg_ctx *actx;
  513. int ret;
  514. char nxtiv[ALG_AES_IV_LEN] = { 0 };
  515. if (ctx == NULL || out == NULL || in == NULL) {
  516. ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
  517. __LINE__);
  518. return 0;
  519. }
  520. actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
  521. if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
  522. ALG_WARN("%s afalg ctx passed\n",
  523. ctx == NULL ? "NULL" : "Uninitialised");
  524. return 0;
  525. }
  526. /*
  527. * set iv now for decrypt operation as the input buffer can be
  528. * overwritten for inplace operation where in = out.
  529. */
  530. if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
  531. memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
  532. }
  533. /* Send input data to kernel space */
  534. ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
  535. EVP_CIPHER_CTX_iv(ctx),
  536. EVP_CIPHER_CTX_encrypting(ctx));
  537. if (ret < 1) {
  538. return 0;
  539. }
  540. /* Perform async crypto operation in kernel space */
  541. ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
  542. if (ret < 1)
  543. return 0;
  544. if (EVP_CIPHER_CTX_encrypting(ctx)) {
  545. memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
  546. ALG_AES_IV_LEN);
  547. } else {
  548. memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
  549. }
  550. return 1;
  551. }
  552. static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
  553. {
  554. afalg_ctx *actx;
  555. if (ctx == NULL) {
  556. ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
  557. __LINE__);
  558. return 0;
  559. }
  560. actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
  561. if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
  562. ALG_WARN("%s afalg ctx passed\n",
  563. ctx == NULL ? "NULL" : "Uninitialised");
  564. return 0;
  565. }
  566. close(actx->sfd);
  567. close(actx->bfd);
  568. # ifdef ALG_ZERO_COPY
  569. close(actx->zc_pipe[0]);
  570. close(actx->zc_pipe[1]);
  571. # endif
  572. /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
  573. if (actx->aio.mode == MODE_SYNC)
  574. close(actx->aio.efd);
  575. io_destroy(actx->aio.aio_ctx);
  576. return 1;
  577. }
  578. static cbc_handles *get_cipher_handle(int nid)
  579. {
  580. switch (nid) {
  581. case NID_aes_128_cbc:
  582. return &cbc_handle[AES_CBC_128];
  583. case NID_aes_192_cbc:
  584. return &cbc_handle[AES_CBC_192];
  585. case NID_aes_256_cbc:
  586. return &cbc_handle[AES_CBC_256];
  587. default:
  588. return NULL;
  589. }
  590. }
  591. static const EVP_CIPHER *afalg_aes_cbc(int nid)
  592. {
  593. cbc_handles *cipher_handle = get_cipher_handle(nid);
  594. if (cipher_handle == NULL)
  595. return NULL;
  596. if (cipher_handle->_hidden == NULL
  597. && ((cipher_handle->_hidden =
  598. EVP_CIPHER_meth_new(nid,
  599. AES_BLOCK_SIZE,
  600. cipher_handle->key_size)) == NULL
  601. || !EVP_CIPHER_meth_set_iv_length(cipher_handle->_hidden,
  602. AES_IV_LEN)
  603. || !EVP_CIPHER_meth_set_flags(cipher_handle->_hidden,
  604. EVP_CIPH_CBC_MODE |
  605. EVP_CIPH_FLAG_DEFAULT_ASN1)
  606. || !EVP_CIPHER_meth_set_init(cipher_handle->_hidden,
  607. afalg_cipher_init)
  608. || !EVP_CIPHER_meth_set_do_cipher(cipher_handle->_hidden,
  609. afalg_do_cipher)
  610. || !EVP_CIPHER_meth_set_cleanup(cipher_handle->_hidden,
  611. afalg_cipher_cleanup)
  612. || !EVP_CIPHER_meth_set_impl_ctx_size(cipher_handle->_hidden,
  613. sizeof(afalg_ctx)))) {
  614. EVP_CIPHER_meth_free(cipher_handle->_hidden);
  615. cipher_handle->_hidden= NULL;
  616. }
  617. return cipher_handle->_hidden;
  618. }
  619. static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
  620. const int **nids, int nid)
  621. {
  622. int r = 1;
  623. if (cipher == NULL) {
  624. *nids = afalg_cipher_nids;
  625. return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
  626. }
  627. switch (nid) {
  628. case NID_aes_128_cbc:
  629. case NID_aes_192_cbc:
  630. case NID_aes_256_cbc:
  631. *cipher = afalg_aes_cbc(nid);
  632. break;
  633. default:
  634. *cipher = NULL;
  635. r = 0;
  636. }
  637. return r;
  638. }
  639. static int bind_afalg(ENGINE *e)
  640. {
  641. /* Ensure the afalg error handling is set up */
  642. unsigned short i;
  643. ERR_load_AFALG_strings();
  644. if (!ENGINE_set_id(e, engine_afalg_id)
  645. || !ENGINE_set_name(e, engine_afalg_name)
  646. || !ENGINE_set_destroy_function(e, afalg_destroy)
  647. || !ENGINE_set_init_function(e, afalg_init)
  648. || !ENGINE_set_finish_function(e, afalg_finish)) {
  649. AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
  650. return 0;
  651. }
  652. /*
  653. * Create _hidden_aes_xxx_cbc by calling afalg_aes_xxx_cbc
  654. * now, as bind_aflag can only be called by one thread at a
  655. * time.
  656. */
  657. for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
  658. if (afalg_aes_cbc(afalg_cipher_nids[i]) == NULL) {
  659. AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
  660. return 0;
  661. }
  662. }
  663. if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
  664. AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
  665. return 0;
  666. }
  667. return 1;
  668. }
  669. # ifndef OPENSSL_NO_DYNAMIC_ENGINE
  670. static int bind_helper(ENGINE *e, const char *id)
  671. {
  672. if (id && (strcmp(id, engine_afalg_id) != 0))
  673. return 0;
  674. if (!afalg_chk_platform())
  675. return 0;
  676. if (!bind_afalg(e))
  677. return 0;
  678. return 1;
  679. }
  680. IMPLEMENT_DYNAMIC_CHECK_FN()
  681. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
  682. # endif
  683. static int afalg_chk_platform(void)
  684. {
  685. int ret;
  686. int i;
  687. int kver[3] = { -1, -1, -1 };
  688. int sock;
  689. char *str;
  690. struct utsname ut;
  691. ret = uname(&ut);
  692. if (ret != 0) {
  693. AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
  694. AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
  695. return 0;
  696. }
  697. str = strtok(ut.release, ".");
  698. for (i = 0; i < 3 && str != NULL; i++) {
  699. kver[i] = atoi(str);
  700. str = strtok(NULL, ".");
  701. }
  702. if (KERNEL_VERSION(kver[0], kver[1], kver[2])
  703. < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
  704. ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
  705. kver[0], kver[1], kver[2]);
  706. ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
  707. K_MAJ, K_MIN1, K_MIN2);
  708. AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
  709. AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
  710. return 0;
  711. }
  712. /* Test if we can actually create an AF_ALG socket */
  713. sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
  714. if (sock == -1) {
  715. AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
  716. return 0;
  717. }
  718. close(sock);
  719. return 1;
  720. }
  721. # ifdef OPENSSL_NO_DYNAMIC_ENGINE
  722. static ENGINE *engine_afalg(void)
  723. {
  724. ENGINE *ret = ENGINE_new();
  725. if (ret == NULL)
  726. return NULL;
  727. if (!bind_afalg(ret)) {
  728. ENGINE_free(ret);
  729. return NULL;
  730. }
  731. return ret;
  732. }
  733. void engine_load_afalg_int(void)
  734. {
  735. ENGINE *toadd;
  736. if (!afalg_chk_platform())
  737. return;
  738. toadd = engine_afalg();
  739. if (toadd == NULL)
  740. return;
  741. ERR_set_mark();
  742. ENGINE_add(toadd);
  743. /*
  744. * If the "add" worked, it gets a structural reference. So either way, we
  745. * release our just-created reference.
  746. */
  747. ENGINE_free(toadd);
  748. /*
  749. * If the "add" didn't work, it was probably a conflict because it was
  750. * already added (eg. someone calling ENGINE_load_blah then calling
  751. * ENGINE_load_builtin_engines() perhaps).
  752. */
  753. ERR_pop_to_mark();
  754. }
  755. # endif
  756. static int afalg_init(ENGINE *e)
  757. {
  758. return 1;
  759. }
  760. static int afalg_finish(ENGINE *e)
  761. {
  762. return 1;
  763. }
  764. static int free_cbc(void)
  765. {
  766. short unsigned int i;
  767. for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
  768. EVP_CIPHER_meth_free(cbc_handle[i]._hidden);
  769. cbc_handle[i]._hidden = NULL;
  770. }
  771. return 1;
  772. }
  773. static int afalg_destroy(ENGINE *e)
  774. {
  775. ERR_unload_AFALG_strings();
  776. free_cbc();
  777. return 1;
  778. }
  779. #endif /* KERNEL VERSION */