]> git.proxmox.com Git - swtpm.git/blob - src/swtpm/swtpm.c
swtpm: Add a chroot option
[swtpm.git] / src / swtpm / swtpm.c
1 /********************************************************************************/
2 /* */
3 /* TPM Main Program */
4 /* Written by Ken Goldman, Stefan Berger */
5 /* IBM Thomas J. Watson Research Center */
6 /* */
7 /* (c) Copyright IBM Corporation 2006, 2010, 2016, 2019. */
8 /* */
9 /* All rights reserved. */
10 /* */
11 /* Redistribution and use in source and binary forms, with or without */
12 /* modification, are permitted provided that the following conditions are */
13 /* met: */
14 /* */
15 /* Redistributions of source code must retain the above copyright notice, */
16 /* this list of conditions and the following disclaimer. */
17 /* */
18 /* Redistributions in binary form must reproduce the above copyright */
19 /* notice, this list of conditions and the following disclaimer in the */
20 /* documentation and/or other materials provided with the distribution. */
21 /* */
22 /* Neither the names of the IBM Corporation nor the names of its */
23 /* contributors may be used to endorse or promote products derived from */
24 /* this software without specific prior written permission. */
25 /* */
26 /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
27 /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
28 /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
29 /* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
30 /* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
31 /* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
32 /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
33 /* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
34 /* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
35 /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
36 /* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
37 /********************************************************************************/
38
39 #include <config.h>
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <time.h>
45 #include <getopt.h>
46 #include <errno.h>
47 #include <poll.h>
48 #include <sys/stat.h>
49 #include <stdbool.h>
50 #include <sys/types.h>
51 #include <sys/socket.h>
52
53 #include <libtpms/tpm_error.h>
54 #include <libtpms/tpm_library.h>
55 #include <libtpms/tpm_memory.h>
56
57 #include "main.h"
58 #include "swtpm_debug.h"
59 #include "swtpm_io.h"
60 #include "swtpm_nvstore.h"
61 #include "server.h"
62 #include "common.h"
63 #include "logging.h"
64 #include "pidfile.h"
65 #include "tpmlib.h"
66 #include "utils.h"
67 #include "mainloop.h"
68 #include "ctrlchannel.h"
69 #include "tpmstate.h"
70 #include "sys_dependencies.h"
71 #include "daemonize.h"
72 #include "seccomp_profile.h"
73 #include "options.h"
74 #include "capabilities.h"
75
76 /* local variables */
77 static int notify_fd[2] = {-1, -1};
78
79 static struct libtpms_callbacks callbacks = {
80 .sizeOfStruct = sizeof(struct libtpms_callbacks),
81 .tpm_nvram_init = SWTPM_NVRAM_Init,
82 .tpm_nvram_loaddata = SWTPM_NVRAM_LoadData,
83 .tpm_nvram_storedata = SWTPM_NVRAM_StoreData,
84 .tpm_nvram_deletename = SWTPM_NVRAM_DeleteName,
85 .tpm_io_init = SWTPM_IO_Init,
86 .tpm_io_getlocality = mainloop_cb_get_locality,
87 };
88
89 static void sigterm_handler(int sig __attribute__((unused)))
90 {
91 TPM_DEBUG("Terminating...\n");
92 if (write(notify_fd[1], "T", 1) < 0) {
93 logprintf(STDERR_FILENO, "Error: sigterm notification failed: %s\n",
94 strerror(errno));
95 }
96 mainloop_terminate = true;
97 }
98
99 static void usage(FILE *file, const char *prgname, const char *iface)
100 {
101 fprintf(file,
102 "Usage: %s %s [options]\n"
103 "\n"
104 "The following options are supported:\n"
105 "\n"
106 "-p|--port <port> : use the given port\n"
107 "-f|--fd <fd> : use the given socket file descriptor\n"
108 "-t|--terminate : terminate the TPM once a connection has been lost\n"
109 "-d|--daemon : daemonize the TPM\n"
110 "--ctrl type=[unixio|tcp][,path=<path>][,port=<port>[,bindaddr=address[,ifname=ifname]]][,fd=<filedescriptor>|clientfd=<filedescriptor>][,mode=0...][,uid=uid][,gid=gid]\n"
111 " : TPM control channel using either UnixIO or TCP sockets;\n"
112 " the path is only valid for Unixio channels; the port must\n"
113 " be given in case the type is TCP; the TCP socket is bound\n"
114 " to 127.0.0.1 by default and other bind addresses can be\n"
115 " given with the bindaddr parameter; if fd is provided,\n"
116 " it will be treated as a server socket and used for \n"
117 " accepting client connections; if clientfd is provided,\n"
118 " it will be treaded as client connection;\n"
119 " NOTE: fd and clientfd are mutually exclusive and clientfd\n"
120 " is only valid for UnixIO channels\n"
121 " mode allows a user to set the file mode bits of a Unixio socket;\n"
122 " the value must be given in octal number format\n"
123 " uid and gid set the ownership of the Unixio socket's file;\n"
124 "--migration-key file=<path>|fd=<fd>[,mode=aes-cbc|aes-256-cbc][,format=hex|binary][,remove=[true|false]]\n"
125 " : use an AES key for the encryption of the TPM's state\n"
126 " when it is retrieved from the TPM via ioctls;\n"
127 " Setting this key ensures that the TPM's state will always\n"
128 " be encrypted when migrated\n"
129 "--migration-key pwdfile=<path>|pwdfd=<fd>[,mode=aes-cbc|aes-256-cbc][,remove=[true|false]][,kdf=sha512|pbkdf2]\n"
130 " : provide a passphrase in a file; the AES key will be\n"
131 " derived from this passphrase; default kdf is PBKDF2\n"
132 "--log file=<path>|fd=<filedescriptor>[,level=n][,prefix=<prefix>][,truncate]\n"
133 " : write the TPM's log into the given file rather than\n"
134 " to the console; provide '-' for path to avoid logging\n"
135 " log level 5 and higher will enable libtpms logging;\n"
136 " all logged output will be prefixed with prefix;\n"
137 " the log file can be reset (truncate)\n"
138 "--key file=<path>|fd=<fd>[,mode=aes-cbc|aes-256-cbc][,format=hex|binary][,remove=[true|false]]\n"
139 " : use an AES key for the encryption of the TPM's state\n"
140 " files; use the given mode for the block encryption;\n"
141 " the key is to be provided as a hex string or in binary\n"
142 " format; the keyfile can be automatically removed using\n"
143 " the remove parameter\n"
144 "--key pwdfile=<path>|pwdfd=<fd>[,mode=aes-cbc|aes-256-cbc][,remove=[true|false]][,kdf=sha512|pbkdf2]\n"
145 " : provide a passphrase in a file; the AES key will be\n"
146 " derived from this passphrase; default kdf is PBKDF2\n"
147 "--locality [reject-locality-4][,allow-set-locality]\n"
148 " : reject-locality-4: reject any command in locality 4\n"
149 " allow-set-locality: accept SetLocality command\n"
150 "--pid file=<path>|fd=<filedescriptor>\n"
151 " : write the process ID into the given file\n"
152 "--tpmstate dir=<dir>[,mode=0...]|backend-uri=<uri>\n"
153 " : set the directory or uri where the TPM's state will be written\n"
154 " into; the TPM_PATH environment variable can be used\n"
155 " instead dir option;\n"
156 " mode allows a user to set the file mode bits of the state files;\n"
157 " the default mode is 0640;\n"
158 "--server [type=tcp][,port=port[,bindaddr=address[,ifname=ifname]]][,fd=fd][,disconnect]\n"
159 " : Expect TCP connections on the given port;\n"
160 " if fd is provided, packets will be read from it directly;\n"
161 " the disconnect parameter closes the connection after\n"
162 " sending a response back to the client; the TCP socket is\n"
163 " bound to 127.0.0.1 by default and other bind addresses\n"
164 " can be given with the bindaddr parameter\n"
165 "--server type=unixio[,path=path][,fd=fd][,mode=0...][,uid=uid][,gid=gid]\n"
166 " : Expect UnixIO connections on the given path; if fd is\n"
167 " provided, packets will be read from it directly;\n"
168 " mode allows a user to set the file mode bits of the socket; the\n"
169 " value must be given in octal number format;\n"
170 " uid and gid set the ownership of the Unixio socket's file;\n"
171 "--flags [not-need-init][,startup-clear|startup-state|startup-deactivated|startup-none][,disable-auto-shutdown]\n"
172 " : not-need-init: commands can be sent without needing to\n"
173 " send an INIT via control channel;\n"
174 " startup-...: send Startup command with this type;\n"
175 " disable-auto-shutdown disables automatic sending of\n"
176 " TPM2_Shutdown before TPM 2 reset or swtpm termination;\n"
177 "-r|--runas <user>: change to the given user\n"
178 "-R|--chroot <path>\n"
179 " : chroot to the given directory at startup\n"
180 "--tpm2 : choose TPM2 functionality\n"
181 #ifdef WITH_SECCOMP
182 # ifndef SCMP_ACT_LOG
183 "--seccomp action=none|kill\n"
184 # else
185 "--seccomp action=none|kill|log\n"
186 # endif
187 " : Choose the action of the seccomp profile when a\n"
188 " blacklisted syscall is executed; default is kill\n"
189 #endif
190 "--print-capabilites\n"
191 " : print capabilities and terminate\n"
192 "--print-states\n"
193 " : print existing TPM states and terminate\n"
194 "-h|--help : display this help screen and terminate\n"
195 "\n",
196 prgname, iface);
197 }
198
199 static void swtpm_cleanup(struct ctrlchannel *cc, struct server *server)
200 {
201 pidfile_remove();
202 ctrlchannel_free(cc);
203 server_free(server);
204 log_global_free();
205 tpmstate_global_free();
206 SWTPM_NVRAM_Shutdown();
207 }
208
209 int swtpm_main(int argc, char **argv, const char *prgname, const char *iface)
210 {
211 TPM_RESULT rc = 0;
212 int daemonize = FALSE;
213 int opt, longindex, ret;
214 struct stat statbuf;
215 struct mainLoopParams mlp = {
216 .cc = NULL,
217 .flags = 0,
218 .fd = -1,
219 .locality_flags = 0,
220 .tpmversion = TPMLIB_TPM_VERSION_1_2,
221 .startupType = _TPM_ST_NONE,
222 .lastCommand = TPM_ORDINAL_NONE,
223 .disable_auto_shutdown = false,
224 };
225 struct server *server = NULL;
226 unsigned long val;
227 char *end_ptr;
228 char buf[20];
229 char *keydata = NULL;
230 char *migkeydata = NULL;
231 char *logdata = NULL;
232 char *piddata = NULL;
233 char *localitydata = NULL;
234 char *tpmstatedata = NULL;
235 char *ctrlchdata = NULL;
236 char *serverdata = NULL;
237 char *flagsdata = NULL;
238 char *seccompdata = NULL;
239 char *runas = NULL;
240 char *chroot = NULL;
241 bool need_init_cmd = true;
242 #ifdef DEBUG
243 time_t start_time;
244 #endif
245 unsigned int seccomp_action;
246 bool printcapabilities = false;
247 bool printstates = false;
248 static struct option longopts[] = {
249 {"daemon" , no_argument, 0, 'd'},
250 {"help" , no_argument, 0, 'h'},
251 {"port" , required_argument, 0, 'p'},
252 {"fd" , required_argument, 0, 'f'},
253 {"server" , required_argument, 0, 'c'},
254 {"runas" , required_argument, 0, 'r'},
255 {"chroot" , required_argument, 0, 'R'},
256 {"terminate" , no_argument, 0, 't'},
257 {"locality" , required_argument, 0, 'L'},
258 {"log" , required_argument, 0, 'l'},
259 {"key" , required_argument, 0, 'k'},
260 {"migration-key", required_argument, 0, 'K'},
261 {"pid" , required_argument, 0, 'P'},
262 {"tpmstate" , required_argument, 0, 's'},
263 {"ctrl" , required_argument, 0, 'C'},
264 {"flags" , required_argument, 0, 'F'},
265 {"tpm2" , no_argument, 0, '2'},
266 #ifdef WITH_SECCOMP
267 {"seccomp" , required_argument, 0, 'S'},
268 #endif
269 {"print-capabilities"
270 , no_argument, 0, 'a'},
271 {"print-states", no_argument, 0, 'e'},
272 {NULL , 0 , 0, 0 },
273 };
274
275 log_set_prefix("swtpm: ");
276
277 while (TRUE) {
278 opt = getopt_long(argc, argv, "dhp:f:tr:R:", longopts, &longindex);
279
280 if (opt == -1)
281 break;
282
283 switch (opt) {
284 case 'd':
285 daemonize = TRUE;
286 if (daemonize_prep() == -1) {
287 logprintf(STDERR_FILENO,
288 "Could not prepare to daemonize: %s\n", strerror(errno));
289 exit(EXIT_FAILURE);
290 }
291 break;
292
293 case 'p':
294 errno = 0;
295 val = strtoul(optarg, &end_ptr, 0);
296 if (val != (unsigned int)val || errno || end_ptr[0] != '\0') {
297 logprintf(STDERR_FILENO,
298 "Cannot parse socket port number '%s'.\n",
299 optarg);
300 exit(EXIT_FAILURE);
301 }
302 if (val >= 0x10000) {
303 logprintf(STDERR_FILENO, "Port is outside valid range.\n");
304 exit(EXIT_FAILURE);
305 }
306 snprintf(buf, sizeof(buf), "%lu", val);
307 if (setenv("TPM_PORT", buf, 1) != 0) {
308 logprintf(STDERR_FILENO,
309 "Could not set port: %s\n", strerror(errno));
310 exit(EXIT_FAILURE);
311 }
312 serverdata = "type=tcp,disconnect";
313 break;
314
315 case 'f':
316 errno = 0;
317 val = strtoul(optarg, &end_ptr, 10);
318 if (val != (unsigned int)val || errno || end_ptr[0] != '\0') {
319 logprintf(STDERR_FILENO,
320 "Cannot parse socket file descriptor.\n");
321 exit(EXIT_FAILURE);
322 }
323 mlp.fd = val;
324 if (fstat(mlp.fd, &statbuf) != 0) {
325 logprintf(STDERR_FILENO, "Cannot stat file descriptor: %s\n",
326 strerror(errno));
327 exit(EXIT_FAILURE);
328 }
329 /*
330 * test for wrong file types; anonymous fd's do not seem to be any of the wrong
331 * ones but are also not character devices
332 */
333 if (S_ISREG(statbuf.st_mode) || S_ISDIR(statbuf.st_mode) ||
334 S_ISBLK(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) {
335 logprintf(STDERR_FILENO,
336 "Given file descriptor type is not supported.\n");
337 exit(EXIT_FAILURE);
338 }
339 mlp.flags |= MAIN_LOOP_FLAG_TERMINATE | MAIN_LOOP_FLAG_USE_FD |
340 MAIN_LOOP_FLAG_KEEP_CONNECTION;
341
342 SWTPM_IO_SetSocketFD(mlp.fd);
343
344 break;
345
346 case 'c':
347 serverdata = optarg;
348 break;
349
350 case 't':
351 mlp.flags |= MAIN_LOOP_FLAG_TERMINATE;
352 break;
353
354 case 'k':
355 keydata = optarg;
356 break;
357
358 case 'K':
359 migkeydata = optarg;
360 break;
361
362 case 'l':
363 logdata = optarg;
364 break;
365
366 case 'P':
367 piddata = optarg;
368 break;
369
370 case 's':
371 tpmstatedata = optarg;
372 break;
373
374 case 'C':
375 ctrlchdata = optarg;
376 break;
377
378 case 'L':
379 localitydata = optarg;
380 break;
381
382 case 'F':
383 flagsdata = optarg;
384 break;
385
386 case '2':
387 mlp.tpmversion = TPMLIB_TPM_VERSION_2;
388 break;
389
390 case 'h':
391 usage(stdout, prgname, iface);
392 exit(EXIT_SUCCESS);
393
394 case 'a':
395 printcapabilities = true;
396 break;
397
398 case 'e':
399 printstates = true;
400 break;
401
402 case 'r':
403 runas = optarg;
404 break;
405
406 case 'R':
407 chroot = optarg;
408 break;
409
410 case 'S':
411 seccompdata = optarg;
412 break;
413
414 default:
415 usage(stderr, prgname, iface);
416 exit(EXIT_FAILURE);
417 }
418 }
419
420 if (optind < argc) {
421 logprintf(STDERR_FILENO,
422 "Unknown parameter '%s'\n", argv[optind]);
423 exit(EXIT_FAILURE);
424 }
425
426 if (chroot) {
427 if (do_chroot(chroot) < 0)
428 exit(EXIT_FAILURE);
429 }
430
431 /* change process ownership before accessing files */
432 if (runas) {
433 if (change_process_owner(runas) < 0)
434 exit(EXIT_FAILURE);
435 }
436
437 if (handle_log_options(logdata) < 0)
438 exit(EXIT_FAILURE);
439
440 if (mlp.fd >= 0 && mlp.fd < 3) {
441 /* no std{in,out,err} */
442 logprintf(STDERR_FILENO,
443 "Error: Cannot accept file descriptors with values 0, 1, or 2\n");
444 exit(EXIT_FAILURE);
445 }
446
447 if (printcapabilities) {
448 /*
449 * Choose the TPM version so that getting/setting buffer size works.
450 * Ignore failure, for backward compatibility when TPM 1.2 is disabled.
451 */
452 ret = capabilities_print_json(false, mlp.tpmversion);
453 exit(ret ? EXIT_FAILURE : EXIT_SUCCESS);
454 }
455
456 if (tpmlib_choose_tpm_version(mlp.tpmversion) != TPM_SUCCESS)
457 exit(EXIT_FAILURE);
458
459 if (handle_ctrlchannel_options(ctrlchdata, &mlp.cc) < 0 ||
460 handle_server_options(serverdata, &server) < 0) {
461 goto exit_failure;
462 }
463
464 tpmstate_set_version(mlp.tpmversion);
465
466 if (printstates) {
467 if (handle_tpmstate_options(tpmstatedata) < 0)
468 goto exit_failure;
469 if (tpmstatedata == NULL) {
470 logprintf(STDERR_FILENO,
471 "Error: --tpmstate option is required for --print-states\n");
472 goto exit_failure;
473 }
474 ret = SWTPM_NVRAM_PrintJson();
475 if (ret == 0)
476 goto exit_success;
477 else
478 goto exit_failure;
479 }
480
481 if (handle_key_options(keydata) < 0 ||
482 handle_migration_key_options(migkeydata) < 0 ||
483 handle_pid_options(piddata) < 0 ||
484 handle_locality_options(localitydata, &mlp.locality_flags) < 0 ||
485 handle_tpmstate_options(tpmstatedata) < 0 ||
486 handle_seccomp_options(seccompdata, &seccomp_action) < 0 ||
487 handle_flags_options(flagsdata, &need_init_cmd,
488 &mlp.startupType, &mlp.disable_auto_shutdown) < 0) {
489 goto exit_failure;
490 }
491
492 if (server) {
493 if (server_get_fd(server) >= 0) {
494 mlp.fd = server_set_fd(server, -1);
495 SWTPM_IO_SetSocketFD(mlp.fd);
496 }
497
498 mlp.flags |= MAIN_LOOP_FLAG_KEEP_CONNECTION;
499 if ((server_get_flags(server) & SERVER_FLAG_DISCONNECT))
500 mlp.flags &= ~MAIN_LOOP_FLAG_KEEP_CONNECTION;
501
502 if ((server_get_flags(server) & SERVER_FLAG_FD_GIVEN))
503 mlp.flags |= MAIN_LOOP_FLAG_TERMINATE | MAIN_LOOP_FLAG_USE_FD;
504 }
505
506 if (pidfile_write(getpid()) < 0) {
507 goto exit_failure;
508 }
509
510 setvbuf(stdout, 0, _IONBF, 0); /* output may be going through pipe */
511
512 #ifdef DEBUG
513 /* initialization */
514 start_time = time(NULL);
515 #endif
516
517 TPM_DEBUG("main: Initializing TPM at %s", ctime(&start_time));
518
519 tpmlib_debug_libtpms_parameters(mlp.tpmversion);
520
521 if ((rc = tpmlib_register_callbacks(&callbacks)))
522 goto error_no_tpm;
523
524 if (!need_init_cmd) {
525 if ((rc = tpmlib_start(0, mlp.tpmversion)))
526 goto error_no_tpm;
527 tpm_running = true;
528 }
529
530 if (install_sighandlers(notify_fd, sigterm_handler) < 0)
531 goto error_no_sighandlers;
532
533 if (create_seccomp_profile(false, seccomp_action) < 0)
534 goto error_seccomp_profile;
535
536 if (daemonize) {
537 daemonize_finish();
538 }
539
540 rc = mainLoop(&mlp, notify_fd[0]);
541
542 error_seccomp_profile:
543 uninstall_sighandlers();
544
545 error_no_sighandlers:
546 TPMLIB_Terminate();
547
548 error_no_tpm:
549 close(notify_fd[0]);
550 notify_fd[0] = -1;
551 close(notify_fd[1]);
552 notify_fd[1] = -1;
553
554 swtpm_cleanup(mlp.cc, server);
555
556 /* Fatal initialization errors cause the program to abort */
557 if (rc == 0) {
558 exit(EXIT_SUCCESS);
559 }
560 else {
561 TPM_DEBUG("main: TPM initialization failure %08x, exiting\n", rc);
562 exit(EXIT_FAILURE);
563 }
564
565 exit_failure:
566 swtpm_cleanup(mlp.cc, server);
567
568 exit(EXIT_FAILURE);
569
570 exit_success:
571 swtpm_cleanup(mlp.cc, server);
572
573 exit(EXIT_SUCCESS);
574 }