1 /* sh-dmcrypt.c - The DM-Crypt part for g13-syshelp
2 * Copyright (C) 2015, 2016 Werner Koch
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
27 #include <sys/types.h>
29 # include <sys/stat.h>
33 #include "g13-syshelp.h"
40 /* The standard disk block size (logical). */
41 #define SECTOR_SIZE 512
43 /* The physical block size used by modern devices. */
44 #define PHY_SECTOR_SIZE (SECTOR_SIZE*8) /* 4 KiB */
46 /* The length of the crypto setup area in sectors. 16 KiB is a nice
47 multiple of a modern block size and should be sufficient for all
48 kind of extra public key encryption packets. */
49 #define SETUP_AREA_SECTORS 32 /* 16 KiB */
51 /* The number of header block copies stored at the begin and end of
53 #define HEADER_SETUP_AREA_COPIES 2
54 #define FOOTER_SETUP_AREA_COPIES 2
56 /* The length in blocks of the space we put at the start and at the
57 end of the device. This space is used to store N copies of the
58 setup area for the actual encrypted container inbetween. */
59 #define HEADER_SECTORS (SETUP_AREA_SECTORS * HEADER_SETUP_AREA_COPIES)
60 #define FOOTER_SECTORS (SETUP_AREA_SECTORS * FOOTER_SETUP_AREA_COPIES)
62 /* Minimim size of the encrypted space in blocks. This is more or
63 less an arbitrary value. */
64 #define MIN_ENCRYPTED_SPACE 32
66 /* Some consistency checks for the above constants. */
67 #if (PHY_SECTOR_SIZE % SECTOR_SIZE)
68 # error the physical secotor size should be a multiple of 512
70 #if ((SETUP_AREA_SECTORS*SECTOR_SIZE) % PHY_SECTOR_SIZE)
71 # error The setup area size should be a multiple of the phy. sector size.
76 * Check whether the block device DEVNAME is used by device mapper.
77 * If EXPECT_BUSY is set no error message is printed if the device is
78 * busy. Returns: 0 if the device is good and not yet used by DM.
81 check_blockdev (const char *devname, int expect_busy)
85 unsigned int devmajor, devminor;
91 if (stat (devname, &sb))
93 err = gpg_error_from_syserror ();
94 log_error ("error stating '%s': %s\n", devname, gpg_strerror (err));
97 if (!S_ISBLK (sb.st_mode))
99 err = gpg_error (GPG_ERR_ENOTBLK);
100 log_error ("can't use '%s': %s\n", devname, gpg_strerror (err));
103 devmajor = major (sb.st_rdev);
104 devminor = minor (sb.st_rdev);
111 err = gnupg_exec_tool ("/sbin/dmsetup", argv, NULL, &result, NULL);
115 log_error ("error running '%s' to search for '%s': %s\n",
116 "dmsetup deps", devname, gpg_strerror (err));
119 lines = strsplit (result, '\n', 0, NULL);
122 err = gpg_error_from_syserror ();
125 if (lines[0] && !strcmp (lines[0], "No devices found"))
129 for (lno=0; lines[lno]; lno++)
131 unsigned int xmajor, xminor;
136 fields = strsplit (lines[lno], ':', 0, &count);
139 err = gpg_error_from_syserror ();
143 || sscanf (fields[2], " (%u,%u)", &xmajor, &xminor) != 2)
145 log_error ("error running '%s' to search for '%s': %s\n",
146 "dmsetup deps", devname, "unexpected output");
147 err = gpg_error (GPG_ERR_INV_VALUE);
151 if (xmajor == devmajor && xminor == devminor)
154 log_error ("device '%s' (%u:%u)"
155 " already in use by device mapper\n",
156 devname, devmajor, devminor);
157 err = gpg_error (GPG_ERR_EBUSY);
172 /* Return a malloced buffer with the prefix of the setup area. This
173 is the data written right before the encrypted keyblob. Return NULL
174 on error and sets ERRNO. */
176 mk_setup_area_prefix (size_t *r_length)
178 unsigned char *packet;
181 packet = xtrymalloc (32);
186 setuparealen = SETUP_AREA_SECTORS * SECTOR_SIZE;
188 packet[0] = (0xc0|61); /* CTB for the private packet type 0x61. */
189 packet[1] = 0xff; /* 5 byte length packet, value 20. */
194 memcpy (packet+6, "GnuPG/G13", 10); /* Packet subtype. */
195 packet[16] = 1; /* G13 packet format version. */
196 packet[17] = 0; /* Reserved. */
197 packet[18] = 0; /* Reserved. */
198 packet[19] = 1; /* OS Flag = Linux */
199 packet[20] = (setuparealen >> 24); /* Total length of header. */
200 packet[21] = (setuparealen >> 16);
201 packet[22] = (setuparealen >> 8);
202 packet[23] = (setuparealen);
203 packet[24] = HEADER_SETUP_AREA_COPIES;
204 packet[25] = FOOTER_SETUP_AREA_COPIES;
205 packet[26] = 0; /* Reserved. */
206 packet[27] = 0; /* Reserved. */
207 packet[28] = 0; /* Reserved. */
208 packet[29] = 0; /* Reserved. */
209 packet[30] = 0; /* Reserved. */
210 packet[31] = 0; /* Reserved. */
216 /* Create a new g13 styloe DM-Crypt container on devoce DEVNAME. */
218 sh_dmcrypt_create_container (ctrl_t ctrl, const char *devname, estream_t devfp)
222 size_t header_space_size, header_space_used;
224 char *targetname = NULL;
229 unsigned long long nblocks;
231 unsigned char twobyte[2];
233 void *keyblob_buf = NULL;
237 unsigned char *packet;
241 return gpg_error (GPG_ERR_INV_ARG);
243 g13_syshelp_i_know_what_i_am_doing ();
245 header_space_size = SETUP_AREA_SECTORS * SECTOR_SIZE;
246 header_space = xtrymalloc (header_space_size);
248 return gpg_error_from_syserror ();
250 /* Start building the keyblob. */
251 init_membuf (&keyblob, 512);
252 append_tuple (&keyblob, KEYBLOB_TAG_BLOBVERSION, "\x01", 1);
253 n = CONTTYPE_DM_CRYPT;
254 twobyte[0] = (n >> 8);
256 append_tuple (&keyblob, KEYBLOB_TAG_CONTTYPE, twobyte, 2);
258 gnupg_isotime_t tbuf;
260 gnupg_get_isotime (tbuf);
261 append_tuple (&keyblob, KEYBLOB_TAG_CREATED, tbuf, strlen (tbuf));
264 /* Rewind device stream. */
265 if (es_fseeko (devfp, 0, SEEK_SET))
267 err = gpg_error_from_syserror ();
268 log_error ("error seeking to begin of '%s': %s\n",
269 devname, gpg_strerror (err));
274 /* Extra check that the device is empty. */
275 if (es_read (devfp, header_space, header_space_size, &nread))
276 err = gpg_error_from_syserror ();
277 else if (nread != header_space_size)
278 err = gpg_error (GPG_ERR_TOO_SHORT);
283 log_error ("error reading header space of '%s': %s\n",
284 devname, gpg_strerror (err));
287 for (p=header_space; nread && !*p; nread--, p++)
291 log_error ("header space of '%s' already used - use %s to override\n",
293 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
297 /* Check that the device is not used by device mapper. */
298 err = check_blockdev (devname, 0);
302 /* Compute the number of blocks. */
303 err = sh_blockdev_getsz (devname, &nblocks);
306 log_error ("error getting size of '%s': %s\n",
307 devname, gpg_strerror (err));
310 if (nblocks <= HEADER_SECTORS + MIN_ENCRYPTED_SPACE + FOOTER_SECTORS)
312 log_error ("device '%s' is too small (min=%d blocks)\n",
314 HEADER_SECTORS + MIN_ENCRYPTED_SPACE + FOOTER_SECTORS);
315 err = gpg_error (GPG_ERR_TOO_SHORT);
318 append_tuple_uint (&keyblob, KEYBLOB_TAG_CONT_NSEC, nblocks);
319 nblocks -= HEADER_SECTORS + FOOTER_SECTORS;
320 append_tuple_uint (&keyblob, KEYBLOB_TAG_ENC_NSEC, nblocks);
321 append_tuple_uint (&keyblob, KEYBLOB_TAG_ENC_OFF, HEADER_SECTORS);
323 /* Device mapper needs a name for the device: Take it from the label
325 targetname = strconcat ("g13-", ctrl->client.uname, "-",
326 ctrl->devti->label? ctrl->devti->label : "0",
330 err = gpg_error_from_syserror ();
334 /* Create the key. */
337 gcry_randomize (key, sizeof key, GCRY_STRONG_RANDOM);
338 append_tuple (&keyblob, KEYBLOB_TAG_ENCKEY, key, sizeof key);
339 bin2hex (key, 16, hexkey);
340 wipememory (key, 16);
341 /* Add a 2*(4+16) byte filler to conceal the fact that we use
342 AES-128. If we ever want to switch to 256 bit we can resize
343 that filler to keep the keyblob at the same size. */
344 append_tuple (&keyblob, KEYBLOB_TAG_FILLER, key, sizeof key);
345 append_tuple (&keyblob, KEYBLOB_TAG_FILLER, key, sizeof key);
348 /* Build dmcrypt table. */
349 s = "aes-cbc-essiv:sha256";
350 append_tuple (&keyblob, KEYBLOB_TAG_ALGOSTR, s, strlen (s));
351 table = es_bsprintf ("0 %llu crypt %s %s 0 %s %d",
352 nblocks, s, hexkey, devname, HEADER_SECTORS);
355 err = gpg_error_from_syserror ();
358 wipememory (hexkey, sizeof hexkey);
360 /* Add a copy of the setup area prefix to the keyblob. */
361 p = mk_setup_area_prefix (&n);
364 err = gpg_error_from_syserror ();
367 append_tuple (&keyblob, KEYBLOB_TAG_HDRCOPY, p, n);
368 assert (n < header_space_size);
369 memcpy (header_space, p, n);
370 header_space_used = n;
372 /* Turn the keyblob into a buffer and callback to encrypt it. */
373 keyblob_buf = get_membuf (&keyblob, &keyblob_len);
376 err = gpg_error_from_syserror ();
379 err = sh_encrypt_keyblob (ctrl, keyblob_buf, keyblob_len, &p, &n);
382 log_error ("encrypting the keyblob failed: %s\n", gpg_strerror (err));
385 log_debug ("plain setuparea=%p %zu bytes\n", keyblob_buf, keyblob_len);
386 wipememory (keyblob_buf, keyblob_len);
390 log_debug ("encry setuparea=%p %zu bytes\n", p, n);
391 if (n >= header_space_size || (header_space_used + n) >= header_space_size)
393 err = gpg_error (GPG_ERR_TOO_LARGE);
394 log_error ("setup area would overflow: %s\n", gpg_strerror (err));
397 memcpy (header_space + header_space_used, p, n);
398 header_space_used += n;
400 /* Write the padding. */
401 packet = header_space + header_space_used;
402 paddinglen = header_space_size - header_space_used;
405 err = gpg_error (GPG_ERR_TOO_LARGE);
406 log_error ("setup area too short for padding: %s\n", gpg_strerror (err));
409 packet[0] = (0xc0|61); /* CTB for Private packet type 0x61. */
410 packet[1] = 0xff; /* 5 byte length packet, value 20. */
411 packet[2] = (paddinglen-6) >> 24;
412 packet[3] = (paddinglen-6) >> 16;
413 packet[4] = (paddinglen-6) >> 8;
414 packet[5] = (paddinglen-6);
417 header_space_used += 6;
418 for ( ;paddinglen >= 10;
419 paddinglen -= 10, packet += 10, header_space_used += 10)
420 memcpy (packet, "GnuPG/PAD", 10);
421 for ( ;paddinglen; paddinglen--, packet++, header_space_used++)
424 if (header_space_used != header_space_size)
427 /* Create the container. */
432 argv[1] = targetname;
434 log_debug ("now running \"dmsetup create %s\"\n", targetname);
435 log_debug (" with table='%s'\"\n", table);
436 err = gnupg_exec_tool ("/sbin/dmsetup", argv, table, &result, NULL);
440 log_error ("error running dmsetup for '%s': %s\n",
441 devname, gpg_strerror (err));
444 if (result && *result)
445 log_debug ("dmsetup result: %s\n", result);
447 /* Write the setup area. */
448 if (es_fseeko (devfp, 0, SEEK_SET))
450 err = gpg_error_from_syserror ();
451 log_error ("error seeking to begin of '%s': %s\n",
452 devname, gpg_strerror (err));
457 for (copy = 0; copy < HEADER_SETUP_AREA_COPIES; copy++)
461 if (es_write (devfp, header_space, header_space_size, &nwritten))
463 err = gpg_error_from_syserror ();
466 else if (nwritten != header_space_size)
468 err = gpg_error (GPG_ERR_TOO_SHORT);
474 log_error ("error writing header space copy %d of '%s': %s\n",
475 copy, devname, gpg_strerror (err));
479 if (es_fseeko (devfp,
480 (- header_space_size * FOOTER_SETUP_AREA_COPIES), SEEK_END))
482 err = gpg_error_from_syserror ();
483 log_error ("error seeking to end of '%s': %s\n",
484 devname, gpg_strerror (err));
489 for (copy = 0; copy < FOOTER_SETUP_AREA_COPIES; copy++)
493 if (es_write (devfp, header_space, header_space_size, &nwritten))
495 err = gpg_error_from_syserror ();
498 else if (nwritten != header_space_size)
500 err = gpg_error (GPG_ERR_TOO_SHORT);
504 if (!err && es_fflush (devfp))
505 err = gpg_error_from_syserror ();
508 log_error ("error writing footer space copy %d of '%s': %s\n",
509 copy, devname, gpg_strerror (err));
514 wipememory (hexkey, sizeof hexkey);
517 wipememory (table, strlen (table));
522 wipememory (keyblob_buf, keyblob_len);
525 xfree (get_membuf (&keyblob, NULL));
528 xfree (header_space);
533 /* Mount a DM-Crypt container on device DEVNAME taking keys and other
534 * meta data from KEYBLOB. */
536 sh_dmcrypt_mount_container (ctrl_t ctrl, const char *devname,
540 char *targetname_abs = NULL;
541 const char *targetname;
544 unsigned long long nblocks, nblocks2;
552 return gpg_error (GPG_ERR_INV_ARG);
554 g13_syshelp_i_know_what_i_am_doing ();
556 /* Check that the device is not yet used by device mapper. */
557 err = check_blockdev (devname, 0);
561 /* Compute the number of blocks and compare them to the value
562 provided as meta data. */
563 err = sh_blockdev_getsz (devname, &nblocks);
566 log_error ("error getting size of '%s': %s\n",
567 devname, gpg_strerror (err));
570 err = find_tuple_uint (keyblob, KEYBLOB_TAG_CONT_NSEC, &nblocks2);
573 log_error ("error getting size from keyblob: %s\n", gpg_strerror (err));
576 if (nblocks != nblocks2)
578 log_error ("inconsistent size of container: expected==%llu got=%llu\n",
580 err = gpg_error (GPG_ERR_INV_DATA);
583 if (nblocks <= HEADER_SECTORS + MIN_ENCRYPTED_SPACE + FOOTER_SECTORS)
585 log_error ("device '%s' is too small (min=%d blocks)\n",
587 HEADER_SECTORS + MIN_ENCRYPTED_SPACE + FOOTER_SECTORS);
588 err = gpg_error (GPG_ERR_TOO_SHORT);
591 nblocks -= HEADER_SECTORS + FOOTER_SECTORS;
592 err = find_tuple_uint (keyblob, KEYBLOB_TAG_ENC_NSEC, &nblocks2);
595 log_error ("error getting enc size from keyblob: %s\n",
599 if (nblocks != nblocks2)
601 log_error ("inconsistent size of enc data: expected==%llu got=%llu\n",
603 err = gpg_error (GPG_ERR_INV_DATA);
606 /* Check that the offset is consistent. */
607 err = find_tuple_uint (keyblob, KEYBLOB_TAG_ENC_OFF, &nblocks2);
610 log_error ("error getting enc offset from keyblob: %s\n",
614 if (nblocks2 != HEADER_SECTORS)
616 log_error ("inconsistent offset of enc data: expected==%llu got=%d\n",
617 nblocks2, HEADER_SECTORS);
618 err = gpg_error (GPG_ERR_INV_DATA);
622 /* Device mapper needs a name for the device: Take it from the label
624 targetname_abs = strconcat ("/dev/mapper/",
625 "g13-", ctrl->client.uname, "-",
626 ctrl->devti->label? ctrl->devti->label : "0",
630 err = gpg_error_from_syserror ();
633 targetname = strrchr (targetname_abs, '/');
638 /* Get the algorithm string. */
639 algostr = find_tuple (keyblob, KEYBLOB_TAG_ALGOSTR, &algostrlen);
640 if (!algostr || algostrlen > 100)
642 log_error ("algo string not found in keyblob or too long\n");
643 err = gpg_error (GPG_ERR_INV_DATA);
648 s = find_tuple (keyblob, KEYBLOB_TAG_ENCKEY, &n);
652 log_error ("no key found in keyblob\n");
654 log_error ("unexpected size of key (%zu)\n", n);
655 err = gpg_error (GPG_ERR_INV_KEYLEN);
658 bin2hex (s, 16, hexkey);
660 /* Build dmcrypt table. */
661 table = es_bsprintf ("0 %llu crypt %.*s %s 0 %s %d",
662 nblocks, (int)algostrlen, algostr,
663 hexkey, devname, HEADER_SECTORS);
664 wipememory (hexkey, sizeof hexkey);
667 err = gpg_error_from_syserror ();
671 /* Load the table. */
676 argv[1] = targetname;
678 log_debug ("now running \"dmsetup create %s\"\n", targetname);
679 err = gnupg_exec_tool ("/sbin/dmsetup", argv, table, &result, NULL);
683 log_error ("error running dmsetup for '%s': %s\n",
684 devname, gpg_strerror (err));
687 if (result && *result)
688 log_debug ("dmsetup result: %s\n", result);
692 /* Mount if a mountpoint has been given. */
693 if (ctrl->devti->mountpoint)
697 argv[0] = targetname_abs;
698 argv[1] = ctrl->devti->mountpoint;
700 log_debug ("now running \"mount %s %s\"\n",
701 targetname_abs, ctrl->devti->mountpoint);
702 err = gnupg_exec_tool ("/bin/mount", argv, NULL, &result, NULL);
705 log_error ("error running mount: %s\n", gpg_strerror (err));
708 if (result && *result) /* (We should not see output to stdout). */
709 log_info ("WARNING: mount returned data on stdout! (%s)\n", result);
714 wipememory (hexkey, sizeof hexkey);
717 wipememory (table, strlen (table));
720 xfree (targetname_abs);
726 /* Suspend a DM-Crypt container on device DEVNAME and wipe the keys. */
728 sh_dmcrypt_suspend_container (ctrl_t ctrl, const char *devname)
731 char *targetname_abs = NULL;
732 const char *targetname;
736 return gpg_error (GPG_ERR_INV_ARG);
738 g13_syshelp_i_know_what_i_am_doing ();
740 /* Check that the device is used by device mapper. */
741 err = check_blockdev (devname, 1);
742 if (gpg_err_code (err) != GPG_ERR_EBUSY)
744 log_error ("device '%s' is not used by the device mapper: %s\n",
745 devname, gpg_strerror (err));
749 /* Fixme: Check that this is really a g13 partition. */
751 /* Device mapper needs a name for the device: Take it from the label
753 targetname_abs = strconcat ("/dev/mapper/",
754 "g13-", ctrl->client.uname, "-",
755 ctrl->devti->label? ctrl->devti->label : "0",
759 err = gpg_error_from_syserror ();
762 targetname = strrchr (targetname_abs, '/');
767 /* Send the suspend command. */
772 argv[1] = targetname;
774 log_debug ("now running \"dmsetup suspend %s\"\n", targetname);
775 err = gnupg_exec_tool ("/sbin/dmsetup", argv, NULL, &result, NULL);
779 log_error ("error running \"dmsetup suspend %s\": %s\n",
780 targetname, gpg_strerror (err));
783 if (result && *result)
784 log_debug ("dmsetup result: %s\n", result);
788 /* Send the wipe key command. */
793 argv[1] = targetname;
795 argv[3] = "key wipe";
797 log_debug ("now running \"dmsetup message %s 0 key wipe\"\n", targetname);
798 err = gnupg_exec_tool ("/sbin/dmsetup", argv, NULL, &result, NULL);
802 log_error ("error running \"dmsetup message %s 0 key wipe\": %s\n",
803 targetname, gpg_strerror (err));
806 if (result && *result)
807 log_debug ("dmsetup result: %s\n", result);
813 xfree (targetname_abs);
819 /* Resume a DM-Crypt container on device DEVNAME taking keys and other
820 * meta data from KEYBLOB. */
822 sh_dmcrypt_resume_container (ctrl_t ctrl, const char *devname,
826 char *targetname_abs = NULL;
827 const char *targetname;
828 char hexkey[8+16*2+1]; /* 8 is used to prepend "key set ". */
837 return gpg_error (GPG_ERR_INV_ARG);
839 g13_syshelp_i_know_what_i_am_doing ();
841 /* Check that the device is used by device mapper. */
842 err = check_blockdev (devname, 1);
843 if (gpg_err_code (err) != GPG_ERR_EBUSY)
845 log_error ("device '%s' is not used by the device mapper: %s\n",
846 devname, gpg_strerror (err));
850 /* Device mapper needs a name for the device: Take it from the label
852 targetname_abs = strconcat ("/dev/mapper/",
853 "g13-", ctrl->client.uname, "-",
854 ctrl->devti->label? ctrl->devti->label : "0",
858 err = gpg_error_from_syserror ();
861 targetname = strrchr (targetname_abs, '/');
866 /* Get the algorithm string. */
867 algostr = find_tuple (keyblob, KEYBLOB_TAG_ALGOSTR, &algostrlen);
868 if (!algostr || algostrlen > 100)
870 log_error ("algo string not found in keyblob or too long\n");
871 err = gpg_error (GPG_ERR_INV_DATA);
876 s = find_tuple (keyblob, KEYBLOB_TAG_ENCKEY, &n);
880 log_error ("no key found in keyblob\n");
882 log_error ("unexpected size of key (%zu)\n", n);
883 err = gpg_error (GPG_ERR_INV_KEYLEN);
886 strcpy (hexkey, "key set ");
887 bin2hex (s, 16, hexkey+8);
894 argv[1] = targetname;
897 log_debug ("now running \"dmsetup message %s 0 [key set]\"\n", targetname);
898 err = gnupg_exec_tool ("/sbin/dmsetup", argv, hexkey, &result, NULL);
900 wipememory (hexkey, sizeof hexkey);
903 log_error ("error running \"dmsetup message %s 0 [key set]\": %s\n",
904 devname, gpg_strerror (err));
907 if (result && *result)
908 log_debug ("dmsetup result: %s\n", result);
912 /* Send the resume command. */
917 argv[1] = targetname;
919 log_debug ("now running \"dmsetup resume %s\"\n", targetname);
920 err = gnupg_exec_tool ("/sbin/dmsetup", argv, NULL, &result, NULL);
924 log_error ("error running \"dmsetup resume %s\": %s\n",
925 targetname, gpg_strerror (err));
928 if (result && *result)
929 log_debug ("dmsetup result: %s\n", result);
934 wipememory (hexkey, sizeof hexkey);
937 wipememory (table, strlen (table));
940 xfree (targetname_abs);