Debian Codegraph @

apps/kcapi-enc.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2017 - 2022, Stephan Mueller <[email protected]>
3 *
4 * License: see LICENSE file in root directory
5 *
6 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
7 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
8 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
9 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
10 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
11 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
12 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
13 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
14 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
16 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 */
19
20 #define _GNU_SOURCE
21 #include <stdio.h>
22 #include <sys/mman.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <stdlib.h>
31 #include <getopt.h>
32 #include <limits.h>
33
34 #include "app-internal.h"
35
36 #define TAGBUFLEN 16
37
38 struct opt_data {
39 const char *infile;
40 const char *outfile;
41 const char *ciphername;
42 const char *iv;
43 const char *ccmnonce;
44 const char *aad;
45 const char *tag;
46 const char *passwd;
47 const char *salt;
48 const char *pbkdf_hash;
49 int password_fd;
50 int key_fd;
51 uint32_t pbkdf_iterations;
52 uint32_t taglen;
53 uint32_t aadlen;
54 bool decrypt;
55 bool nounpad;
56 bool removetag;
57 int (*func_init)(struct kcapi_handle **handle, const char *ciphername,
58 uint32_t flags);
59 void (*func_destroy)(struct kcapi_handle *handle);
60 int (*func_setkey)(struct kcapi_handle *handle,
61 const uint8_t *key, uint32_t keylen);
62 ssize_t (*func_stream_init_enc)(struct kcapi_handle *handle,
63 const uint8_t *iv,
64 struct iovec *iov, size_t iovlen);
65 ssize_t (*func_stream_init_dec)(struct kcapi_handle *handle,
66 const uint8_t *iv,
67 struct iovec *iov, size_t iovlen);
68 ssize_t (*func_stream_update)(struct kcapi_handle *handle,
69 struct iovec *iov, size_t iovlen);
70 ssize_t (*func_stream_update_last)(struct kcapi_handle *handle,
71 struct iovec *iov, size_t iovlen);
72 ssize_t (*func_stream_op)(struct kcapi_handle *handle,
73 struct iovec *iov, size_t iovlen);
74 uint32_t (*func_blocksize)(struct kcapi_handle *handle);
75 };
76
77 static ssize_t return_data_stdout(struct kcapi_handle *handle,
78 struct opt_data *opts, size_t outsize)
79 {
80 struct iovec outiov;
81 uint8_t tmpbuf[TMPBUFLEN] __aligned(KCAPI_APP_ALIGN);
82 ssize_t ret = 0;
83 ssize_t generated_bytes = 0;
84
85 /*
86 * Generate output data in a tmp buffer and then dump it.
87 */
88 while (outsize > 0) {
89 /* length of the input data */
90 size_t inlen = outsize < TMPBUFLEN ? outsize : TMPBUFLEN;
91 /* length of the output data */
92 size_t outlen = inlen;
93 uint8_t *tmpbufptr = tmpbuf;
94
95 outiov.iov_base = tmpbuf;
96 outiov.iov_len = inlen;
97 ret = opts->func_stream_op(handle, &outiov, 1);
98 if (ret < 0)
99 goto out;
100 generated_bytes += ret;
101
102 /*
103 * If we have to remove the tag, simply reduce
104 * number of bytes to be written to stdout as the tag
105 * is the trailing part of the memory.
106 */
107 if (opts->removetag) {
108 outlen -= opts->taglen;
109 generated_bytes -= (ssize_t)opts->taglen;
110
111 dolog(KCAPI_LOG_DEBUG,
112 "remove %u bytes of unused but generated tag",
113 opts->taglen);
114 }
115
116 /* write the data */
117 if (fwrite(tmpbufptr, sizeof(char), outlen, stdout) != outlen) {
118 dolog(KCAPI_LOG_ERR, "Write failed %d", -errno);
119 ret = -errno;
120 goto out;
121 }
122 outsize -= inlen;
123 }
124
125 /*
126 * We cannot remove padding as we do not know when the last
127 * block is processed.
128 */
129 dolog(KCAPI_LOG_VERBOSE, "Removal of padding disabled");
130
131 out:
132 return (ret < 0) ? ret : generated_bytes;
133 }
134
135 static ssize_t return_data_fd(struct kcapi_handle *handle,
136 struct opt_data *opts,
137 int outfd, size_t outsize, size_t offset,
138 uint32_t unpad)
139 {
140 struct iovec outiov;
141 size_t off_outsize = outsize + offset;
142 uint8_t *outmem;
143 ssize_t ret = 0;
144 ssize_t generated_bytes = 0;
145 uint8_t *off_ptr;
146
147 /* Map the file into memory. */
148 outmem = mmap(NULL, off_outsize, PROT_WRITE, MAP_SHARED,
149 outfd, 0);
150 if (outmem == MAP_FAILED) {
151 dolog(KCAPI_LOG_ERR, "Use of mmap for outfd failed");
152 return -ENOMEM;
153 }
154
155 off_ptr = outmem + offset;
156 outiov.iov_base = off_ptr;
157 outiov.iov_len = outsize;
158
159 /* Write the data. */
160 ret = opts->func_stream_op(handle, &outiov, 1);
161 if (ret < 0)
162 goto out;
163 generated_bytes += ret;
164
165 /* Padding is only removed for decryption */
166 if (!opts->decrypt)
167 goto out;
168
169 /* undo padding */
170 if (unpad && !opts->nounpad) {
171 uint8_t padbyte;
172
173 padbyte = *(off_ptr + generated_bytes - 1);
174
175 if ((uint32_t)padbyte < opts->func_blocksize(handle)) {
176 ssize_t i;
177 uint32_t padded = 1;
178
179 for (i = generated_bytes - 2;
180 i >= generated_bytes - (ssize_t)padbyte; i--) {
181 if (*(off_ptr + i) != padbyte) {
182 padded = 0;
183 break;
184 }
185 }
186
187 if (padded) {
188 dolog(KCAPI_LOG_DEBUG, "Unpad %d bytes",
189 (uint32_t)padbyte);
190
191 off_outsize -= (uint32_t)padbyte;
192
193 ret = ftruncate(outfd, (off_t)off_outsize);
194 if (ret)
195 goto out;
196
197 generated_bytes -= (ssize_t)padbyte;
198 }
199 }
200 } else
201 dolog(KCAPI_LOG_VERBOSE, "Removal of padding disabled");
202
203 /*
204 * Remove the trailing tag for older kernels by simply
205 * truncating the output file to the generated data size minus
206 * the tag value. As the tag is the trailing part of the data,
207 * it will be cleared.
208 */
209 if (opts->removetag) {
210 ret = ftruncate(outfd, (off_t)(off_outsize - opts->taglen));
211 if (ret)
212 goto out;
213 generated_bytes -= (ssize_t)opts->taglen;
214 dolog(KCAPI_LOG_DEBUG,
215 "remove %u bytes of unused but generated tag",
216 opts->taglen);
217 }
218
219 out:
220 munmap(outmem, outsize);
221 return (ret < 0) ? ret : generated_bytes;
222 }
223
224 static ssize_t return_data(struct kcapi_handle *handle, struct opt_data *opts,
225 int outfd, size_t outsize, size_t offset,
226 uint32_t unpad)
227 {
228 /* Tell kernel that we have sent all data */
229 ssize_t ret = opts->func_stream_update_last(handle, NULL, 0);
230 if (ret < 0)
231 return (int)ret;
232
233 /* send generated data to stdout */
234 if (outfd == STDOUT_FD)
235 return return_data_stdout(handle, opts, outsize);
236 /* Write to a file. */
237 else
238 return return_data_fd(handle, opts, outfd, outsize, offset,
239 unpad);
240 }
241
242 /**
243 * Get the output data size to be expected for the cipher operation given
244 * the input data size.
245 */
246 static size_t outbufsize(struct kcapi_handle *handle, struct opt_data *opts,
247 size_t datalen)
248 {
249 size_t outsize;
250
251 if (opts->aad) {
252 if (opts->decrypt) {
253 outsize = kcapi_aead_outbuflen_dec(handle, datalen,
254 opts->aadlen,
255 opts->taglen);
256
257 /*
258 * This is needed for kernels < 4.9: see the libkcapi
259 * documentation where the tag value is generated
260 * during decryption. As we do not want a zero tag,
261 * simply discard the tag during print out.
262 */
263 if (outsize == (datalen + opts->aadlen + opts->taglen))
264 opts->removetag = true;
265 } else
266 outsize = kcapi_aead_outbuflen_enc(handle, datalen,
267 opts->aadlen,
268 opts->taglen);
269 } else {
270 outsize = ((datalen + opts->func_blocksize(handle) - 1) /
271 opts->func_blocksize(handle)) *
272 opts->func_blocksize(handle);
273 }
274
275 dolog(KCAPI_LOG_DEBUG, "Data size expected to be generated: %lu",
276 outsize);
277
278 return outsize;
279 }
280
281 /*
282 * Send the tag value to the kernel for AEAD operations.
283 * This function also handles the interface change between kernels 4.8 and 4.9.
284 */
285 static int sendtag(struct kcapi_handle *handle, struct opt_data *opts,
286 uint8_t *tagbuf, uint8_t *tmptagbuf)
287 {
288 size_t outsize;
289 struct iovec iniov;
290 ssize_t ret;
291
292 /* If no AEAD operation, return immediately. */
293 if (!opts->aad)
294 return 0;
295
296 /* If we have a tag value, simply send it. */
297 if (tagbuf) {
298 iniov.iov_base = tagbuf;
299 iniov.iov_len = opts->taglen;
300
301 ret = opts->func_stream_update(handle, &iniov,
302 1);
303 if (ret < 0)
304 return (int)ret;
305
306 dolog(KCAPI_LOG_DEBUG, "Sent %u bytes of tag", opts->taglen);
307
308 return 0;
309 }
310
311 /*
312 * On kernels < 4.9, the outsize is always aadlen + data + taglen.
313 *
314 * For newer kernels, the outsize is aadlen + data + tag (encryption) or
315 * aadlen + data (decryption).
316 */
317 if (opts->decrypt)
318 outsize = kcapi_aead_inbuflen_dec(handle, 0, opts->aadlen,
319 opts->taglen);
320 else
321 outsize = kcapi_aead_inbuflen_enc(handle, 0, opts->aadlen,
322 opts->taglen);
323
324 if (outsize != (opts->aadlen + opts->taglen)) {
325 /* We have a newer kernel, do not do anything. */
326 return 0;
327 }
328
329 /*
330 * Send an empty buffer for a tag as required on kernels < 4.9 as
331 * documented for libkcapi.
332 */
333 if (TAGBUFLEN < opts->taglen) {
334 dolog(KCAPI_LOG_ERR, "Tag size %u too large\n", opts->taglen);
335 return -EINVAL;
336 }
337
338 memset(tmptagbuf, 0, opts->taglen);
339
340 iniov.iov_base = tmptagbuf;
341 iniov.iov_len = opts->taglen;
342 ret = opts->func_stream_update(handle, &iniov, 1);
343 if (ret < 0)
344 return (int)ret;
345
346 dolog(KCAPI_LOG_DEBUG, "Sent %u bytes of null tag", opts->taglen);
347
348 return 0;
349 }
350
351 /**
352 * Add the padding data to ensure that for a cipher operation, the input
353 * data is multiples of the cipher's block size.
354 */
355 static int add_padding(struct kcapi_handle *handle, struct opt_data *opts,
356 uint8_t *padbuf, size_t outsize, size_t currblock)
357 {
358 size_t padsize = 0;
359
360 if (opts->aad)
361 return 0;
362
363 if (opts->decrypt)
364 return 0;
365
366 if (outsize > currblock) {
367 struct iovec iniov;
368 ssize_t ret = 0;
369
370 padsize = outsize - currblock;
371 memset(padbuf, (uint8_t)padsize, padsize);
372
373 /*
374 * WARNING: we cannot use a local buffer here, because when
375 * splicing the data, the data is first accessed from user space
376 * upon recvmsg. Thus, the buffer with the pad data must be
377 * alive until the recvmsg is invoked.
378 */
379 iniov.iov_base = padbuf;
380 iniov.iov_len = padsize;
381 ret = opts->func_stream_update(handle, &iniov, 1);
382 if (ret < 0)
383 return (int)ret;
384
385 dolog_bin(KCAPI_LOG_DEBUG, iniov.iov_base,
386 (uint32_t)iniov.iov_len, "Padding contents");
387 dolog(KCAPI_LOG_VERBOSE, "Padding of %u bytes applied",
388 iniov.iov_len);
389 }
390
391 return (int)padsize;
392 }
393
394 /**
395 * Perform the requested cipher operation.
396 *
397 * The cipher handle must already have the key set.
398 */
399 static int cipher_op(struct kcapi_handle *handle, struct opt_data *opts)
400 {
401 int infd = -1, outfd = -1;
402 ssize_t ret = 0;
403 unsigned int generated_bytes = 0;
404 struct stat insb, outsb;
405 uint8_t *inmem = NULL;
406 size_t outsize = 0;
407 struct iovec iniov;
408 uint8_t *ivbuf = NULL;
409 uint32_t ivbuflen = 0;
410 char tmpbuf[TMPBUFLEN] __aligned(KCAPI_APP_ALIGN);
411
412 uint8_t *aadbuf = NULL;
413 uint8_t *tagbuf = NULL;
414 uint8_t padbuf[32] __aligned(KCAPI_APP_ALIGN);
415 uint8_t tagtmpbuf[TAGBUFLEN] __aligned(KCAPI_APP_ALIGN);
416
417 unsigned int maxdata;
418
419 /*
420 * To avoid spurious padding, the buffer must be multiples of the
421 * block size.
422 */
423 BUILD_BUG_ON(TMPBUFLEN % 32);
424
425 if (opts->iv) {
426 uint8_t *newiv = NULL;
427 uint32_t newivlen;
428
429 ret = hex2bin_alloc(opts->iv, (uint32_t)strlen(opts->iv),
430 &ivbuf, &ivbuflen);
431 if (ret)
432 goto out;
433
434 /* generate the padded IV */
435 if (ivbuflen != opts->func_blocksize(handle)) {
436 ret = kcapi_pad_iv(handle, ivbuf, ivbuflen,
437 &newiv, &newivlen);
438 if (ret)
439 goto out;
440
441 free(ivbuf);
442 ivbuf = newiv;
443 ivbuflen = newivlen;
444
445 dolog_bin(KCAPI_LOG_DEBUG, ivbuf, ivbuflen,
446 "Padded IV");
447 }
448
449 } else if (opts->ccmnonce) {
450 uint8_t *nonce;
451 uint32_t noncelen;
452
453 /* Convert a CCM nonce into an IV. */
454 ret = hex2bin_alloc(opts->ccmnonce,
455 (uint32_t)strlen(opts->ccmnonce),
456 &nonce, &noncelen);
457 if (ret)
458 goto out;
459
460 ret = kcapi_aead_ccm_nonce_to_iv(nonce, noncelen,
461 &ivbuf, &ivbuflen);
462 free(nonce);
463 if (ret)
464 goto out;
465
466 dolog(KCAPI_LOG_DEBUG,
467 "CCM nonce (%u bytes) convereted to IV (%u bytes)",
468 noncelen, ivbuflen);
469 dolog_bin(KCAPI_LOG_DEBUG, ivbuf, ivbuflen,
470 "CCM nonce converted to IV");
471 }
472
473 /* AEAD specific code */
474 if (opts->aad) {
475 ret = hex2bin_alloc(opts->aad, (uint32_t)strlen(opts->aad),
476 &aadbuf, &opts->aadlen);
477 if (ret)
478 goto out;
479
480 /* Set AAD length. */
481 kcapi_aead_setassoclen(handle, opts->aadlen);
482 dolog(KCAPI_LOG_DEBUG, "Set AAD length to %u bytes",
483 opts->aadlen);
484
485 if (opts->tag) {
486 ret = hex2bin_alloc(opts->tag,
487 (uint32_t)strlen(opts->tag),
488 &tagbuf, &opts->taglen);
489 if (ret)
490 goto out;
491 }
492
493 /* Set tag length. */
494 if (opts->taglen) {
495 ret = kcapi_aead_settaglen(handle, opts->taglen);
496 if (ret)
497 goto out;
498
499 dolog(KCAPI_LOG_DEBUG, "Set tag length to %u bytes",
500 opts->taglen);
501 }
502 }
503
504 /* Access input data. */
505 if (opts->infile) {
506 infd = open(opts->infile, O_RDONLY | O_CLOEXEC);
507 if (infd < 0) {
508 dolog(KCAPI_LOG_ERR, "Cannot open file %s: %s",
509 opts->infile, strerror(errno));
510 ret = -EIO;
511 goto out;
512 }
513 ret = check_filetype(infd, &insb, opts->infile);
514 if (ret)
515 goto out;
516 } else
517 infd = STDIN_FD;
518
519 /* Access output location */
520 if (opts->outfile) {
521 outfd = open(opts->outfile, O_RDWR | O_CLOEXEC | O_CREAT,
522 S_IRWXU | S_IRWXG | S_IRWXO);
523 if (outfd < 0) {
524 dolog(KCAPI_LOG_ERR, "Cannot open file %s: %s",
525 opts->outfile, strerror(errno));
526 ret = -EIO;
527 goto out;
528 }
529
530 ret = check_filetype(outfd, &outsb, opts->outfile);
531 if (ret)
532 goto out;
533 } else
534 outfd = STDOUT_FD;
535
536 /* Initialize cipher operation */
537 if (opts->decrypt)
538 ret = opts->func_stream_init_dec(handle, ivbuf, NULL, 0);
539 else
540 ret = opts->func_stream_init_enc(handle, ivbuf, NULL, 0);
541 if (ret)
542 goto out;
543
544 /* Send AAD in case we have it */
545 if (aadbuf) {
546 iniov.iov_base = aadbuf;
547 iniov.iov_len = opts->aadlen;
548
549 ret = opts->func_stream_update(handle, &iniov, 1);
550 if (ret < 0)
551 goto out;
552
553 dolog(KCAPI_LOG_DEBUG, "Sent %u bytes of AAD",
554 opts->aadlen);
555 }
556
557 ret = kcapi_get_maxsplicesize(handle);
558 if (ret < 0)
559 goto out;
560 maxdata = (unsigned int)ret;
561
562 /* Get data from stdin. */
563 if (infd == STDIN_FD) {
564 bool data_sent = false;
565
566 iniov.iov_base = tmpbuf;
567 while ((iniov.iov_len =
568 fread(tmpbuf, sizeof(uint8_t), TMPBUFLEN, stdin))) {
569
570 /* WARNING: with AEAD, only one loop is possible */
571 if (opts->aad && data_sent) {
572 dolog(KCAPI_LOG_ERR,
573 "Kernel is unable to receive AEAD data in chunks, send all AEAD data in one operation using a file (max numbers of bytes for STDIN is %u)\n",
574 TMPBUFLEN);
575 ret = -EOVERFLOW;
576 goto out;
577 }
578
579 ret = opts->func_stream_update(handle, &iniov, 1);
580 if (ret < 0)
581 goto out;
582
583 outsize = outbufsize(handle, opts,
584 (uint32_t)iniov.iov_len);
585 ret = sendtag(handle, opts, tagbuf, tagtmpbuf);
586 if (ret)
587 goto out;
588
589 if (outfd != STDOUT_FD) {
590 ret = ftruncate(outfd,
591 (off_t)(generated_bytes + outsize));
592 if (ret)
593 goto out;
594 }
595
596 /* padding */
597 ret = add_padding(handle, opts, padbuf,
598 outsize, (uint32_t)iniov.iov_len);
599 if (ret < 0)
600 goto out;
601
602 ret = return_data(handle, opts, outfd, outsize,
603 generated_bytes, 0);
604 if (ret < 0)
605 goto out;
606
607 generated_bytes += (unsigned int)ret;
608 }
609
610 /* Get data from file. */
611 } else {
612 uint32_t sent_data = 0;
613
614 inmem = mmap(NULL, (size_t)insb.st_size, PROT_READ, MAP_SHARED,
615 infd, 0);
616 if (inmem == MAP_FAILED) {
617 dolog(KCAPI_LOG_ERR, "Use of mmap for infd failed");
618 ret = -ENOMEM;
619 goto out;
620 }
621
622 if (outfd != STDOUT_FD && insb.st_size) {
623 uint8_t padbyte;
624
625 outsize = outbufsize(handle, opts,
626 (uint32_t)insb.st_size);
627 ret = ftruncate(outfd, (off_t)outsize);
628 if (ret)
629 goto out;
630
631 padbyte = *(inmem + insb.st_size - 1);
632
633 /*
634 * Warn if trailing bytes look like padding although
635 * we will not apply padding.
636 */
637 if (!opts->decrypt &&
638 !(insb.st_size % opts->func_blocksize(handle)) &&
639 (uint32_t)padbyte < opts->func_blocksize(handle)) {
640 uint32_t i;
641 uint32_t padded = 1;
642
643 for (i = (uint32_t)insb.st_size - 2;
644 i >= insb.st_size - (uint32_t)padbyte;
645 i--) {
646 if (*(inmem + i) != padbyte) {
647 padded = 0;
648 break;
649 }
650 }
651
652 if (padded &&
653 ((uint64_t)insb.st_size ==
654 (i + (uint32_t)padbyte) + 1)) {
655 dolog(KCAPI_LOG_WARN,
656 "Input file's trailing bytes will be treated as padding during decryption unless you turn off padding handling with --nounpad\n");
657 }
658 }
659 }
660
661 while (sent_data < (uint64_t)insb.st_size) {
662 uint32_t avail = (uint32_t)insb.st_size - sent_data;
663 uint32_t todo = avail > maxdata ? maxdata : avail;
664
665 if (opts->aad && avail > todo) {
666 dolog(KCAPI_LOG_VERBOSE,
667 "Increase pipeseize for AEAD operation to %u\n",
668 avail);
669
670 ret = kcapi_set_maxsplicesize(handle, avail);
671 if (ret < 0)
672 goto out;
673 todo = avail;
674 }
675
676 iniov.iov_base = inmem + sent_data;
677 iniov.iov_len = todo;
678 ret = opts->func_stream_update(handle, &iniov, 1);
679 if (ret < 0)
680 goto out;
681
682 outsize = outbufsize(handle, opts,
683 (uint32_t)iniov.iov_len);
684
685 ret = sendtag(handle, opts, tagbuf, tagtmpbuf);
686 if (ret)
687 goto out;
688
689 /* padding */
690 ret = add_padding(handle, opts, padbuf,
691 outsize, (uint32_t)iniov.iov_len);
692 if (ret < 0)
693 goto out;
694
695 ret = return_data(handle, opts, outfd, outsize,
696 generated_bytes, outsize == avail);
697 if (ret < 0)
698 goto out;
699
700 generated_bytes += (unsigned int)ret;
701 sent_data += todo;
702 }
703 }
704
705 out:
706 if (inmem && inmem != MAP_FAILED)
707 munmap(inmem, (size_t)insb.st_size);
708
709 if (ivbuf)
710 free(ivbuf);
711 if (tagbuf)
712 free(tagbuf);
713 if (aadbuf)
714 free(aadbuf);
715
716 if (infd >= 0 && infd != STDIN_FD)
717 close(infd);
718 if (outfd >= 0 && outfd != STDOUT_FD)
719 close(outfd);
720
721 return (ret < 0) ? (int)ret : (int)generated_bytes;
722 }
723
724 /**
725 * Set the key for a cipher operation. This function potentially derives
726 * the key from a given passphrase.
727 */
728 static int set_key(struct kcapi_handle *handle, struct opt_data *opts)
729 {
730 uint8_t passwdbuf[128] __aligned(KCAPI_APP_ALIGN);
731 uint32_t passwdlen = 0;
732 uint8_t keybuf[32] __aligned(KCAPI_APP_ALIGN);
733 uint32_t keybuflen = 0;
734 int have_key = 0;
735 const uint8_t *passwdptr = NULL;
736 ssize_t ret;
737
738 /* Get password from command line */
739 if (opts->passwd) {
740 passwdptr = (uint8_t *)opts->passwd;
741 passwdlen = (uint32_t)strlen(opts->passwd);
742 }
743
744 /* Get password from password FD */
745 if (opts->password_fd != -1) {
746 ret = read_complete(opts->password_fd, passwdbuf,
747 sizeof(passwdbuf));
748 if (ret < 0)
749 goto out;
750
751 passwdbuf[sizeof(passwdbuf) - 1] = '\0';
752 passwdptr = passwdbuf;
753 passwdlen = (uint32_t)ret;
754 }
755
756 /* Transform password into a key using PBKDF2. */
757 if (passwdptr && passwdlen) {
758 uint8_t *saltbuf = NULL;
759 uint32_t saltbuflen = 0;
760
761 dolog(KCAPI_LOG_DEBUG, "password %s", passwdptr);
762
763 /* Determine the number of PBKDF2 iterations. */
764 if (!opts->pbkdf_iterations) {
765 opts->pbkdf_iterations =
766 kcapi_pbkdf_iteration_count(opts->pbkdf_hash, 0);
767
768 dolog(KCAPI_LOG_WARN, "PBKDF2 iterations used: %u",
769 opts->pbkdf_iterations);
770 }
771
772 /* Convert the salt hex representation into binary. */
773 if (opts->salt) {
774 ret = hex2bin_alloc(opts->salt,
775 (uint32_t)strlen(opts->salt),
776 &saltbuf, &saltbuflen);
777 if (ret)
778 goto out;
779 } else {
780 /* No salt provided, generate a random number. */
781 struct kcapi_handle *rng;
782 uint32_t j = 0;
783
784 ret = kcapi_rng_init(&rng, "stdrng", 0);
785 if (ret)
786 goto out;
787 ret = kcapi_rng_seed(rng, NULL, 0);
788 if (ret) {
789 kcapi_rng_destroy(rng);
790 goto out;
791 }
792
793 saltbuflen = 32;
794 saltbuf = malloc(saltbuflen);
795 if (!saltbuf) {
796 ret = -ENOMEM;
797 kcapi_rng_destroy(rng);
798 goto out;
799 }
800
801 while (j < saltbuflen) {
802 ret = kcapi_rng_generate(rng, saltbuf,
803 saltbuflen);
804 if (ret < 0) {
805 kcapi_rng_destroy(rng);
806 free(saltbuf);
807 goto out;
808 }
809 j += (uint32_t)ret;
810 }
811 kcapi_rng_destroy(rng);
812
813 dolog_bin(KCAPI_LOG_WARN, saltbuf, saltbuflen,
814 "PBKDF2 salt used");
815 }
816
817 /*
818 * PBKDF2 operation: generate a key from password --
819 * reading of sizeof(keybuf) implies 256 bit key.
820 */
821 ret = kcapi_pbkdf(opts->pbkdf_hash, passwdptr, passwdlen,
822 saltbuf, saltbuflen, opts->pbkdf_iterations,
823 keybuf, sizeof(keybuf));
824 free(saltbuf);
825 if (ret)
826 goto out;
827
828 have_key = 1;
829 keybuflen = sizeof(keybuf);
830
831 dolog(KCAPI_LOG_VERBOSE,
832 "Data Encryption Key derived from Password using PBKDF2 using %s with %u iterations",
833 opts->pbkdf_hash, opts->pbkdf_iterations);
834 }
835
836 /* Get key from key FD */
837 if (opts->key_fd != -1) {
838 ret = read_complete(opts->key_fd, keybuf, sizeof(keybuf));
839 if (ret < 0)
840 goto out;
841
842 have_key = 1;
843 keybuflen = (uint32_t)ret;
844 }
845
846 if (!have_key) {
847 dolog(KCAPI_LOG_ERR, "No key found in input data");
848 ret = -EINVAL;
849 goto out;
850 }
851
852 dolog_bin(KCAPI_LOG_DEBUG, keybuf, keybuflen, "data-encryption-key");
853
854 /* Set the key for the key handle. */
855 ret = opts->func_setkey(handle, keybuf, keybuflen);
856
857 out:
858 kcapi_memset_secure(passwdbuf, 0, sizeof(passwdbuf));
859 kcapi_memset_secure(keybuf, 0, sizeof(keybuf));
860
861 return (int)ret;
862 }
863
864 static void usage(void)
865 {
866 char version[30];
867 uint32_t ver = kcapi_version();
868
869 memset(version, 0, sizeof(version));
870 kcapi_versionstring(version, sizeof(version));
871
872 fprintf(stderr, "\nKernel Crypto API Symmetric Crypto Helper\n");
873 fprintf(stderr, "\nKernel Crypto API interface library version: %s\n", version);
874 fprintf(stderr, "Reported numeric version number %u\n\n", ver);
875 fprintf(stderr, "Usage:\n");
876 fprintf(stderr, "\t-c --cipher <NAME>\tCipher name to use for crypto operation\n");
877 fprintf(stderr, "\t-e --encrypt\t\tEncryption operation (default)\n");
878 fprintf(stderr, "\t-d --decrypt\t\tDecryption operation\n");
879 fprintf(stderr, "\t-i --infile <FILE>\tFile with input data\n");
880 fprintf(stderr, "\t-o --outfile <FILE>\tFile with output data\n");
881 fprintf(stderr, "\t --iv <IV>\t\tIV for cipher operation\n");
882 fprintf(stderr, "\t --aad <AAD>\t\tAAD for AEAD cipher operation\n");
883 fprintf(stderr, "\t --tag <TAG>\t\tTag for AEAD decryption operation\n");
884 fprintf(stderr, "\t --taglen <BYTES>\tTag length to be generated AEAD encryption\n");
885 fprintf(stderr, "\t --ccm-nonce <NONCE>\tCCM nonce (instead of IV)\n");
886 fprintf(stderr, "\t\t\t\toperation\n");
887 fprintf(stderr, "\t-s --salt <SALT>\tSalt for PBKDF2\n");
888 fprintf(stderr, "\t-p --passwd <PWD>\tPassword the session key is derived from using\n");
889 fprintf(stderr, "\t\t\t\tPBKDF2\n");
890 fprintf(stderr, "\t --passwdfd <FD>\tPassword file descriptor providing password\n");
891 fprintf(stderr, "\t --pbkdfiter <NUM>\tNumber of PBKDF2 iterations\n");
892 fprintf(stderr, "\t --pbkdfmac <MAC>\tMac for PBKDF2 (default: hmac(sha256))\n");
893 fprintf(stderr, "\t --keyfd <FD>\t\tKey file descriptor providing password\n");
894 fprintf(stderr, "\t --nounpad\t\tDo not unpad output file\n");
895 fprintf(stderr, "\t-h --help\t\tThis help information\n");
896 fprintf(stderr, "\t --version\t\tPrint version\n");
897 fprintf(stderr, "\t-v --verbose\t\tVerbose logging, multiple options increase\n");
898 fprintf(stderr, "\t\t\t\tverbosity\n");
899 fprintf(stderr, "\t-q --quiet\t\tNo informational output - quiet operation\n");
900 fprintf(stderr, "\nData provided at stdin is encrypted or decrypted\n");
901 fprintf(stderr, "Data output at stdout\n");
902
903 exit(1);
904 }
905
906 static void parse_opts(int argc, char *argv[], struct opt_data *opts)
907 {
908 int c = 0;
909 char version[30];
910 unsigned long val = 0;
911 uint32_t verbosity = KCAPI_LOG_WARN;
912
913 memset(opts, 0, sizeof(*opts));
914 opts->password_fd = -1;
915 opts->key_fd = -1;
916
917 while (1) {
918 int opt_index = 0;
919 static struct option options[] = {
920 {"cipher", required_argument, 0, 'c'},
921 {"encrypt", no_argument, 0, 'e'},
922 {"decrypt", no_argument, 0, 'd'},
923 {"infile", required_argument, 0, 'i'},
924 {"outfile", required_argument, 0, 'o'},
925 {"iv", required_argument, 0, 0},
926 {"aad", required_argument, 0, 0},
927 {"tag", required_argument, 0, 0},
928 {"taglen", required_argument, 0, 0},
929 {"ccm-nonce", required_argument, 0, 0},
930 {"salt", required_argument, 0, 's'},
931 {"passwd", required_argument, 0, 'p'},
932 {"passwdfd", required_argument, 0, 0},
933 {"pbkdfiter", required_argument, 0, 0},
934 {"pbkdfmac", required_argument, 0, 0},
935 {"keyfd", required_argument, 0, 0},
936 {"nounpad", no_argument, 0, 0},
937
938 {"verbose", no_argument, 0, 'v'},
939 {"quiet", no_argument, 0, 'q'},
940 {"help", no_argument, 0, 'h'},
941 {"version", no_argument, 0, 0},
942 {0, 0, 0, 0}
943 };
944 c = getopt_long(argc, argv, "c:edi:o:s:p:vqh",
945 options, &opt_index);
946 if (-1 == c)
947 break;
948 switch (c) {
949 case 0:
950 switch (opt_index) {
951 case 0:
952 opts->ciphername = optarg;
953 break;
954 case 1:
955 opts->decrypt = false;
956 break;
957 case 2:
958 opts->decrypt = true;
959 break;
960 case 3:
961 opts->infile = optarg;
962 break;
963 case 4:
964 opts->outfile = optarg;
965 break;
966 case 5:
967 opts->iv = optarg;
968 break;
969 case 6:
970 opts->aad = optarg;
971 break;
972 case 7:
973 opts->tag = optarg;
974 break;
975 case 8:
976 val = strtoul(optarg, NULL, 10);
977 if (val == UINT_MAX) {
978 dolog(KCAPI_LOG_ERR,
979 "Tag length value too big");
980 usage();
981 }
982 opts->taglen = (uint32_t)val;
983 break;
984 case 9:
985 opts->ccmnonce = optarg;
986 break;
987 case 10:
988 opts->salt = optarg;
989 break;
990 case 11:
991 opts->passwd = optarg;
992 break;
993 case 12:
994 val = strtoul(optarg, NULL, 10);
995 if (val == UINT_MAX) {
996 dolog(KCAPI_LOG_ERR,
997 "Passwd FD value too big");
998 usage();
999 }
1000 opts->password_fd = (int)val;
1001 break;
1002 case 13:
1003 val = strtoul(optarg, NULL, 10);
1004 if (val == UINT_MAX) {
1005 dolog(KCAPI_LOG_ERR,
1006 "PBKDF2 iteration value too big");
1007 usage();
1008 }
1009 opts->pbkdf_iterations = (uint32_t)val;
1010 break;
1011 case 14:
1012 opts->pbkdf_hash = optarg;
1013 break;
1014 case 15:
1015 val = strtoul(optarg, NULL, 10);
1016 if (val == UINT_MAX) {
1017 dolog(KCAPI_LOG_ERR,
1018 "Passwd FD value too big");
1019 usage();
1020 }
1021 opts->key_fd = (int)val;
1022 break;
1023 case 16:
1024 opts->nounpad = true;
1025 break;
1026
1027 case 17:
1028 verbosity++;
1029 break;
1030 case 18:
1031 verbosity = KCAPI_LOG_NONE;
1032 break;
1033 case 19:
1034 usage();
1035 break;
1036 case 20:
1037 memset(version, 0, sizeof(version));
1038 kcapi_versionstring(version, sizeof(version));
1039 fprintf(stderr, "Version %s\n", version);
1040 exit(0);
1041 break;
1042 default:
1043 usage();
1044 }
1045 break;
1046
1047 case 'c':
1048 opts->ciphername = optarg;
1049 break;
1050 case 'e':
1051 opts->decrypt = false;
1052 break;
1053 case 'd':
1054 opts->decrypt = true;
1055 break;
1056 case 'i':
1057 opts->infile = optarg;
1058 break;
1059 case 'o':
1060 opts->outfile = optarg;
1061 break;
1062 case 's':
1063 opts->salt = optarg;
1064 break;
1065 case 'p':
1066 opts->passwd = optarg;
1067 break;
1068
1069 case 'v':
1070 verbosity++;
1071 break;
1072 case 'q':
1073 verbosity = KCAPI_LOG_NONE;
1074 break;
1075 case 'h':
1076 usage();
1077 break;
1078 default:
1079 usage();
1080 }
1081 }
1082
1083 set_verbosity("kcapi-enc", verbosity);
1084
1085 if (!opts->ciphername) {
1086 dolog(KCAPI_LOG_ERR, "Provide cipher name");
1087 usage();
1088 }
1089
1090 if (!opts->passwd && opts->password_fd == -1 &&
1091 opts->key_fd == -1) {
1092 dolog(KCAPI_LOG_ERR,
1093 "Provide at least a password, a password FD or key FD");
1094 usage();
1095 }
1096
1097 if (opts->aad) {
1098 if (opts->decrypt && !opts->tag) {
1099 dolog(KCAPI_LOG_ERR,
1100 "No tag provided for AEAD decryption operation");
1101 usage();
1102 }
1103 if (!opts->decrypt && !opts->taglen) {
1104 dolog(KCAPI_LOG_ERR,
1105 "No tag length provided for AEAD encryption operation");
1106 usage();
1107 }
1108 }
1109
1110 if (opts->iv && opts->ccmnonce) {
1111 dolog(KCAPI_LOG_ERR, "IV and CCM nonce set\n");
1112 usage();
1113 }
1114
1115 if (opts->passwd)
1116 dolog(KCAPI_LOG_WARN,
1117 "Password on command line is visible in process listing and /proc! Use --passwd_fd command line option!");
1118
1119 if (!opts->pbkdf_hash)
1120 opts->pbkdf_hash = "hmac(sha256)";
1121 dolog(KCAPI_LOG_DEBUG, "Using PBKDF2 mac of %s", opts->pbkdf_hash);
1122 }
1123
1124 int main(int argc, char *argv[])
1125 {
1126 struct kcapi_handle *handle = NULL;
1127 struct opt_data opts;
1128 int ret;
1129
1130 parse_opts(argc, argv, &opts);
1131
1132 if (opts.aad) {
1133 opts.func_init = kcapi_aead_init;
1134 opts.func_destroy = kcapi_aead_destroy;
1135 opts.func_setkey = kcapi_aead_setkey;
1136 opts.func_stream_init_enc = kcapi_aead_stream_init_enc;
1137 opts.func_stream_init_dec = kcapi_aead_stream_init_dec;
1138 opts.func_stream_update = kcapi_aead_stream_update;
1139 opts.func_stream_update_last = kcapi_aead_stream_update_last;
1140 opts.func_stream_op = kcapi_aead_stream_op;
1141 opts.func_blocksize = kcapi_aead_blocksize;
1142 } else {
1143 opts.func_init = kcapi_cipher_init;
1144 opts.func_destroy = kcapi_cipher_destroy;
1145 opts.func_setkey = kcapi_cipher_setkey;
1146 opts.func_stream_init_enc = kcapi_cipher_stream_init_enc;
1147 opts.func_stream_init_dec = kcapi_cipher_stream_init_dec;
1148 opts.func_stream_update = kcapi_cipher_stream_update;
1149 opts.func_stream_update_last = kcapi_cipher_stream_update_last;
1150 opts.func_stream_op = kcapi_cipher_stream_op;
1151 opts.func_blocksize = kcapi_cipher_blocksize;
1152 }
1153
1154 /* Initialize link to the kernel's AF_ALG interface. */
1155 ret = opts.func_init(&handle, opts.ciphername, 0);
1156 if (ret)
1157 return ret;
1158
1159 /* Set the key from password or key-FD. */
1160 ret = set_key(handle, &opts);
1161 if (ret)
1162 goto out;
1163
1164 /* Perform cipher operation. */
1165 ret = cipher_op(handle, &opts);
1166
1167 if (ret >= 0) {
1168 dolog(KCAPI_LOG_VERBOSE, "%d bytes of %stext created",
1169 ret, opts.decrypt ? "plain" : "cipher");
1170 ret = 0;
1171 } else {
1172 if (ret == -EBADMSG && opts.aad) {
1173 dolog(KCAPI_LOG_ERR,
1174 "AEAD decryption failed due to integrity violation");
1175 } else {
1176 dolog(KCAPI_LOG_ERR, "%s failed with error %d",
1177 opts.decrypt ? "decryption" : "encryption", ret);
1178 }
1179 }
1180
1181 out:
1182 opts.func_destroy(handle);
1183
1184 return ret;
1185 }