• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stefanberger / swtpm / #2935

15 Apr 2026 01:09PM UTC coverage: 73.485% (+0.07%) from 73.414%
#2935

push

travis-ci

web-flow
Merge fde6e50a4 into 8c3f99ce8

209 of 252 new or added lines in 2 files covered. (82.94%)

321 existing lines in 3 files now uncovered.

7824 of 10647 relevant lines covered (73.49%)

10090.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.92
/src/swtpm_setup/swtpm_setup.c
1
/* SPDX-License-Identifier: BSD-3-Clause */
2
/*
3
 * swtpm_setup.c: Tool to simulate TPM 1.2 & TPM 2 manufacturing
4
 *
5
 * Author: Stefan Berger, stefanb@linux.ibm.com
6
 *
7
 * Copyright (c) IBM Corporation, 2021 - 2026
8
 */
9

10
#include "config.h"
11

12
#include <errno.h>
13
#include <getopt.h>
14
#include <grp.h>
15
#include <limits.h>
16
#include <pwd.h>
17
#include <stdbool.h>
18
#include <stdlib.h>
19
#include <stdio.h>
20
#include <string.h>
21
#include <unistd.h>
22
#include <sys/stat.h>
23
#include <fcntl.h>
24
#include <sys/types.h>
25
#include <sys/wait.h>
26

27
#include <glib.h>
28
#include <glib/gstdio.h>
29
#include <glib/gprintf.h>
30

31
#include <glib-object.h>
32
#include <json-glib/json-glib.h>
33

34
#include <libtpms/tpm_nvfilename.h>
35

36
#include "profile.h"
37
#include "swtpm.h"
38
#include "swtpm_conf.h"
39
#include "swtpm_utils.h"
40
#include "swtpm_setup_utils.h"
41

42
#include <openssl/sha.h>
43

44
/* default values for passwords */
45
#define DEFAULT_OWNER_PASSWORD "ooo"
46
#define DEFAULT_SRK_PASSWORD   "sss"
47

48
#define SETUP_CREATE_EK_F           (1 << 0)
49
#define SETUP_TAKEOWN_F             (1 << 1)
50
#define SETUP_EK_CERT_F             (1 << 2)
51
#define SETUP_PLATFORM_CERT_F       (1 << 3)
52
#define SETUP_LOCK_NVRAM_F          (1 << 4)
53
#define SETUP_SRKPASS_ZEROS_F       (1 << 5)
54
#define SETUP_OWNERPASS_ZEROS_F     (1 << 6)
55
#define SETUP_STATE_OVERWRITE_F     (1 << 7)
56
#define SETUP_STATE_NOT_OVERWRITE_F (1 << 8)
57
#define SETUP_TPM2_F                (1 << 9)
58
#define SETUP_ALLOW_SIGNING_F       (1 << 10)
59
#define SETUP_TPM2_ECC_F            (1 << 11)
60
#define SETUP_CREATE_SPK_F          (1 << 12)
61
#define SETUP_DISPLAY_RESULTS_F     (1 << 13)
62
#define SETUP_DECRYPTION_F          (1 << 14)
63
#define SETUP_WRITE_EK_CERT_FILES_F (1 << 15)
64
#define SETUP_RECONFIGURE_F         (1 << 16)
65
#define SETUP_RSA_KEYSIZE_BY_USER_F (1 << 17)
66

67
/* default configuration file */
68
#define SWTPM_SETUP_CONF "swtpm_setup.conf"
69

70
/* Default logging goes to stderr */
71
gchar *gl_LOGFILE = NULL;
72

73
#define DEFAULT_RSA_KEYSIZE 2048
74

75
#define DEFAULT_EK1KEYALGO "rsa-2048"
76
#define DEFAULT_EK2KEYALGO "secp384r1"
77

78
static const struct flag_to_certfile {
79
    unsigned long flag;
80
    const char *filename;
81
    const char *type;
82
} flags_to_certfiles[] = {
83
    {.flag = SETUP_EK_CERT_F      , .filename = "ek.cert",       .type = "ek" },
84
    {.flag = SETUP_PLATFORM_CERT_F, .filename = "platform.cert", .type = "platform" },
85
    {.flag = 0,                     .filename = NULL,            .type = NULL},
86
};
87

88
static const struct {
89
    const char *name;
90
    enum keyalgo keyalgo;
91
    unsigned int keyalgo_param;
92
} keyalgo_choices[] = {
93
    { .name = "rsa-2048" , .keyalgo = KEYALGO_RSA, .keyalgo_param = 2048 },
94
    { .name = "rsa-3072" , .keyalgo = KEYALGO_RSA, .keyalgo_param = 3072 },
95
    { .name = "rsa-4096" , .keyalgo = KEYALGO_RSA, .keyalgo_param = 4096 },
96
    { .name = "secp384r1", .keyalgo = KEYALGO_ECC, .keyalgo_param = TPM2_ECC_NIST_P384 },
97
};
98

99
/* initialize the path of the config_file */
100
static int init(gchar **config_file)
187✔
101
{
102
    const gchar *configdir = g_get_user_config_dir();
187✔
103

104
    *config_file = g_build_filename(configdir, SWTPM_SETUP_CONF, NULL);
187✔
105
    if (access(*config_file, R_OK) != 0) {
187✔
106
        g_free(*config_file);
187✔
107
        *config_file = g_build_filename(SYSCONFDIR, SWTPM_SETUP_CONF, NULL);
187✔
108
    }
109

110
    return 0;
187✔
111
}
112

113
/* Get the spec and attributes parameters from swtpm */
114
static int tpm_get_specs_and_attributes(struct swtpm *swtpm, gchar ***params)
95✔
115
{
116
    int ret;
95✔
117
    g_autofree gchar *json = NULL;
190✔
118
    JsonParser *jp = NULL;
95✔
119
    GError *error = NULL;
95✔
120
    JsonReader *jr = NULL;
95✔
121
    JsonNode *root;
95✔
122
    static const struct parse_rule {
95✔
123
         const char *node1;
124
         const char *node2;
125
         gboolean is_int;
126
         const char *optname;
127
    } parser_rules[7] = {
128
         {"TPMSpecification", "family", FALSE, "--tpm-spec-family"},
129
         {"TPMSpecification", "level", TRUE, "--tpm-spec-level"},
130
         {"TPMSpecification", "revision", TRUE, "--tpm-spec-revision"},
131
         {"TPMAttributes", "manufacturer", FALSE, "--tpm-manufacturer"},
132
         {"TPMAttributes", "model", FALSE, "--tpm-model"},
133
         {"TPMAttributes", "version", FALSE, "--tpm-version"},
134
         {NULL, NULL, FALSE, NULL},
135
    };
136
    size_t idx;
95✔
137

138
    ret = swtpm->cops->ctrl_get_tpm_specs_and_attrs(swtpm, &json);
95✔
139
    if (ret != 0) {
95✔
UNCOV
140
        logerr(gl_LOGFILE, "Could not get the TPM spec and attribute parameters.\n");
×
UNCOV
141
        return 1;
×
142
    }
143

144
    jp = json_parser_new();
95✔
145

146
    if (!json_parser_load_from_data(jp, json, -1, &error)) {
95✔
UNCOV
147
        logerr(gl_LOGFILE, "JSON parser failed: %s\n", error->message);
×
UNCOV
148
        g_error_free(error);
×
UNCOV
149
        goto error;
×
150
    }
151

152
    *params = NULL;
95✔
153
    root = json_parser_get_root(jp);
95✔
154

155
    for (idx = 0; parser_rules[idx].node1 != NULL; idx++) {
760✔
156
        jr = json_reader_new(root);
570✔
157
        if (json_reader_read_member(jr, parser_rules[idx].node1) &&
1,140✔
158
            json_reader_read_member(jr, parser_rules[idx].node2)) {
570✔
159
            gchar *str;
570✔
160

161
            if (parser_rules[idx].is_int)
570✔
162
                str = g_strdup_printf("%ld", (long)json_reader_get_int_value(jr));
190✔
163
            else
164
                str = g_strdup(json_reader_get_string_value(jr));
380✔
165

166
            *params = concat_varrays(*params,
1,710✔
167
                                    (gchar*[]){
570✔
168
                                        g_strdup(parser_rules[idx].optname),
1,140✔
169
                                        str,
170
                                        NULL
171
                                    }, TRUE);
172
        } else {
UNCOV
173
            logerr(gl_LOGFILE, "Could not find [%s][%s] in '%s'\n",
×
UNCOV
174
                   parser_rules[idx].node1, parser_rules[idx].node2, json);
×
UNCOV
175
            ret = 1;
×
UNCOV
176
            break;
×
177
        }
178
        g_object_unref(jr);
570✔
179
        jr = NULL;
570✔
180
    }
181

UNCOV
182
    if (ret) {
×
UNCOV
183
        g_strfreev(*params);
×
UNCOV
184
        *params = NULL;
×
UNCOV
185
        g_object_unref(jr);
×
186
    }
187
error:
95✔
188
    g_object_unref(jp);
95✔
189

190
    return ret;
95✔
191
}
192

193
/* Call an external tool to create the certificates */
194
static int call_create_certs(unsigned long flags, unsigned int cert_flags,
95✔
195
                             const gchar *configfile, const gchar *certsdir,
196
                             const gchar *ekparam, const gchar *vmid, struct swtpm *swtpm)
197
{
198
    gchar **config_file_lines = NULL; /* must free */
95✔
199
    g_autofree gchar *create_certs_tool = NULL;
190✔
200
    g_autofree gchar *create_certs_tool_config = NULL;
95✔
201
    g_autofree gchar *create_certs_tool_options = NULL;
95✔
202
    g_autofree const gchar **cmd = NULL;
95✔
203
    gchar **params = NULL; /* must free */
95✔
204
    g_autofree gchar *prgname = NULL;
95✔
205
    gboolean success;
95✔
206
    gint exit_status;
95✔
207
    size_t idx, j;
95✔
208
    gchar *s;
95✔
209
    int ret;
95✔
210

211
    ret = tpm_get_specs_and_attributes(swtpm, &params);
95✔
212
    if (ret != 0)
95✔
UNCOV
213
        goto error;
×
214

215
    ret = read_file_lines(configfile, &config_file_lines);
95✔
216
    if (ret != 0)
95✔
UNCOV
217
        goto error;
×
218

219
    create_certs_tool = get_config_value(config_file_lines, "create_certs_tool");
95✔
220
    create_certs_tool_config = get_config_value(config_file_lines, "create_certs_tool_config");
95✔
221
    create_certs_tool_options = get_config_value(config_file_lines, "create_certs_tool_options");
95✔
222

223
    ret = 0;
95✔
224

225
    if (create_certs_tool != NULL) {
95✔
226
        g_autofree gchar *create_certs_tool_path = g_find_program_in_path(create_certs_tool);
190✔
227
        if (create_certs_tool_path == NULL) {
95✔
UNCOV
228
            logerr(gl_LOGFILE, "Could not find %s in PATH.\n", create_certs_tool);
×
UNCOV
229
            ret = 1;
×
UNCOV
230
            goto error;
×
231
        }
232

233
        if (flags & SETUP_TPM2_F) {
95✔
234
            params = concat_varrays(params,
174✔
235
                                (gchar*[]){
87✔
236
                                    g_strdup("--tpm2"),
87✔
237
                                    NULL
238
                                }, TRUE);
239
        }
240
        cmd = concat_arrays((const gchar*[]) {
95✔
241
                                create_certs_tool_path,
242
                                "--type", "_",  /* '_' must be at index '2' ! */
243
                                "--ek", ekparam,
244
                                "--dir", certsdir,
245
                                NULL
246
                            }, NULL, FALSE);
247

248
        if (flags & SETUP_ALLOW_SIGNING_F) {
95✔
249
            cmd = concat_arrays(cmd, (const gchar*[]){"--allow-signing", NULL}, TRUE);
42✔
250
            /* once --allow-signing is passed we need to pass --decryption also */
251
            if (flags & SETUP_DECRYPTION_F)
42✔
252
                cmd = concat_arrays(cmd, (const gchar*[]){"--decryption", NULL}, TRUE);
14✔
253
        }
254
        if (gl_LOGFILE != NULL)
95✔
255
            cmd = concat_arrays(cmd, (const gchar*[]){"--logfile", gl_LOGFILE, NULL}, TRUE);
11✔
256
        if (vmid != NULL)
95✔
257
            cmd = concat_arrays(cmd, (const gchar*[]){"--vmid", vmid, NULL}, TRUE);
75✔
258
        cmd = concat_arrays(cmd, (const char **)params, TRUE);
95✔
259
        if (create_certs_tool_config != NULL)
95✔
260
            cmd = concat_arrays(cmd, (const gchar*[]){"--configfile", create_certs_tool_config, NULL}, TRUE);
11✔
261
        if (create_certs_tool_options != NULL)
95✔
262
            cmd = concat_arrays(cmd, (const gchar*[]){"--optsfile", create_certs_tool_options, NULL}, TRUE);
11✔
263

264
        s = g_strrstr(create_certs_tool, G_DIR_SEPARATOR_S);
95✔
265
        if (s)
95✔
266
            prgname = strdup(&s[1]);
11✔
267
        else
268
            prgname = strdup(create_certs_tool);
84✔
269

270
        for (idx = 0; flags_to_certfiles[idx].filename != NULL; idx++) {
285✔
271
            if (cert_flags & flags_to_certfiles[idx].flag) {
190✔
272
                g_autofree gchar *standard_output = NULL;
146✔
273
                g_autofree gchar *standard_error = NULL;
146✔
274
                GError *error = NULL;
146✔
275
                gchar **lines;
146✔
276

277
                cmd[2] = (gchar *)flags_to_certfiles[idx].type; /* replaces the "_" above */
146✔
278

279
                s = g_strjoinv(" ", (char **)cmd);
146✔
280
                logit(gl_LOGFILE, "  Invoking %s\n", s);
146✔
281
                g_free(s);
146✔
282

283
                success = spawn_sync(NULL, cmd, NULL, 0, NULL, NULL,
146✔
284
                                     &standard_output, &standard_error, &exit_status, &error);
285
                if (!success) {
146✔
UNCOV
286
                    logerr(gl_LOGFILE, "An error occurred running %s: %s\n",
×
UNCOV
287
                           create_certs_tool, error->message);
×
UNCOV
288
                    g_error_free(error);
×
UNCOV
289
                    ret = 1;
×
UNCOV
290
                    break;
×
291
                } else if (exit_status != 0) {
146✔
UNCOV
292
                    logerr(gl_LOGFILE, "%s exit with status %d: %s\n",
×
UNCOV
293
                           prgname, WEXITSTATUS(exit_status), standard_error);
×
UNCOV
294
                    ret = 1;
×
UNCOV
295
                    break;
×
296
                }
297

298
                lines = g_strsplit(standard_output, "\n", -1);
146✔
299
                for (j = 0; lines[j] != NULL; j++) {
292✔
300
                    if (strlen(lines[j]) > 0)
×
301
                        logit(gl_LOGFILE, "%s: %s\n", prgname, lines[j]);
×
302
                }
303
                g_strfreev(lines);
146✔
304

305
                SWTPM_G_FREE(standard_output);
146✔
306
                SWTPM_G_FREE(standard_error);
146✔
307
            }
308
        }
309
    }
310

UNCOV
311
error:
×
312
    g_strfreev(config_file_lines);
95✔
313
    g_strfreev(params);
95✔
314

315
    return ret;
95✔
316
}
317

318
static char *create_certfile_name(const gchar *user_certsdir,
11✔
319
                                  const gchar *key_type,
320
                                  const gchar *key_description)
321
{
322
    g_autofree gchar *filename = g_strdup_printf("%s-%s.crt", key_type, key_description);
11✔
323

324
    return g_strjoin(G_DIR_SEPARATOR_S, user_certsdir, filename, NULL);
11✔
325
}
326

327
/*
328
 * Remove the cert file unless the user wants a copy of it.
329
 */
330
static int certfile_move_or_delete(unsigned long flags, gboolean preserve, const gchar *certfile,
146✔
331
                                   const gchar *user_certsdir, const gchar *key_type,
332
                                   const gchar *key_description)
333
{
334
    g_autofree gchar *content = NULL;
292✔
335
    g_autofree gchar *cf = NULL;
146✔
336
    gsize content_length;
146✔
337
    GError *error = NULL;
146✔
338
    size_t offset = 0;
146✔
339

340
    if (preserve && (flags & SETUP_WRITE_EK_CERT_FILES_F) && user_certsdir != NULL) {
146✔
341
        if (!g_file_get_contents(certfile, &content, &content_length, &error))
11✔
UNCOV
342
            goto error;
×
343

344
        cf = create_certfile_name(user_certsdir, key_type, key_description);
11✔
345
        if (!(flags & SETUP_TPM2_F)) {
11✔
346
            /* A TPM 1.2 certificate has a 7 byte header at the beginning
347
             * that we now remove */
348
            if (content_length >= 8)
1✔
349
                offset = 7;
11✔
350
        }
351
        if (!g_file_set_contents(cf, &content[offset], content_length - offset,
11✔
352
                                 &error))
UNCOV
353
            goto error;
×
354
        if (g_chmod(cf, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
11✔
UNCOV
355
            logerr(gl_LOGFILE, "Failed to chmod file '%s': %s\n", cf, strerror(errno));
×
356
            goto error_unlink;
×
357
        }
358
    }
359
    unlink(certfile);
146✔
360

361
    return 0;
146✔
362

UNCOV
363
error:
×
UNCOV
364
    logerr(gl_LOGFILE, "%s\n", error->message);
×
UNCOV
365
    g_error_free(error);
×
366

367
error_unlink:
×
UNCOV
368
    unlink(certfile);
×
369

370
    return 1;
×
371
}
372

373
static int read_certificate_file(const gchar *certsdir, const gchar *filename,
146✔
374
                                 gchar **filecontent, gsize *filecontent_len,
375
                                 gchar **certfile)
376
{
377
    *certfile = g_strjoin(G_DIR_SEPARATOR_S, certsdir, filename, NULL);
146✔
378

379
    return read_file(*certfile, filecontent, filecontent_len);
146✔
380
}
381

382
/*
383
 * Read the certificate from the file where swtpm_cert left it.
384
 * Write the file into the TPM's NVRAM and, if the user wants it,
385
 * copy it into a user-provided directory.
386
 */
387
static int tpm2_persist_certificate(unsigned long flags, const gchar *certsdir,
131✔
388
                                    const struct flag_to_certfile *ftc,
389
                                    enum keyalgo keyalgo, unsigned int keyalgo_param,
390
                                    struct swtpm2 *swtpm2, const gchar *user_certsdir,
391
                                    const gchar *key_type, const gchar *key_description)
392
{
393
    g_autofree gchar *filecontent = NULL;
262✔
394
    g_autofree gchar *certfile = NULL;
131✔
395
    gsize filecontent_len;
131✔
396
    int ret;
131✔
397

398
    ret = read_certificate_file(certsdir, ftc->filename,
131✔
399
                                &filecontent, &filecontent_len, &certfile);
400
    if (ret != 0)
131✔
UNCOV
401
        goto error_unlink;
×
402

403
    if (ftc->flag == SETUP_EK_CERT_F) {
131✔
404
        ret = swtpm2->ops->write_ek_cert_nvram(&swtpm2->swtpm,
87✔
405
                                     keyalgo, keyalgo_param,
406
                                     !!(flags & SETUP_LOCK_NVRAM_F),
87✔
407
                                     (const unsigned char*)filecontent, filecontent_len);
408
    } else {
409
        ret = swtpm2->ops->write_platform_cert_nvram(&swtpm2->swtpm,
44✔
410
                                     !!(flags & SETUP_LOCK_NVRAM_F),
44✔
411
                                     (const unsigned char *)filecontent, filecontent_len);
412
    }
413

414
    if (ret != 0)
131✔
415
        goto error_unlink;
×
416

417
    return certfile_move_or_delete(flags, !!(ftc->flag & SETUP_EK_CERT_F),
131✔
418
                                   certfile, user_certsdir,
419
                                   key_type, key_description);
420

UNCOV
421
error_unlink:
×
UNCOV
422
    unlink(certfile);
×
UNCOV
423
    return 1;
×
424
}
425

426
/* Create EK and certificate for a TPM 2 */
427
static int tpm2_create_ek_and_cert(unsigned long flags, const gchar *config_file,
233✔
428
                                   const gchar *certsdir, const gchar *vmid,
429
                                   enum keyalgo keyalgo, unsigned int keyalgo_param,
430
                                   struct swtpm2 *swtpm2, const gchar *user_certsdir)
431
{
432
    const char *key_description = "";
233✔
433
    g_autofree gchar *ekparam = NULL;
466✔
434
    unsigned long cert_flags;
233✔
435
    const gchar *key_type;
233✔
436
    size_t idx;
233✔
437
    int ret;
233✔
438

439
    if (flags & SETUP_CREATE_EK_F) {
233✔
440
        ret = swtpm2->ops->create_ek(&swtpm2->swtpm, keyalgo, keyalgo_param,
202✔
441
                                     !!(flags & SETUP_ALLOW_SIGNING_F),
101✔
442
                                     !!(flags & SETUP_DECRYPTION_F),
101✔
443
                                     !!(flags & SETUP_LOCK_NVRAM_F),
101✔
444
                                     &ekparam, &key_description);
445
        if (ret != 0)
101✔
446
            return 1;
447
    }
448

449
    /* Only look at ek and platform certs here */
450
    cert_flags = flags & (SETUP_EK_CERT_F | SETUP_PLATFORM_CERT_F);
233✔
451
    if (cert_flags) {
233✔
452
        ret = call_create_certs(flags, cert_flags, config_file, certsdir, ekparam,
87✔
453
                                vmid, &swtpm2->swtpm);
454
        if (ret != 0)
87✔
455
            return 1;
456

457
        for (idx = 0; flags_to_certfiles[idx].filename; idx++) {
261✔
458
            if (cert_flags & flags_to_certfiles[idx].flag) {
174✔
459
                key_type = flags_to_certfiles[idx].flag & SETUP_EK_CERT_F ? "ek" : "";
131✔
460

461
                ret = tpm2_persist_certificate(flags, certsdir, &flags_to_certfiles[idx],
131✔
462
                                               keyalgo, keyalgo_param, swtpm2,
463
                                               user_certsdir, key_type, key_description);
464
                if (ret)
131✔
465
                    return 1;
466
            }
467
        }
468
    }
469

470
    return 0;
471
}
472

473
/* Create endorsement keys and certificates for a TPM 2 */
474
static int tpm2_create_eks_and_certs(unsigned long flags, const gchar *config_file,
117✔
475
                                     const gchar *certsdir, const gchar *vmid,
476
                                     enum keyalgo ek1keyalgo, unsigned int ek1keyalgo_param,
477
                                     enum keyalgo ek2keyalgo, unsigned int ek2keyalgo_param,
478
                                     struct swtpm2 *swtpm2, const gchar *user_certsdir)
479
{
480
     int ret;
117✔
481

482
     ret = tpm2_create_ek_and_cert(flags, config_file, certsdir, vmid, ek1keyalgo,
117✔
483
                                   ek1keyalgo_param, swtpm2, user_certsdir);
484
     if (ret != 0)
117✔
485
         return 1;
486

487
     /* two keys the same -- create only one */
488
     if (ek1keyalgo_param == ek2keyalgo_param && ek1keyalgo == ek2keyalgo)
117✔
489
         return 0;
490

491
     /* platform cert only with EK1 */
492
     flags &= ~SETUP_PLATFORM_CERT_F;
116✔
493
     return tpm2_create_ek_and_cert(flags, config_file, certsdir, vmid, ek2keyalgo,
116✔
494
                                    ek2keyalgo_param, swtpm2, user_certsdir);
495
}
496

497
/* Get the default PCR banks from the config file and if nothing can
498
   be found there use the DEFAULT_PCR_BANKS #define.
499
 */
500
static gchar *get_default_pcr_banks(gchar *const *config_file_lines)
149✔
501
{
502
    gchar *pcr_banks;
149✔
503

504
    pcr_banks = get_config_value(config_file_lines, "active_pcr_banks");
149✔
505
    if (pcr_banks)
149✔
506
        g_strstrip(pcr_banks);
27✔
507
    if (pcr_banks == NULL || strlen(pcr_banks) == 0) {
27✔
508
        g_free(pcr_banks);
122✔
509
        pcr_banks = g_strdup(DEFAULT_PCR_BANKS);
122✔
510
    }
511
    return pcr_banks;
149✔
512
}
513

514
/* Get the default RSA keysize from the config file */
515
static gchar *get_default_rsa_keysize(gchar *const *config_file_lines)
105✔
516
{
517
    gchar *rsa_keysize;
105✔
518

519
    rsa_keysize = get_config_value(config_file_lines, "rsa_keysize");
105✔
520
    if (rsa_keysize)
105✔
521
        g_strstrip(rsa_keysize);
6✔
522
    if (rsa_keysize == NULL || strlen(rsa_keysize) == 0) {
6✔
523
        g_free(rsa_keysize);
99✔
524
        rsa_keysize = g_strdup_printf("%d", DEFAULT_RSA_KEYSIZE);
99✔
525
    }
526
    return rsa_keysize;
105✔
527
}
528

529
/* Get the default profile from the config file */
530
static gchar *get_default_profile(gchar *const *config_file_lines)
43✔
531
{
532
    gchar *profile;
43✔
533

534
    profile = get_config_value(config_file_lines, "profile");
43✔
535
    if (profile)
43✔
536
        g_strstrip(profile);
13✔
537
    return profile;
43✔
538
}
539

540
/* If available, open the default profile and return its file descriptor */
541
static int get_default_profile_fd(gchar *const *config_file_lines)
43✔
542
{
543
    g_autofree gchar *profile_file = NULL;
86✔
544
    int fd;
43✔
545

546
    profile_file = get_config_value(config_file_lines, "profile_file");
43✔
547
    if (!profile_file)
43✔
548
        return -1;
549

UNCOV
550
    fd = open(profile_file, O_RDONLY);
×
UNCOV
551
    if (fd < 0) {
×
UNCOV
552
        logerr(gl_LOGFILE, "Could not read default profile '%s': %s",
×
UNCOV
553
               profile_file, strerror(errno));
×
UNCOV
554
        return -2;
×
555
    }
556
    return fd;
557
}
558

559
/* Activate the given list of PCR banks. If pcr_banks is '-' then leave
560
 * the configuration as-is.
561
 */
562
static int tpm2_activate_pcr_banks(struct swtpm2 *swtpm2,
123✔
563
                                   const gchar *pcr_banks)
564
{
565
    g_autofree gchar *active_pcr_banks_join = NULL;
246✔
566
    g_autofree gchar *all_pcr_banks_join = NULL;
123✔
567
    g_auto(GStrv) active_pcr_banks = NULL;
123✔
568
    g_auto(GStrv) all_pcr_banks = NULL;
123✔
569
    g_auto(GStrv) pcr_banks_l = NULL;
123✔
570
    struct swtpm *swtpm = &swtpm2->swtpm;
123✔
571
    int ret = 0;
123✔
572

573
    if (g_str_equal(pcr_banks, "-"))
123✔
574
        return 0;
575

576
    ret = swtpm2->ops->get_all_pcr_banks(swtpm, &all_pcr_banks);
123✔
577
    if (ret != 0)
123✔
578
        return ret;
579

580
    pcr_banks_l = g_strsplit(pcr_banks, ",", -1);
123✔
581
    ret = swtpm2->ops->set_active_pcr_banks(swtpm, pcr_banks_l, all_pcr_banks,
123✔
582
                                            &active_pcr_banks);
583
    if (ret != 0)
123✔
584
        return ret;
585

586
    active_pcr_banks_join = g_strjoinv(",", active_pcr_banks);
122✔
587
    all_pcr_banks_join = g_strjoinv(",", all_pcr_banks);
122✔
588
    logit(gl_LOGFILE, "Successfully activated PCR banks %s among %s.\n",
122✔
589
          active_pcr_banks_join, all_pcr_banks_join);
590

591
    return 0;
122✔
592
}
593

594
static int log_active_profile(struct swtpm2 *swtpm2)
123✔
595
{
596
    g_autofree gchar *profile = NULL;
246✔
597
    char *tmp;
123✔
598

599
    profile = swtpm2->ops->get_active_profile(&swtpm2->swtpm);
123✔
600
    if (!profile) {
123✔
601
        logerr(gl_LOGFILE, "Could not get active profile.\n");
6✔
602
        return 1;
6✔
603
    }
604
    /* Strip out surrounding '{"ActiveProfile":<to display>} */
605
    tmp = strrchr(profile, '}');
117✔
606
    if (!tmp)
117✔
UNCOV
607
        goto malformatted;
×
608
    *tmp = 0;
117✔
609

610
    tmp = strchr(profile, ':');
117✔
611
    if (!tmp)
117✔
UNCOV
612
        goto malformatted;
×
613

614
    logit(gl_LOGFILE, "Active profile: %s\n", tmp + 1);
117✔
615
    return 0;
117✔
616

UNCOV
617
malformatted:
×
UNCOV
618
    logerr(gl_LOGFILE, "Malformatted active profile");
×
UNCOV
619
    return 1;
×
620
}
621

622
/* Simulate manufacturing a TPM 2: create keys and certificates */
623
static int init_tpm2(unsigned long flags, gchar **swtpm_prg_l, const gchar *config_file,
130✔
624
                     const gchar *tpm2_state_path, const gchar *vmid, const gchar *pcr_banks,
625
                     const gchar *swtpm_keyopt, int *fds_to_pass, size_t n_fds_to_pass,
626
                     enum keyalgo ek1keyalgo, unsigned int ek1keyalgo_param,
627
                     enum keyalgo ek2keyalgo, unsigned int ek2keyalgo_param,
628
                     const gchar *certsdir, const gchar *user_certsdir,
629
                     const gchar *json_profile,
630
                     int json_profile_fd, const gchar *profile_remove_disabled_param)
631
{
632
    unsigned int keyalgo_param;
130✔
633
    struct swtpm2 *swtpm2;
130✔
634
    enum keyalgo keyalgo;
130✔
635
    struct swtpm *swtpm;
130✔
636
    int ret;
130✔
637

638
    swtpm2 = swtpm2_new(swtpm_prg_l, tpm2_state_path, swtpm_keyopt, gl_LOGFILE,
130✔
639
                        fds_to_pass, n_fds_to_pass, json_profile, json_profile_fd,
640
                        profile_remove_disabled_param);
641
    if (swtpm2 == NULL)
130✔
642
        return 1;
643
    swtpm = &swtpm2->swtpm;
130✔
644

645
    ret = swtpm->cops->start(swtpm);
130✔
646
    if (ret != 0) {
130✔
647
        logerr(gl_LOGFILE, "Could not start the TPM 2.\n");
1✔
648
        goto error;
1✔
649
    }
650

651
    if (!(flags & SETUP_RECONFIGURE_F)) {
129✔
652
        ret = log_active_profile(swtpm2);
123✔
653
        if (ret)
123✔
654
            goto error;
6✔
655

656
        if ((flags & SETUP_CREATE_SPK_F)) {
117✔
657
            if ((flags & SETUP_TPM2_ECC_F)) {
9✔
658
                keyalgo = KEYALGO_ECC;
659
                keyalgo_param = TPM2_ECC_NIST_P384;
660
            } else {
661
                keyalgo = KEYALGO_RSA;
7✔
662
                keyalgo_param = 3072;
7✔
663
            }
664
            ret = swtpm2->ops->create_spk(swtpm, keyalgo, keyalgo_param);
9✔
665
            if (ret != 0)
9✔
UNCOV
666
                goto destroy;
×
667
        }
668

669
        ret = tpm2_create_eks_and_certs(flags, config_file, certsdir, vmid,
117✔
670
                                        ek1keyalgo, ek1keyalgo_param,
671
                                        ek2keyalgo, ek2keyalgo_param,
672
                                        swtpm2, user_certsdir);
673
        if (ret != 0)
117✔
UNCOV
674
            goto destroy;
×
675
    }
676

677
    ret = tpm2_activate_pcr_banks(swtpm2, pcr_banks);
123✔
678
    if (ret != 0)
123✔
679
        goto destroy;
1✔
680

681
    ret = swtpm2->ops->shutdown(swtpm);
122✔
682

683
destroy:
123✔
684
    swtpm->cops->destroy(swtpm);
123✔
685

686
error:
130✔
687
    swtpm_free(swtpm);
130✔
688

689
    return ret;
130✔
690
}
691

692
/* Create the owner password digest */
693
static void tpm12_get_ownerpass_digest(unsigned long flags, const gchar *ownerpass,
9✔
694
                                       unsigned char ownerpass_digest[SHA_DIGEST_LENGTH])
695
{
696
    const gchar zeros[SHA_DIGEST_LENGTH]= {0, };
9✔
697
    size_t len;
9✔
698

699
    if (ownerpass == NULL) {
9✔
700
        if (flags & SETUP_OWNERPASS_ZEROS_F) {
2✔
701
            ownerpass = zeros;
702
            len = sizeof(zeros);
703
        } else {
704
            ownerpass = DEFAULT_OWNER_PASSWORD;
×
UNCOV
705
            len = strlen(ownerpass);
×
706
        }
707
    } else {
708
        len = strlen(ownerpass);
7✔
709
    }
710
    SHA1((const unsigned char *)ownerpass, len, ownerpass_digest);
9✔
711
}
9✔
712

713
/* Create the SRK password digest */
714
static void tpm12_get_srkpass_digest(unsigned long flags, const gchar *srkpass,
9✔
715
                                     unsigned char srkpass_digest[SHA_DIGEST_LENGTH])
716
{
717
    const gchar zeros[SHA_DIGEST_LENGTH]= {0, };
9✔
718
    size_t len;
9✔
719

720
    if (srkpass == NULL) {
9✔
721
        if (flags & SETUP_SRKPASS_ZEROS_F) {
2✔
722
            srkpass = zeros;
723
            len = sizeof(zeros);
724
        } else {
UNCOV
725
            srkpass = DEFAULT_SRK_PASSWORD;
×
UNCOV
726
            len = strlen(srkpass);
×
727
        }
728
    } else {
729
        len = strlen(srkpass);
7✔
730
    }
731
    SHA1((const unsigned char *)srkpass, len, srkpass_digest);
9✔
732
}
9✔
733

734
/* Take ownership of a TPM 1.2 */
735
static int tpm12_take_ownership(unsigned long flags, const gchar *ownerpass,
9✔
736
                                const gchar *srkpass, gchar *pubek, size_t pubek_len,
737
                                struct swtpm12 *swtpm12)
738
{
739
    unsigned char ownerpass_digest[SHA_DIGEST_LENGTH];
9✔
740
    unsigned char srkpass_digest[SHA_DIGEST_LENGTH];
9✔
741

742
    tpm12_get_ownerpass_digest(flags, ownerpass, ownerpass_digest);
9✔
743
    tpm12_get_srkpass_digest(flags, srkpass, srkpass_digest);
9✔
744

745
    return swtpm12->ops->take_ownership(&swtpm12->swtpm, ownerpass_digest, srkpass_digest,
9✔
746
                                        (const unsigned char *)pubek, pubek_len);
747
}
748

749
/* Create the certificates for a TPM 1.2 */
750
static int tpm12_create_certs(unsigned long flags, const gchar *config_file,
8✔
751
                              const gchar *certsdir, const gchar *ekparam,
752
                              const gchar *vmid, struct swtpm12 *swtpm12,
753
                              const gchar *user_certsdir)
754
{
755
    g_autofree gchar *filecontent = NULL;
16✔
756
    g_autofree gchar *certfile = NULL;
8✔
757
    unsigned int cert_flags;
8✔
758
    const gchar *key_type;
8✔
759
    gsize filecontent_len;
8✔
760
    size_t idx;
8✔
761
    int ret;
8✔
762

763
    /* TPM 1.2 only has ek and platform certs */
764
    cert_flags = flags & (SETUP_EK_CERT_F | SETUP_PLATFORM_CERT_F);
8✔
765

766
    ret = call_create_certs(flags, cert_flags, config_file, certsdir, ekparam,
8✔
767
                            vmid, &swtpm12->swtpm);
768
    if (ret != 0)
8✔
769
        return 1;
770

771
    for (idx = 0; flags_to_certfiles[idx].filename; idx++) {
24✔
772
        if (cert_flags & flags_to_certfiles[idx].flag) {
16✔
773
            SWTPM_G_FREE(filecontent);
15✔
774
            SWTPM_G_FREE(certfile);
15✔
775

776
            ret = read_certificate_file(certsdir, flags_to_certfiles[idx].filename,
15✔
777
                                        &filecontent, &filecontent_len, &certfile);
778
            if (ret != 0)
15✔
779
                return 1;
780

781
            if (flags_to_certfiles[idx].flag == SETUP_EK_CERT_F) {
15✔
782
                ret = swtpm12->ops->write_ek_cert_nvram(&swtpm12->swtpm,
8✔
783
                                                (const unsigned char*)filecontent, filecontent_len);
784
                if (ret == 0)
8✔
785
                    logit(gl_LOGFILE, "Successfully created NVRAM area for EK certificate.\n");
8✔
786
            } else {
787
                ret = swtpm12->ops->write_platform_cert_nvram(&swtpm12->swtpm,
7✔
788
                                                  (const unsigned char*)filecontent, filecontent_len);
789
                if (ret == 0)
7✔
790
                    logit(gl_LOGFILE, "Successfully created NVRAM area for Platform certificate.\n");
7✔
791
            }
792

793
            if (ret != 0) {
15✔
UNCOV
794
                unlink(certfile);
×
UNCOV
795
                return 1;
×
796
            }
797

798
            key_type = flags_to_certfiles[idx].flag & SETUP_EK_CERT_F ? "ek" : "";
15✔
799

800
            if (certfile_move_or_delete(flags, !!(flags_to_certfiles[idx].flag & SETUP_EK_CERT_F),
15✔
801
                                        certfile, user_certsdir, key_type, "rsa2048") != 0)
802
                return 1;
803
        }
804
    }
805

806
    return 0;
807
}
808

809
/* Simulate manufacturing a TPM 1.2: create keys and certificate and possibly take ownership */
810
static int init_tpm(unsigned long flags, gchar **swtpm_prg_l, const gchar *config_file,
26✔
811
                    const gchar *tpm_state_path, const gchar *ownerpass, const gchar *srkpass,
812
                    const gchar *vmid, const gchar *swtpm_keyopt,
813
                    int *fds_to_pass, size_t n_fds_to_pass, const gchar *certsdir,
814
                    const gchar *user_certsdir)
815
{
816
    struct swtpm12 *swtpm12;
26✔
817
    struct swtpm *swtpm;
26✔
818
    g_autofree gchar *pubek = NULL;
52✔
819
    size_t pubek_len = 0;
26✔
820
    int ret = 1;
26✔
821

822
    swtpm12 = swtpm12_new(swtpm_prg_l, tpm_state_path, swtpm_keyopt, gl_LOGFILE,
26✔
823
                          fds_to_pass, n_fds_to_pass);
824
    if (swtpm12 == NULL)
26✔
825
        return 1;
826
    swtpm = &swtpm12->swtpm;
26✔
827

828
    ret = swtpm->cops->start(swtpm);
26✔
829
    if (ret != 0) {
26✔
UNCOV
830
        logerr(gl_LOGFILE, "Could not start the TPM 1.2.\n");
×
UNCOV
831
        goto error;
×
832
    }
833

834
    ret = swtpm12->ops->run_swtpm_bios(swtpm);
26✔
835
    if (ret != 0)
26✔
UNCOV
836
         goto destroy;
×
837

838
    if ((flags & SETUP_CREATE_EK_F)) {
26✔
839
        ret = swtpm12->ops->create_endorsement_key_pair(swtpm, &pubek, &pubek_len);
19✔
840
        if (ret != 0)
19✔
UNCOV
841
            goto destroy;
×
842

843
        logit(gl_LOGFILE, "Successfully created EK.\n");
19✔
844

845
        /* can only take owernship if created an EK */
846
        if ((flags & SETUP_TAKEOWN_F)) {
19✔
847
            ret = tpm12_take_ownership(flags, ownerpass, srkpass, pubek, pubek_len, swtpm12);
9✔
848
            if (ret != 0)
9✔
UNCOV
849
                goto destroy;
×
850

851
            logit(gl_LOGFILE, "Successfully took ownership of the TPM.\n");
9✔
852
        }
853

854
        /* can only create EK cert if created an EK */
855
        if ((flags & SETUP_EK_CERT_F)) {
19✔
856
            g_autofree gchar *ekparam = print_as_hex((unsigned char *)pubek, pubek_len);
16✔
857

858
            ret = tpm12_create_certs(flags, config_file, certsdir, ekparam, vmid, swtpm12,
8✔
859
                                     user_certsdir);
860
            if (ret != 0)
8✔
861
                goto destroy;
×
862
        }
863
    }
864

865
    if ((flags & SETUP_LOCK_NVRAM_F)) {
26✔
866
        ret = swtpm12->ops->nv_lock(swtpm);
12✔
867
        if (ret == 0)
12✔
868
            logit(gl_LOGFILE, "Successfully locked NVRAM access.\n");
12✔
869
    }
870

871
destroy:
14✔
872
    swtpm->cops->destroy(swtpm);
26✔
873

874
error:
26✔
875
    swtpm_free(swtpm);
26✔
876

877
    return ret;
26✔
878
}
879

880
/* Check whether we are allowed to overwrite existing state.
881
 * This function returns 2 if the state exists but flag is set to not to overwrite it,
882
 * 0 in case we can overwrite it, 1 if the state exists.
883
 */
884
static int check_state_overwrite(const gchar **swtpm_prg_l, unsigned int flags,
156✔
885
                                 const char *tpm_state_path)
886
{
887
    gboolean success;
156✔
888
    g_autofree gchar *standard_output = NULL;
312✔
889
    int exit_status = 0;
156✔
890
    g_autoptr(GError) error = NULL;
156✔
891
    g_autofree const gchar **argv = NULL;
156✔
892
    g_autofree gchar *statearg = g_strdup_printf("backend-uri=%s", tpm_state_path);
312✔
893
    g_autofree gchar *logop = NULL;
156✔
894
    g_autofree const gchar **my_argv = NULL;
156✔
895

896
    my_argv = concat_arrays((const gchar*[]) {
156✔
897
                                "--print-states",
898
                                "--tpmstate",
899
                                statearg,
900
                                NULL
901
                            }, NULL, FALSE);
902

903
    if (flags & SETUP_TPM2_F)
156✔
904
        my_argv = concat_arrays(my_argv, (const gchar*[]) { "--tpm2", NULL }, TRUE);
127✔
905

906
    if (gl_LOGFILE != NULL) {
156✔
907
        logop = g_strdup_printf("file=%s", gl_LOGFILE);
87✔
908
        my_argv = concat_arrays(my_argv, (const gchar*[]){"--log", logop, NULL}, TRUE);
87✔
909
    }
910

911
    argv = concat_arrays(swtpm_prg_l, my_argv, FALSE);
156✔
912

913
    success = spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL,
156✔
914
                         &standard_output, NULL, &exit_status, &error);
915
    if (!success) {
156✔
UNCOV
916
        logerr(gl_LOGFILE, "Could not start swtpm '%s': %s\n", swtpm_prg_l[0], error->message);
×
UNCOV
917
        return 1;
×
918
    }
919

920
    if (exit_status != 0) {
156✔
UNCOV
921
        logerr(gl_LOGFILE, "%s exit with status %d: %s\n",
×
922
               swtpm_prg_l[0], exit_status, standard_output);
UNCOV
923
        return 1;
×
924
    }
925

926
    if (g_strstr_len(standard_output, -1, TPM_PERMANENT_ALL_NAME) != NULL) {
156✔
927
        /* State file exists */
928
        if (flags & SETUP_STATE_NOT_OVERWRITE_F) {
75✔
929
            logit(gl_LOGFILE, "Not overwriting existing state file.\n");
2✔
930
            return 2;
2✔
931
        }
932
        if (flags & SETUP_STATE_OVERWRITE_F)
73✔
933
            return 0;
934
        logerr(gl_LOGFILE, "Found existing TPM state '%s'.\n", TPM_PERMANENT_ALL_NAME);
3✔
935
        return 1;
3✔
936
    }
937

938
    return 0;
939
}
940

941
static void versioninfo(void)
2✔
942
{
943
    printf("TPM emulator setup tool version %d.%d.%d\n",
2✔
944
           SWTPM_VER_MAJOR, SWTPM_VER_MINOR, SWTPM_VER_MICRO);
945
}
2✔
946

947
static void usage(const char *prgname, const char *default_config_file)
1✔
948
{
949
    versioninfo();
1✔
950
    printf(
1✔
951
        "Usage: %s [options]\n"
952
        "\n"
953
        "The following options are supported:\n"
954
        "\n"
955
        "--runas <user>   : Run this program under the given user's account.\n"
956
        "\n"
957
        "--tpm-state <dir>: Path where the TPM's state will be written to;\n"
958
        "                   this is a mandatory argument. Prefix with dir:// to\n"
959
        "                   use directory backend, or file:// to use linear file.\n"
960
        "\n"
961
        "--tpmstate <dir> : This is an alias for --tpm-state <dir>.\n"
962
        "\n"
963
        "--tpm '<path-to-executable> socket'\n"
964
        "                 : Path to the TPM executable; this is an optional argument and\n"
965
        "                   by default 'swtpm' in the PATH is used.\n"
966
        "\n"
967
        "--swtpm_ioctl <executable>\n"
968
        "                 : Path to the swtpm_ioctl executable; this is deprecated\n"
969
        "                   argument.\n"
970
        "\n"
971
        "--tpm2           : Setup a TPM 2; by default a TPM 1.2 is setup.\n"
972
        "\n"
973
        "--createek       : Create the EK; for a TPM 2 an RSA and ECC EK will be\n"
974
        "                   created\n"
975
        "\n"
976
        "--allow-signing  : Create an EK that can be used for signing;\n"
977
        "                   this option requires --tpm2.\n"
978
        "                   Note: Careful, this option will create a non-standard EK!\n"
979
        "\n"
980
        "--decryption     : Create an EK that can be used for key encipherment;\n"
981
        "                   this is the default unless --allow-signing is given;\n"
982
        "                   this option requires --tpm2.\n"
983
        "\n"
984
        "--ecc            : This option allows to create a TPM 2's ECC key as storage\n"
985
        "                   primary key; a TPM 2 always gets an RSA and an ECC EK key.\n"
986
        "\n"
987
        "--ek1keyalgo     : Choice of the 1st EK's key algorithm; default is %s\n"
988
        "                   choices: rsa-2048, rsa-3072, rsa-4096, secp384r1\n"
989
        "\n"
990
        "--ek2keyalgo     : Choice of the 2nd EK's key algorithm; default is %s\n"
991
        "                   choices: same as for --ek1keyalgo\n"
992
        "\n"
993
        "--take-ownership : Take ownership; this option implies --createek\n"
994
        "  --ownerpass  <password>\n"
995
        "                 : Provide custom owner password; default is %s\n"
996
        "  --owner-well-known:\n"
997
        "                 : Use an owner password of 20 zero bytes\n"
998
        "  --srkpass <password>\n"
999
        "                 : Provide custom SRK password; default is %s\n"
1000
        "  --srk-well-known:\n"
1001
        "                 : Use an SRK password of 20 zero bytes\n"
1002
        "--create-ek-cert : Create an EK certificate; this implies --createek\n"
1003
        "\n"
1004
        "--create-platform-cert\n"
1005
        "                 : Create a platform certificate; this implies --create-ek-cert\n"
1006
        "\n"
1007
        "--create-spk     : Create storage primary key; this requires --tpm2; deprecated\n"
1008
        "\n"
1009
        "--lock-nvram     : Lock NVRAM access\n"
1010
        "\n"
1011
        "--display        : At the end display as much info as possible about the\n"
1012
        "                   configuration of the TPM\n"
1013
        "\n"
1014
        "--config <config file>\n"
1015
        "                 : Path to configuration file; default is %s\n"
1016
        "\n"
1017
        "--logfile <logfile>\n"
1018
        "                 : Path to log file; default is logging to stderr\n"
1019
        "\n"
1020
        "--keyfile <keyfile>\n"
1021
        "                 : Path to a key file containing the encryption key for the\n"
1022
        "                   TPM to encrypt its persistent state with. The content\n"
1023
        "                   must be a 32 hex digit number representing a 128bit AES key.\n"
1024
        "                   This parameter will be passed to the TPM using\n"
1025
        "                   '--key file=<file>'.\n"
1026
        "\n"
1027
        "--keyfile-fd <fd>: Like --keyfile but a file descriptor is given to read the\n"
1028
        "                   encryption key from.\n"
1029
        "\n"
1030
        "--pwdfile <pwdfile>\n"
1031
        "                 : Path to a file containing a passphrase from which the\n"
1032
        "                   TPM will derive the 128bit AES key. The passphrase can be\n"
1033
        "                   32 bytes long.\n"
1034
        "                   This parameter will be passed to the TPM using\n"
1035
        "                   '--key pwdfile=<file>'.\n"
1036
        "\n"
1037
        "--pwdfile-fd <fd>: Like --pwdfile but a file descriptor is given to to read\n"
1038
        "                   the passphrase from.\n"
1039
        "\n"
1040
        "--cipher <cipher>: The cipher to use; either aes-128-cbc or aes-256-cbc;\n"
1041
        "                   the default is aes-128-cbc; the same cipher must be\n"
1042
        "                   used on the swtpm command line\n"
1043
        "\n"
1044
        "--overwrite      : Overwrite existing TPM state by re-initializing it; if this\n"
1045
        "                   option is not given, this program will return an error if\n"
1046
        "                   existing state is detected\n"
1047
        "\n"
1048
        "--not-overwrite  : Do not overwrite existing TPM state but silently end\n"
1049
        "\n"
1050
        "--vmid <vm id>   : Unique (VM) identifier to use as common name in certificate\n"
1051
        "\n"
1052
        "--pcr-banks <banks>\n"
1053
        "                 : Set of PCR banks to activate. Provide a comma separated list\n"
1054
        "                   like 'sha1,sha256'. '-' to skip and leave all banks active.\n"
1055
        "                   Default: %s\n"
1056
        "\n"
1057
        "--rsa-keysize <keysize>\n"
1058
        "                 : The RSA key size of the 1st EK key; 3072 and 4096 bits may\n"
1059
        "                   be supported if libtpms supports it. This option is ignored\n"
1060
        "                   if --ek1keyalgo is used.\n"
1061
        "                   Default: %u\n"
1062
        "\n"
1063
        "--write-ek-cert-files <directory>\n"
1064
        "                 : Write EK cert files into the given directory\n"
1065
        "\n"
1066
        "--tcsd-system-ps-file <file>\n"
1067
        "                 : This option is deprecated and has no effect.\n"
1068
        "\n"
1069
        "--print-capabilities\n"
1070
        "                 : Print JSON formatted capabilities added after v0.1 and exit.\n"
1071
        "\n"
1072
        "--create-config-files [[overwrite][,root]]\n"
1073
        "                 : Create swtpm_setup and swtpm-localca config files for a\n"
1074
        "                   user account.\n"
1075
        "                   overwrite: overwrite any existing files\n"
1076
        "                   root: allow to create files under root's home directory\n"
1077
        "                   skip-if-exist: if any file exists exit without error\n"
1078
        "\n"
1079
        "--reconfigure    : Reconfigure an existing swtpm by reusing existing state.\n"
1080
        "                   The active PCR banks can be changed but no new keys will\n"
1081
        "                   be created.\n"
1082
        "\n"
1083
        "--profile <json-profile>\n"
1084
        "                 : Configure swtpm with the given profile.\n"
1085
        "\n"
1086
        "--profile-name <profile name | built-in profile name>\n"
1087
        "                 : Search for a profile with the <name>.json in distro and\n"
1088
        "                   local directories; if not found try it as a built-in.\n"
1089
        "\n"
1090
        "--profile-file <file>\n"
1091
        "                 : Configure swtpm with a profile read from the given file.\n"
1092
        "\n"
1093
        "--profile-file-fd <fd>\n"
1094
        "                 : Configure swtpm with a profile read from a file descriptor.\n"
1095
        "\n"
1096
        "--profile-remove-disabled check|fips-host\n"
1097
        "                 : Instruct swtpm to remove algorithms that may be disabled by\n"
1098
        "                   FIPS mode on the host from 'custom' profile.\n"
1099
        "                   check: algorithms are tested.\n"
1100
        "                   fips-host: no testing.\n"
1101
        "\n"
1102
        "--print-profiles : Display all local and distro-provided profile as well as\n"
1103
        "                   the ones built into libtpms and exit.\n"
1104
        "\n"
1105
        "--version        : Display version and exit\n"
1106
        "\n"
1107
        "--help,-h        : Display this help screen\n\n",
1108
            prgname,
1109
            DEFAULT_EK1KEYALGO,
1110
            DEFAULT_EK2KEYALGO,
1111
            DEFAULT_OWNER_PASSWORD,
1112
            DEFAULT_SRK_PASSWORD,
1113
            default_config_file,
1114
            DEFAULT_PCR_BANKS,
1115
            DEFAULT_RSA_KEYSIZE
1116
        );
1117
}
1✔
1118

1119
static int get_swtpm_capabilities(const gchar **swtpm_prg_l, gboolean is_tpm2,
414✔
1120
                                  gchar **standard_output)
1121
{
1122
    const gchar *my_argv[] = { "--print-capabilities", is_tpm2 ? "--tpm2" : NULL, NULL };
414✔
1123
    g_autofree gchar *standard_error = NULL;
828✔
1124
    g_autofree gchar *logop = NULL;
414✔
1125
    g_autoptr(GError) error = NULL;
414✔
1126
    g_autofree const gchar **argv = NULL;
414✔
1127
    int exit_status = 0;
414✔
1128
    gboolean success;
414✔
1129
    int ret = 1;
414✔
1130

1131
    argv = concat_arrays(swtpm_prg_l, my_argv, FALSE);
414✔
1132

1133
    if (gl_LOGFILE != NULL) {
414✔
1134
        logop = g_strdup_printf("file=%s", gl_LOGFILE);
248✔
1135
        argv = concat_arrays(argv, (const gchar*[]){"--log", logop, NULL}, TRUE);
248✔
1136
    }
1137

1138
    success = spawn_sync(NULL, argv, NULL, 0, NULL, NULL,
414✔
1139
                         standard_output, &standard_error, &exit_status, &error);
1140
    if (!success) {
414✔
UNCOV
1141
        logerr(gl_LOGFILE, "Could not start swtpm '%s': %s\n", swtpm_prg_l[0], error->message);
×
UNCOV
1142
        goto error;
×
1143
    }
1144
    if (exit_status != 0) {
414✔
1145
        /* possible: failure to access log file */
UNCOV
1146
        logerr(gl_LOGFILE, "Failed to run swtpm '%s': %s\n", swtpm_prg_l[0], standard_error);
×
UNCOV
1147
        goto error;
×
1148
    }
1149
    ret = 0;
1150

1151
error:
414✔
1152
    return ret;
414✔
1153
}
1154

1155
static int get_supported_tpm_versions(const gchar **swtpm_prg_l, gboolean *swtpm_has_tpm12,
174✔
1156
                                      gboolean *swtpm_has_tpm2)
1157
{
1158
    g_autofree gchar *standard_output = NULL;
348✔
1159
    int ret;
174✔
1160

1161
    ret = get_swtpm_capabilities(swtpm_prg_l, FALSE, &standard_output);
174✔
1162
    if (ret)
174✔
1163
        return ret;
1164

1165
    *swtpm_has_tpm12 = g_strstr_len(standard_output, -1, "\"tpm-1.2\"") != NULL;
174✔
1166
    *swtpm_has_tpm2 = g_strstr_len(standard_output, -1, "\"tpm-2.0\"") != NULL;
174✔
1167

1168
    return 0;
174✔
1169
}
1170

1171
/* Get the support RSA key sizes.
1172
 *  This function returns an array of ints like the following
1173
 *  - [ 1024, 2048, 3072, 4096 ]
1174
 *  - [] (empty array, indicating only 2048 bit RSA keys are supported)
1175
 */
1176
static int get_rsa_keysizes(unsigned long flags, const gchar **swtpm_prg_l,
141✔
1177
                            unsigned int **keysizes, size_t *n_keysizes)
1178
{
1179
    g_autofree gchar *standard_output = NULL;
282✔
1180
    const gchar *needle = "\"rsa-keysize-";
141✔
1181
    unsigned int keysize;
141✔
1182
    int ret = 1;
141✔
1183
    char *p;
141✔
1184
    int n;
141✔
1185

1186
    *n_keysizes = 0;
141✔
1187

1188
    if (flags & SETUP_TPM2_F) {
141✔
1189
        ret = get_swtpm_capabilities(swtpm_prg_l, TRUE, &standard_output);
141✔
1190
        if (ret)
141✔
UNCOV
1191
            goto error;
×
1192

1193
        p = standard_output;
141✔
1194
        /* A crude way of parsing the json output just looking for "rsa-keysize-%u" */
1195
        while ((p = g_strstr_len(p, -1, needle)) != NULL) {
705✔
1196
            p += strlen(needle);
564✔
1197
            n = sscanf(p, "%u\"", &keysize);
564✔
1198
            if (n == 1) {
564✔
1199
                *keysizes = g_realloc(*keysizes, (*n_keysizes + 1) * sizeof(unsigned int));
564✔
1200
                (*keysizes)[*n_keysizes] = keysize;
564✔
1201
                (*n_keysizes)++;
564✔
1202
            }
1203
        }
1204
    }
1205
    ret = 0;
1206

1207
error:
141✔
1208
    return ret;
141✔
1209
}
1210

1211
/* Return the RSA key size capabilities in a NULL-terminated array */
1212
static int get_rsa_keysize_caps(unsigned long flags, const gchar **swtpm_prg_l,
9✔
1213
                                gchar ***keysize_strs)
1214
{
1215
    unsigned int *keysizes = NULL;
9✔
1216
    size_t n_keysizes = 0;
9✔
1217
    size_t i, j;
9✔
1218
    int ret = get_rsa_keysizes(flags, swtpm_prg_l, &keysizes, &n_keysizes);
9✔
1219
    if (ret)
9✔
1220
        return ret;
1221

1222
    *keysize_strs = g_malloc0(sizeof(char *) * (n_keysizes + 1));
9✔
1223
    for (i = 0, j = 0; i < n_keysizes; i++) {
45✔
1224
        if (keysizes[i] >= 2048)
36✔
1225
            (*keysize_strs)[j++] = g_strdup_printf("tpm2-rsa-keysize-%u", keysizes[i]);
27✔
1226
    }
1227

1228
    g_free(keysizes);
9✔
1229

1230
    return 0;
9✔
1231
}
1232

1233
static bool is_rsa_keysize_supported(unsigned long flags, unsigned int rsa_keysize,
132✔
1234
                                     gchar **swtpm_prg_l)
1235
{
1236
    g_autofree unsigned int *keysizes = NULL;
264✔
1237
    gboolean found = FALSE;
132✔
1238
    size_t n_keysizes;
132✔
1239
    size_t i;
132✔
1240
    int ret;
132✔
1241

1242
    ret = get_rsa_keysizes(flags, (const char **)swtpm_prg_l, &keysizes, &n_keysizes);
132✔
1243
    if (ret)
132✔
1244
        return false;
1245

1246
    for (i = 0; i < n_keysizes && !found; i++)
426✔
1247
        found = (keysizes[i] == rsa_keysize);
294✔
1248
    if (!found && rsa_keysize != 2048) {
132✔
NEW
1249
        logerr(gl_LOGFILE, "%u bit RSA keys are not supported by libtpms.\n", rsa_keysize);
×
NEW
1250
        return false;
×
1251
    }
1252
    return true;
1253
}
1254

1255
/* Parse the rsa_keysize_str and check that it contains a supported size */
1256
static unsigned int parse_rsa_keysize(unsigned long flags, char **rsa_keysize_str,
125✔
1257
                                      gchar **swtpm_prg_l)
1258
{
1259
    unsigned int *keysizes = NULL;
125✔
1260
    unsigned int rsa_keysize;
125✔
1261
    size_t n_keysizes;
125✔
1262
    int ret;
125✔
1263

1264
    if (strcmp(*rsa_keysize_str, "max") == 0) {
125✔
NEW
1265
        ret = get_rsa_keysizes(flags, (const char **)swtpm_prg_l, &keysizes, &n_keysizes);
×
NEW
1266
        if (ret)
×
1267
            return 0;
NEW
1268
        g_free(*rsa_keysize_str);
×
NEW
1269
        if (n_keysizes > 0) {
×
1270
            /* last one is the biggest one */
NEW
1271
            *rsa_keysize_str = g_strdup_printf("%u", keysizes[n_keysizes - 1]);
×
1272
        } else {
NEW
1273
            *rsa_keysize_str = g_strdup("2048");
×
1274
        }
NEW
1275
        g_free(keysizes);
×
1276
    }
1277

1278
    if (strcmp(*rsa_keysize_str, "2048") == 0 ||
125✔
1279
        strcmp(*rsa_keysize_str, "3072") == 0 ||
19✔
1280
        strcmp(*rsa_keysize_str, "4096") == 0) {
7✔
1281

1282
        rsa_keysize = strtoull(*rsa_keysize_str, NULL, 10);
125✔
1283

1284
        if (!is_rsa_keysize_supported(flags, rsa_keysize, swtpm_prg_l))
125✔
1285
            return 0;
1286
        return rsa_keysize;
1287
    }
1288

NEW
1289
    logit(gl_LOGFILE, "Unsupported RSA key size %s.\n", *rsa_keysize_str);
×
NEW
1290
    return 0;
×
1291
}
1292

1293
static int validate_json_profile(const gchar **swtpm_prg_l, const char *json_profile)
90✔
1294
{
1295
    g_autofree gchar *standard_output = NULL;
180✔
1296
    int ret;
90✔
1297

1298
    ret = get_swtpm_capabilities(swtpm_prg_l, TRUE, &standard_output);
90✔
1299
    if (ret)
90✔
1300
        return ret;
1301

1302
    return check_json_profile(standard_output, json_profile);
90✔
1303
}
1304

1305
/* Print the JSON object of swtpm_setup's capabilities */
1306
static int print_capabilities(const char **swtpm_prg_l, gboolean swtpm_has_tpm12,
9✔
1307
                              gboolean swtpm_has_tpm2)
1308
{
1309
    g_autofree gchar *standard_output = NULL;
18✔
1310
    g_autofree gchar *param = g_strdup("");
18✔
1311
    g_autofree gchar *profile_list = NULL;
9✔
1312
    gchar **profile_names = NULL;
9✔
1313
    gchar **keysize_strs = NULL;
9✔
1314
    gchar *tmp;
9✔
1315
    size_t i;
9✔
1316
    int ret = 0;
9✔
1317

1318
    ret = get_rsa_keysize_caps(SETUP_TPM2_F, swtpm_prg_l, &keysize_strs);
9✔
1319
    if (ret)
9✔
1320
        return 1;
1321

1322
    for (i = 0; keysize_strs[i] != NULL; i++) {
36✔
1323
        tmp = g_strdup_printf("%s, \"%s\"", param, keysize_strs[i]);
27✔
1324
        g_free(param);
27✔
1325
        param = tmp;
27✔
1326
    }
1327

1328
    if (swtpm_has_tpm2) {
9✔
1329
        ret = get_swtpm_capabilities(swtpm_prg_l, TRUE, &standard_output);
9✔
1330
        if (ret)
9✔
UNCOV
1331
            goto error;
×
1332
        ret = get_profile_names(standard_output, &profile_names);
9✔
1333
        if (ret)
9✔
UNCOV
1334
            goto error;
×
1335

1336
        if (g_strv_length(profile_names) > 0) {
9✔
1337
            tmp = g_strjoinv("\", \"", profile_names);
9✔
1338
            profile_list = g_strdup_printf(" \"%s\" ", tmp);
9✔
1339
            g_free(tmp);
9✔
1340
        }
1341
    }
1342

1343
    printf("{ \"type\": \"swtpm_setup\", "
9✔
1344
           "\"features\": [ %s%s\"cmdarg-keyfile-fd\", \"cmdarg-pwdfile-fd\", \"tpm12-not-need-root\""
1345
           ", \"cmdarg-write-ek-cert-files\", \"cmdarg-create-config-files\""
1346
           ", \"cmdarg-reconfigure-pcr-banks\""
1347
           "%s"
1348
           ", \"cmdarg-profile\", \"cmdarg-profile-remove-disabled\""
1349
           ", \"cmdarg-ek1keyalgo\", \"cmdarg-ek2keyalgo\""
1350
           " ], "
1351
           "\"profiles\": [%s], "
1352
           "\"version\": \"" VERSION "\" "
1353
           "}\n",
1354
           swtpm_has_tpm12 ? "\"tpm-1.2\", " : "",
1355
           swtpm_has_tpm2  ? "\"tpm-2.0\", " : "",
1356
           param,
1357
           profile_list ? profile_list : ""
1358
           );
1359

1360
error:
9✔
1361
    g_strfreev(keysize_strs);
9✔
1362
    g_strfreev(profile_names);
9✔
1363

1364
    return ret;
9✔
1365
}
1366

1367
static int change_process_owner(const char *user)
1368
{
UNCOV
1369
    char *endptr;
×
1370
    unsigned long long uid = strtoull(user, &endptr, 10);
×
UNCOV
1371
    gid_t gid;
×
1372
    struct passwd *passwd;
×
UNCOV
1373
    int ret = 1;
×
1374

UNCOV
1375
    if (*endptr != '\0') {
×
1376
        /* assuming a name */
UNCOV
1377
        passwd = getpwnam(user);
×
UNCOV
1378
        if (passwd == NULL) {
×
UNCOV
1379
            logerr(gl_LOGFILE, "Error: User '%s' does not exist.\n", user);
×
UNCOV
1380
            goto error;
×
1381
        }
1382

UNCOV
1383
        if (initgroups(passwd->pw_name, passwd->pw_gid) != 0) {
×
UNCOV
1384
            logerr(gl_LOGFILE, "Error: initgroups() failed: %s\n", strerror(errno));
×
UNCOV
1385
            goto error;
×
1386
        }
1387

1388
        gid = passwd->pw_gid;
×
1389
        uid = passwd->pw_uid;
×
1390
    } else {
UNCOV
1391
        if (uid > 0xffffffff) {
×
UNCOV
1392
            logerr(gl_LOGFILE, "Error: uid %s outside valid range.\n", user);
×
UNCOV
1393
            goto error;
×
1394
        }
UNCOV
1395
        gid = (gid_t)uid;
×
1396
    }
1397

UNCOV
1398
    if (setgid(gid) != 0) {
×
UNCOV
1399
        logerr(gl_LOGFILE, "Error: setgid(%d) failed: %s\n", gid, strerror(errno));
×
UNCOV
1400
        goto error;
×
1401
    }
1402

UNCOV
1403
    if (setuid(uid) != 0) {
×
UNCOV
1404
        logerr(gl_LOGFILE, "Error: setuid(%lld) failed: %s\n", uid, strerror(errno));
×
UNCOV
1405
        goto error;
×
1406
    }
1407

1408
    ret = 0;
1409

UNCOV
1410
error:
×
UNCOV
1411
    return ret;
×
1412
}
1413

1414
static int handle_create_config_files(const char *opt_arg)
1415
{
UNCOV
1416
    g_auto(GStrv) tokens = NULL;
×
UNCOV
1417
    gboolean overwrite = FALSE;
×
UNCOV
1418
    gboolean root_flag = FALSE;
×
UNCOV
1419
    gboolean skip_if_exist = FALSE;
×
1420

UNCOV
1421
    if (opt_arg) {
×
UNCOV
1422
        tokens = g_strsplit_set(opt_arg, ", ", -1);
×
UNCOV
1423
        overwrite = g_strv_contains((const gchar **)tokens, "overwrite");
×
UNCOV
1424
        root_flag = g_strv_contains((const gchar **)tokens, "root");
×
UNCOV
1425
        skip_if_exist = g_strv_contains((const gchar **)tokens, "skip-if-exist");
×
UNCOV
1426
        if (overwrite && skip_if_exist) {
×
UNCOV
1427
            fprintf(stderr, "Error: overwrite and skip-if-exist cannot both be used\n");
×
UNCOV
1428
            return 1;
×
1429
        }
1430
    }
1431

UNCOV
1432
    return create_config_files(overwrite, root_flag, skip_if_exist);
×
1433
}
1434

1435
static int read_config_file(const gchar *config_file,
160✔
1436
                            const struct passwd *user,
1437
                            gchar ***config_file_lines)
1438
{
1439
    if (access(config_file, R_OK) != 0) {
160✔
UNCOV
1440
        logerr(gl_LOGFILE, "User %s cannot read config file %s.\n",
×
1441
               user ? user->pw_name : "<unknown>", config_file);
UNCOV
1442
        return -1;
×
1443
    }
1444

1445
    if (read_file_lines(config_file, config_file_lines))
160✔
1446
        return -1;
1447

1448
    return 0;
1449
}
1450

1451
static bool parse_keyalgo(const char *keyalgo_str,
10✔
1452
                          enum keyalgo *keyalgo,
1453
                          unsigned int *keyalgo_param,
1454
                          unsigned long *flags)
1455
{
1456
    size_t i;
10✔
1457

1458
    for (i = 0; i < ARRAY_LEN(keyalgo_choices); i++) {
23✔
1459
        if (!strcasecmp(keyalgo_choices[i].name, keyalgo_str)) {
23✔
1460
            *keyalgo = keyalgo_choices[i].keyalgo;
10✔
1461
            *keyalgo_param = keyalgo_choices[i].keyalgo_param;
10✔
1462
            return true;
10✔
1463
        }
1464
    }
NEW
1465
    logerr(gl_LOGFILE,
×
1466
           "Key algorithm %s is not supported.\n", keyalgo_str);
NEW
1467
    return false;
×
1468
}
1469

1470
int main(int argc, char *argv[])
187✔
1471
{
1472
    int opt, option_index = 0;
187✔
1473
    static const struct option long_options[] = {
187✔
1474
        {"tpm-state", required_argument, NULL, 't'},
1475
        {"tpmstate", required_argument, NULL, 't'}, /* alias for tpm-state */
1476
        {"tpm", required_argument, NULL, 'T'},
1477
        {"swtpm_ioctl", required_argument, NULL, '_'},
1478
        {"tpm2", no_argument, NULL, '2'},
1479
        {"ecc", no_argument, NULL, 'e'},
1480
        {"createek", no_argument, NULL, 'c'},
1481
        {"create-spk", no_argument, NULL, 'C'},
1482
        {"ek1keyalgo", required_argument, NULL, '4'},
1483
        {"ek2keyalgo", required_argument, NULL, '5'},
1484
        {"take-ownership", no_argument, NULL, 'o'},
1485
        {"ownerpass", required_argument, NULL, 'O'},
1486
        {"owner-well-known", no_argument, NULL, 'w'},
1487
        {"srkpass", required_argument, NULL, 'S'},
1488
        {"srk-well-known", no_argument, NULL, 's'},
1489
        {"create-ek-cert", no_argument, NULL, 'E'},
1490
        {"create-platform-cert", no_argument, NULL, 'P'},
1491
        {"lock-nvram", no_argument, NULL, 'L'},
1492
        {"display", no_argument, NULL, 'i'},
1493
        {"config", required_argument, NULL, 'f'},
1494
        {"vmid", required_argument, NULL, 'm'},
1495
        {"keyfile", required_argument, NULL, 'x'},
1496
        {"keyfile-fd", required_argument, NULL, 'X'},
1497
        {"pwdfile", required_argument, NULL, 'k'},
1498
        {"pwdfile-fd", required_argument, NULL, 'K'},
1499
        {"cipher", required_argument, NULL, 'p'},
1500
        {"runas", required_argument, NULL, 'r'},
1501
        {"logfile", required_argument, NULL, 'l'},
1502
        {"overwrite", no_argument, NULL, 'v'},
1503
        {"not-overwrite", no_argument, NULL, 'V'},
1504
        {"allow-signing", no_argument, NULL, 'a'},
1505
        {"decryption", no_argument, NULL, 'd'},
1506
        {"pcr-banks", required_argument, NULL, 'b'},
1507
        {"rsa-keysize", required_argument, NULL, 'A'},
1508
        {"write-ek-cert-files", required_argument, NULL, '3'},
1509
        {"create-config-files", optional_argument, NULL, 'u'},
1510
        {"tcsd-system-ps-file", required_argument, NULL, 'F'},
1511
        {"version", no_argument, NULL, '1'},
1512
        {"print-capabilities", no_argument, NULL, 'y'},
1513
        {"reconfigure", no_argument, NULL, 'R'},
1514
        {"profile", required_argument, NULL, 'I'},
1515
        {"profile-name", required_argument, NULL, 'J'},
1516
        {"profile-file", required_argument, NULL, 'g'},
1517
        {"profile-file-fd", required_argument, NULL, 'G'},
1518
        {"profile-remove-disabled", required_argument, NULL, 'j'},
1519
        {"print-profiles", no_argument, NULL, 'M'},
1520
        {"help", no_argument, NULL, 'h'},
1521
        {NULL, 0, NULL, 0}
1522
    };
1523
    unsigned long flags = 0;
187✔
1524
    g_auto(GStrv) config_file_lines = NULL;
187✔
1525
    g_autofree gchar *swtpm_prg = NULL;
187✔
1526
    g_autofree gchar *tpm_state_path = NULL;
187✔
1527
    struct swtpm_backend_ops *backend_ops = &swtpm_backend_dir;
187✔
1528
    void *backend_state = NULL;
187✔
1529
    g_autofree gchar *config_file = NULL;
187✔
1530
    g_autofree gchar *ownerpass = NULL;
187✔
1531
    gboolean got_ownerpass = FALSE;
187✔
1532
    g_autofree gchar *srkpass = NULL;
187✔
1533
    gboolean got_srkpass = FALSE;
187✔
1534
    g_autofree gchar *vmid = NULL;
187✔
1535
    g_autofree gchar *pcr_banks = NULL;
187✔
1536
    gboolean printcapabilities = FALSE;
187✔
1537
    gboolean printprofiles = FALSE;
187✔
1538
    g_autofree gchar *keyfile = NULL;
187✔
1539
    long int keyfile_fd = -1;
187✔
1540
    g_autofree gchar *pwdfile = NULL;
187✔
1541
    long int pwdfile_fd = -1;
187✔
1542
    g_autofree gchar *cipher = g_strdup("aes-128-cbc");
374✔
1543
    g_autofree gchar *rsa_keysize_str = NULL;
187✔
1544
    unsigned int rsa_keysize = 2048;
187✔
1545
    g_autofree gchar *swtpm_keyopt = NULL;
187✔
1546
    g_autofree gchar *runas = NULL;
187✔
1547
    g_autofree gchar *certsdir = NULL;
187✔
1548
    g_autofree gchar *user_certsdir = NULL;
187✔
1549
    g_autofree gchar *json_profile = NULL;
187✔
1550
    g_autofree gchar *json_profile_name = NULL;
187✔
1551
    g_autofree gchar *json_profile_file = NULL;
187✔
1552
    g_autofree gchar *profile_remove_disabled_param = NULL;
187✔
1553
    g_autofree gchar *ek1keyalgo_str = NULL;
187✔
1554
    g_autofree gchar *ek2keyalgo_str = NULL;
187✔
1555
    int json_profile_fd = -1;
187✔
1556
    gchar *tmp;
187✔
1557
    gchar **swtpm_prg_l = NULL;
187✔
1558
    gchar **tmp_l = NULL;
187✔
1559
    size_t i, n;
187✔
1560
    int logfd;
187✔
1561
    const struct passwd *curr_user;
187✔
1562
    struct group *curr_grp;
187✔
1563
    char *endptr;
187✔
1564
    gboolean swtpm_has_tpm12 = FALSE;
187✔
1565
    gboolean swtpm_has_tpm2 = FALSE;
187✔
1566
    int fds_to_pass[2] = { -1, -1 };
187✔
1567
    unsigned n_fds_to_pass = 0;
187✔
1568
    char tmpbuffer[200];
187✔
1569
    time_t now;
187✔
1570
    struct tm *tm;
187✔
1571
    int ret = 1;
187✔
1572
    g_autoptr(GError) error = NULL;
187✔
1573
    enum keyalgo ek1keyalgo = KEYALGO_RSA;
187✔
1574
    enum keyalgo ek2keyalgo = KEYALGO_ECC;
187✔
1575
    unsigned int ek1keyalgo_param = 0;
187✔
1576
    unsigned int ek2keyalgo_param = 0;
187✔
1577

1578
    setvbuf(stdout, 0, _IONBF, 0);
187✔
1579

1580
    if (init(&config_file) < 0)
187✔
UNCOV
1581
        goto error;
×
1582

1583
    swtpm_prg = g_find_program_in_path("swtpm");
187✔
1584
    if (swtpm_prg) {
187✔
1585
        tmp = g_strconcat(swtpm_prg, " socket", NULL);
73✔
1586
        g_free(swtpm_prg);
73✔
1587
        swtpm_prg = tmp;
73✔
1588
    }
1589

1590
    while ((opt = getopt_long(argc, argv, "h?",
3,214✔
1591
                              long_options, &option_index)) != -1) {
1,607✔
1592
        switch (opt) {
1,422✔
1593
        case 't': /* --tpmstate, --tpm-state */
172✔
1594
            g_free(tpm_state_path);
172✔
1595
            if (strncmp(optarg, "dir://", 6) == 0) {
172✔
1596
                tpm_state_path = g_strdup(optarg);
10✔
1597
            } else if (strncmp(optarg, "file://", 7) == 0) {
162✔
1598
                tpm_state_path = g_strdup(optarg);
3✔
1599
                backend_ops = &swtpm_backend_file;
1600
            } else {
1601
                /* always prefix with dir:// so we can pass verbatim to swtpm */
1602
                tpm_state_path = g_strconcat("dir://", optarg, NULL);
159✔
1603
            }
1604
            break;
1605
        case 'T': /* --tpm */
170✔
1606
            g_free(swtpm_prg);
170✔
1607
            swtpm_prg = g_strdup(optarg);
170✔
1608
            break;
UNCOV
1609
        case '_': /* --swtpm_ioctl */
×
UNCOV
1610
            fprintf(stdout, "Warning: --swtpm_ioctl is deprecated and has no effect.");
×
UNCOV
1611
            break;
×
1612
        case '2': /* --tpm2 */
149✔
1613
            flags |= SETUP_TPM2_F;
149✔
1614
            break;
149✔
1615
        case 'e': /* --ecc */
17✔
1616
            flags |= SETUP_TPM2_ECC_F;
17✔
1617
            break;
17✔
1618
        case '4': /* --ek1keyalgo */
5✔
1619
            g_free(ek1keyalgo_str);
5✔
1620
            ek1keyalgo_str = g_strdup(optarg);
5✔
1621
            break;
1622
        case '5': /* --ek2keyalgo */
5✔
1623
            g_free(ek2keyalgo_str);
5✔
1624
            ek2keyalgo_str = g_strdup(optarg);
5✔
1625
            break;
1626
        case 'c': /* --createek */
50✔
1627
            flags |= SETUP_CREATE_EK_F;
50✔
1628
            break;
50✔
1629
        case 'C': /* --create-spk */
10✔
1630
            flags |= SETUP_CREATE_SPK_F;
10✔
1631
            break;
10✔
1632
        case 'o': /* --take-ownership */
10✔
1633
            flags |= SETUP_CREATE_EK_F | SETUP_TAKEOWN_F;
10✔
1634
            break;
10✔
1635
        case 'O': /* --ownerpass */
2✔
1636
            g_free(ownerpass);
2✔
1637
            ownerpass = g_strdup(optarg);
2✔
1638
            got_ownerpass = TRUE;
1639
            break;
1640
        case 'w': /* --owner-well-known */
2✔
1641
            flags |= SETUP_OWNERPASS_ZEROS_F;
2✔
1642
            got_ownerpass = TRUE;
2✔
1643
            break;
2✔
1644
        case 'S': /* --srk-pass */
2✔
1645
            g_free(srkpass);
2✔
1646
            srkpass = g_strdup(optarg);
2✔
1647
            got_srkpass = TRUE;
1648
            break;
1649
        case 's': /* --srk-well-known */
2✔
1650
            flags |= SETUP_SRKPASS_ZEROS_F;
2✔
1651
            got_srkpass = TRUE;
2✔
1652
            break;
2✔
1653
        case 'E': /* --create-ek-cert */
53✔
1654
            flags |= SETUP_CREATE_EK_F | SETUP_EK_CERT_F;
53✔
1655
            break;
53✔
1656
        case 'P': /* --create-platform-cert */
51✔
1657
            flags |= SETUP_CREATE_EK_F | SETUP_PLATFORM_CERT_F;
51✔
1658
            break;
51✔
1659
        case 'L': /* --lock-nvram */
16✔
1660
            flags |= SETUP_LOCK_NVRAM_F;
16✔
1661
            break;
16✔
1662
        case 'i': /* --display */
40✔
1663
            flags |= SETUP_DISPLAY_RESULTS_F;
40✔
1664
            break;
40✔
1665
        case 'f': /* --config */
213✔
1666
            g_free(config_file);
213✔
1667
            config_file = g_strdup(optarg);
213✔
1668
            break;
213✔
1669
        case 'm': /* --vmid */
41✔
1670
            g_free(vmid);
41✔
1671
            vmid = g_strdup(optarg);
41✔
1672
            break;
1673
        case 'x': /* --keyfile */
12✔
1674
            g_free(keyfile);
12✔
1675
            keyfile = g_strdup(optarg);
12✔
1676
            break;
1677
        case 'X': /* --pwdfile-fd' */
2✔
1678
            keyfile_fd = strtoull(optarg, &endptr, 10);
2✔
1679
            if (*endptr != '\0' && keyfile_fd >= INT_MAX) {
2✔
UNCOV
1680
                fprintf(stderr, "Invalid file descriptor '%s'\n", optarg);
×
UNCOV
1681
                goto error;
×
1682
            }
1683
            break;
1684
        case 'k': /* --pwdfile */
17✔
1685
            g_free(pwdfile);
17✔
1686
            pwdfile = g_strdup(optarg);
17✔
1687
            break;
1688
        case 'K': /* --pwdfile-fd' */
2✔
1689
            pwdfile_fd = strtoull(optarg, &endptr, 10);
2✔
1690
            if (*endptr != '\0' || pwdfile_fd >= INT_MAX) {
2✔
UNCOV
1691
                fprintf(stderr, "Invalid file descriptor '%s'\n", optarg);
×
UNCOV
1692
                goto error;
×
1693
            }
1694
            break;
1695
        case 'p': /* --cipher */
14✔
1696
            g_free(cipher);
14✔
1697
            cipher = g_strdup(optarg);
14✔
1698
            break;
UNCOV
1699
        case 'r': /* --runas */
×
UNCOV
1700
            g_free(runas);
×
UNCOV
1701
            runas = g_strdup(optarg);
×
1702
            break;
1703
        case 'l': /* --logfile */
93✔
1704
            g_free(gl_LOGFILE);
93✔
1705
            gl_LOGFILE = g_strdup(optarg);
93✔
1706
            break;
93✔
1707
        case 'v': /* --overwrite */
90✔
1708
            flags |= SETUP_STATE_OVERWRITE_F;
90✔
1709
            break;
90✔
1710
        case 'V': /* --not-overwrite */
3✔
1711
            flags |= SETUP_STATE_NOT_OVERWRITE_F;
3✔
1712
            break;
3✔
1713
        case 'a': /* --allow-signing */
25✔
1714
            flags |= SETUP_ALLOW_SIGNING_F;
25✔
1715
            break;
25✔
1716
        case 'd': /* --decryption */
8✔
1717
            flags |= SETUP_DECRYPTION_F;
8✔
1718
            break;
8✔
1719
        case 'b': /* --pcr-banks */
9✔
1720
            tmp = g_strconcat(pcr_banks ? pcr_banks: "",
18✔
1721
                              pcr_banks ? "," : "", g_strstrip(optarg), NULL);
1722
            g_free(pcr_banks);
9✔
1723
            pcr_banks = tmp;
9✔
1724
            break;
9✔
1725
        case 'A': /* --rsa-keysize */
21✔
1726
            g_free(rsa_keysize_str);
21✔
1727
            rsa_keysize_str = strdup(optarg);
21✔
1728
            flags |= SETUP_RSA_KEYSIZE_BY_USER_F;
21✔
1729
            break;
21✔
1730
        case '3': /* --write-ek-cert-files */
6✔
1731
            g_free(user_certsdir);
6✔
1732
            user_certsdir = g_strdup(optarg);
6✔
1733
            flags |= SETUP_WRITE_EK_CERT_FILES_F;
6✔
1734
            break;
6✔
UNCOV
1735
        case 'u':
×
UNCOV
1736
            if (optarg == NULL && optind < argc && argv[optind][0] != '0')
×
UNCOV
1737
                optarg = argv[optind++];
×
UNCOV
1738
            ret = handle_create_config_files(optarg);
×
UNCOV
1739
            goto out;
×
1740
        case 'F': /* --tcsd-system-ps-file */
UNCOV
1741
            printf("Warning: --tcsd-system-ps-file is deprecated and has no effect.");
×
UNCOV
1742
            break;
×
1743
        case '1': /* --version */
1✔
1744
            versioninfo();
1✔
1745
            ret = 0;
1✔
1746
            goto out;
1✔
1747
        case 'y': /* --print-capabilities */
1748
            printcapabilities = TRUE;
1749
            break;
1750
        case 'R': /* --reconfigure */
8✔
1751
            flags |= SETUP_RECONFIGURE_F;
8✔
1752
            break;
8✔
1753
        case 'I': /* --profile */
60✔
1754
            g_free(json_profile);
60✔
1755
            json_profile = g_strdup(optarg);
60✔
1756
            break;
60✔
1757
        case 'J': /* --profile-name */
21✔
1758
            g_free(json_profile_name);
21✔
1759
            json_profile_name = g_strdup(optarg);
21✔
1760
            break;
1761
        case 'g': /* --profile-file */
1✔
1762
            g_free(json_profile_file);
1✔
1763
            json_profile_file = g_strdup(optarg);
1✔
1764
            break;
1✔
UNCOV
1765
        case 'G': /* --profile-file-fd */
×
UNCOV
1766
            json_profile_fd = strtoull(optarg, &endptr, 10);
×
UNCOV
1767
            if (*endptr != '\0' || json_profile_fd >= INT_MAX) {
×
UNCOV
1768
                fprintf(stderr, "Invalid file descriptor '%s'\n", optarg);
×
UNCOV
1769
                goto error;
×
1770
            }
1771
            break;
1772
        case 'j': /* --profile-remove-disabled */
6✔
1773
            if (strcmp(optarg, "fips-host") != 0 &&
6✔
UNCOV
1774
                strcmp(optarg, "check") != 0) {
×
UNCOV
1775
                fprintf(stderr,
×
1776
                        "Unsupported parameter for --profile-remove-disabled: %s\n",
1777
                        optarg);
UNCOV
1778
                goto error;
×
1779
            }
1780
            g_free(profile_remove_disabled_param);
6✔
1781
            profile_remove_disabled_param = g_strdup(optarg);
1,613✔
1782
            break;
1783
        case 'M': /* --print-profiles */
3✔
1784
            printprofiles = TRUE;
3✔
1785
            break;
3✔
1786
        case '?':
1✔
1787
        case 'h': /* --help */
1788
            usage(argv[0], config_file);
1✔
1789
            if (opt == 'h')
1✔
1790
                ret = 0;
1✔
1791
            goto out;
1✔
UNCOV
1792
        default:
×
UNCOV
1793
            fprintf(stderr, "Unknown option code %d\n", opt);
×
UNCOV
1794
            usage(argv[0], config_file);
×
UNCOV
1795
            goto error;
×
1796
        }
1797
    }
1798

1799
    if (gl_LOGFILE != NULL) {
185✔
1800
        logfd = open(gl_LOGFILE, O_WRONLY|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR|S_IRGRP);
93✔
1801
        if (logfd < 0) {
93✔
UNCOV
1802
            fprintf(stderr, "Cannot open logfile %s: %s\n", gl_LOGFILE, strerror(errno));
×
UNCOV
1803
            goto error;
×
1804
        }
1805
        close(logfd);
93✔
1806
    }
1807

1808
    if (swtpm_prg == NULL) {
185✔
1809
        logerr(gl_LOGFILE,
11✔
1810
               "Default TPM 'swtpm' could not be found and was not provided using --tpm.\n");
1811
        goto error;
11✔
1812
    }
1813

1814
    swtpm_prg_l = split_cmdline(swtpm_prg);
174✔
1815
    tmp = g_find_program_in_path(swtpm_prg_l[0]);
174✔
1816
    if (!tmp) {
174✔
UNCOV
1817
        logerr(gl_LOGFILE, "swtpm at %s is not an executable.\n", swtpm_prg_l[0]);
×
UNCOV
1818
        goto error;
×
1819
    }
1820
    g_free(tmp);
174✔
1821

1822
    ret = get_supported_tpm_versions((const char **)swtpm_prg_l, &swtpm_has_tpm12, &swtpm_has_tpm2);
174✔
1823
    if (ret != 0)
174✔
UNCOV
1824
        goto error;
×
1825

1826
    if (printcapabilities) {
174✔
1827
        ret = print_capabilities((const char **)swtpm_prg_l, swtpm_has_tpm12, swtpm_has_tpm2);
9✔
1828
        goto out;
9✔
1829
    }
1830

1831
    if ((flags & SETUP_TPM2_F) != 0 && !swtpm_has_tpm2) {
165✔
UNCOV
1832
        logerr(gl_LOGFILE, "swtpm at %s does not support TPM 2\n", swtpm_prg_l[0]);
×
1833
        goto error;
×
1834
    } else if ((flags & SETUP_TPM2_F) == 0 && !swtpm_has_tpm12){
165✔
1835
        logerr(gl_LOGFILE, "swtpm at %s does not support TPM 1.2\n", swtpm_prg_l[0]);
×
UNCOV
1836
        goto error;
×
1837
    }
1838

1839
    if (runas) {
165✔
UNCOV
1840
        ret = change_process_owner(runas);
×
UNCOV
1841
        if (ret != 0)
×
UNCOV
1842
            goto error;
×
1843
    }
1844

1845
    curr_user = getpwuid(getuid());
165✔
1846

1847
    if (printprofiles) {
165✔
1848
        ret = 0;
3✔
1849
        if (read_config_file(config_file, curr_user, &config_file_lines) < 0)
3✔
UNCOV
1850
            goto error;
×
1851

1852
        if (flags & SETUP_TPM2_F) {
3✔
1853
            if (profile_printall((const char **)swtpm_prg_l, config_file_lines))
3✔
1854
                ret = 1;
3✔
1855
        } else {
UNCOV
1856
            printf("{}\n");
×
1857
        }
1858
        goto out;
3✔
1859
    }
1860

1861
    if (!got_ownerpass)
162✔
1862
        ownerpass = g_strdup(DEFAULT_OWNER_PASSWORD);
158✔
1863
    if (!got_srkpass)
162✔
1864
        srkpass = g_strdup(DEFAULT_SRK_PASSWORD);
158✔
1865

1866
    // Check tpm_state_path directory and access rights
1867
    if (tpm_state_path == NULL) {
162✔
UNCOV
1868
        logerr(gl_LOGFILE, "--tpm-state must be provided\n");
×
1869
        goto error;
×
1870
    }
1871

1872
    backend_state = backend_ops->parse_backend(tpm_state_path);
162✔
1873
    if (!backend_state)
162✔
UNCOV
1874
        goto error;
×
1875

1876
    if (backend_ops->check_access(backend_state, R_OK|W_OK, curr_user) != 0)
162✔
UNCOV
1877
        goto error;
×
1878

1879
    if ((flags & SETUP_WRITE_EK_CERT_FILES_F)) {
162✔
1880
        if (check_directory_access(user_certsdir, W_OK, curr_user) != 0)
6✔
UNCOV
1881
            goto error;
×
1882
    }
1883

1884
    if (flags & SETUP_TPM2_F) {
162✔
1885
        if (flags & SETUP_TAKEOWN_F) {
133✔
UNCOV
1886
            logerr(gl_LOGFILE, "Taking ownership is not supported for TPM 2.\n");
×
UNCOV
1887
            goto error;
×
1888
        }
1889
    } else {
1890
        if (flags & SETUP_TPM2_ECC_F) {
29✔
UNCOV
1891
            logerr(gl_LOGFILE, "--ecc requires --tpm2.\n");
×
UNCOV
1892
            goto error;
×
1893
        }
1894
        if (flags & SETUP_CREATE_SPK_F) {
29✔
UNCOV
1895
            logerr(gl_LOGFILE, "--create-spk requires --tpm2.\n");
×
UNCOV
1896
            goto error;
×
1897
        }
1898
        if (flags & SETUP_RECONFIGURE_F) {
29✔
1899
            logerr(gl_LOGFILE, "--reconfigure requires --tpm2.\n");
×
1900
            goto error;
×
1901
        }
1902
        if (flags & SETUP_ALLOW_SIGNING_F) {
29✔
1903
            logerr(gl_LOGFILE, "--allow-signing requires --tpm2.\n");
×
UNCOV
1904
            goto error;
×
1905
        }
1906
        if (flags & SETUP_DECRYPTION_F) {
29✔
UNCOV
1907
            logerr(gl_LOGFILE, "--decryption requires --tpm2.\n");
×
1908
            goto error;
×
1909
        }
1910
        if (pcr_banks) {
29✔
UNCOV
1911
            logerr(gl_LOGFILE, "--pcr-banks requires --tpm2.\n");
×
1912
            goto error;
×
1913
        }
1914
    }
1915

1916
    if (!(flags & SETUP_RECONFIGURE_F)) {
162✔
1917
        ret = check_state_overwrite((const char **)swtpm_prg_l, flags, tpm_state_path);
156✔
1918
        if (ret == 1) {
156✔
1919
            goto error;
3✔
1920
        } else if (ret == 2) {
153✔
1921
            ret = 0;
2✔
1922
            goto out;
2✔
1923
        }
1924

1925
        ret = backend_ops->delete_state(backend_state);
151✔
1926
        if (ret != 0)
151✔
1927
            goto error;
×
1928
    }
1929

1930
    if (!config_file_lines &&
314✔
1931
        read_config_file(config_file, curr_user, &config_file_lines) < 0)
157✔
UNCOV
1932
        goto error;
×
1933

1934
    /* check pcr_banks; read from config file if not given */
1935
    tmp_l = g_strsplit(pcr_banks ? pcr_banks : "", ",", -1);
157✔
1936
    for (i = 0, n = 0; tmp_l[i]; i++) {
328✔
1937
        g_strstrip(tmp_l[i]);
14✔
1938
        n += strlen(tmp_l[i]);
14✔
1939
    }
1940
    g_strfreev(tmp_l);
157✔
1941
    if (n == 0) {
157✔
1942
        g_free(pcr_banks);
149✔
1943
        pcr_banks = get_default_pcr_banks(config_file_lines);
149✔
1944
    }
1945

1946
    if ((json_profile != NULL) +
157✔
1947
        (json_profile_name != NULL) +
157✔
1948
        (json_profile_file != NULL) +
157✔
1949
        (json_profile_fd > 0) > 1) {
157✔
UNCOV
1950
        logerr(gl_LOGFILE, "Only one of --profile, --profile-name, --profile-file, and --profile-file-fd may be given.\n");
×
UNCOV
1951
        goto error;
×
1952
    }
1953

1954
    if ((flags & SETUP_RECONFIGURE_F) &&
157✔
1955
         (json_profile ||
6✔
1956
          json_profile_name ||
6✔
1957
          json_profile_file ||
6✔
1958
          json_profile_fd > 0)) {
UNCOV
1959
            logerr(gl_LOGFILE, "Reconfiguration does not accept a (new) profile.\n");
×
1960
            goto error;
×
1961
    }
1962

1963
    if (json_profile_name) {
157✔
1964
        if (profile_name_check(json_profile_name) < 0)
21✔
1965
            goto error;
×
1966
        /*
1967
         * Load profile from distro and local locations; sets json_profile_file
1968
         * to filename or json_profile with the JSON.
1969
         */
1970
        if (profile_get_by_name(config_file_lines,
21✔
1971
                                json_profile_name,
1972
                                &json_profile_file,
1973
                                &json_profile) < 0) {
UNCOV
1974
            logerr(gl_LOGFILE, "Could not find or access profile '%s'.\n",
×
1975
                   json_profile_name);
UNCOV
1976
            goto error;
×
1977
        }
1978
    }
1979

1980
    if (json_profile_file) {
157✔
1981
        json_profile_fd = open(json_profile_file, O_RDONLY);
5✔
1982
        if (json_profile_fd < 0) {
5✔
UNCOV
1983
            logerr(gl_LOGFILE, "Could not open profile file '%s': %s\n",
×
UNCOV
1984
                   json_profile_file, strerror(errno));
×
UNCOV
1985
            goto error;
×
1986
        }
1987
    }
1988

1989
    /*
1990
     * Read default profile from swtpm_setup.conf;
1991
     * Do not read it when --reconfigure'ing
1992
     */
1993
    if ((flags & SETUP_TPM2_F) != 0 &&
157✔
1994
        json_profile == NULL && json_profile_fd < 0 &&
131✔
1995
        (flags & SETUP_RECONFIGURE_F) == 0) {
1996

1997
        json_profile_fd = get_default_profile_fd(config_file_lines);
43✔
1998
        if (json_profile_fd == -2)
43✔
UNCOV
1999
            goto error;
×
2000
        if (json_profile_fd < 0)
43✔
2001
            json_profile = get_default_profile(config_file_lines);
43✔
2002
    }
2003

2004
    if (json_profile_fd >= 0)
152✔
2005
        fds_to_pass[n_fds_to_pass++] = json_profile_fd;
5✔
2006

2007
    if ((flags & SETUP_TPM2_F) != 0 && json_profile) {
157✔
2008
        if (validate_json_profile((const char **)swtpm_prg_l, json_profile) != 0)
90✔
2009
            goto error;
1✔
2010
    } else if (json_profile) {
67✔
UNCOV
2011
        logerr(gl_LOGFILE, "There's no --profile support for TPM 1.2\n");
×
UNCOV
2012
        goto error;
×
2013
    }
2014

2015
    if (cipher != NULL) {
156✔
2016
        if (strcmp(cipher, "aes-128-cbc") != 0 &&
156✔
2017
            strcmp(cipher, "aes-cbc") != 0 &&
13✔
2018
            strcmp(cipher, "aes-256-cbc") != 0) {
13✔
UNCOV
2019
            logerr(gl_LOGFILE, "Unsupported cipher %s.\n", cipher);
×
UNCOV
2020
            goto error;
×
2021
        }
2022
        tmp = g_strdup_printf(",mode=%s", cipher);
156✔
2023
        g_free(cipher);
156✔
2024
        cipher = tmp;
156✔
2025
    }
2026

2027
    if (keyfile != NULL) {
156✔
2028
        if (access(keyfile, R_OK) != 0) {
12✔
UNCOV
2029
            logerr(gl_LOGFILE, "User %s cannot read keyfile %s.\n",
×
2030
                   curr_user ? curr_user->pw_name : "<unknown>", keyfile);
2031
            goto error;
×
2032
        }
2033
        swtpm_keyopt = g_strdup_printf("file=%s%s", keyfile, cipher);
12✔
2034
        logit(gl_LOGFILE, "  The TPM's state will be encrypted with a provided key.\n");
12✔
2035
    } else if (pwdfile != NULL) {
144✔
2036
        if (access(pwdfile, R_OK) != 0) {
17✔
UNCOV
2037
            logerr(gl_LOGFILE, "User %s cannot read passphrase file %s.\n",
×
2038
                   curr_user ? curr_user->pw_name : "<unknown>", pwdfile);
2039
            goto error;
×
2040
        }
2041
        swtpm_keyopt = g_strdup_printf("pwdfile=%s%s", pwdfile, cipher);
17✔
2042
        logit(gl_LOGFILE, "  The TPM's state will be encrypted using a key derived from a passphrase.\n");
17✔
2043
    } else if (keyfile_fd >= 0) {
127✔
2044
        fds_to_pass[n_fds_to_pass++] = keyfile_fd;
2✔
2045
        swtpm_keyopt = g_strdup_printf("fd=%ld%s", keyfile_fd, cipher);
2✔
2046
        logit(gl_LOGFILE, "  The TPM's state will be encrypted with a provided key (fd).\n");
2✔
2047
    } else if (pwdfile_fd >= 0) {
125✔
2048
        fds_to_pass[n_fds_to_pass++] = pwdfile_fd;
2✔
2049
        swtpm_keyopt = g_strdup_printf("pwdfd=%ld%s", pwdfile_fd, cipher);
2✔
2050
        logit(gl_LOGFILE, "  The TPM's state will be encrypted using a key derived from a passphrase (fd).\n");
2✔
2051
    }
2052

2053
    if ((flags & SETUP_TPM2_F) != 0) {
156✔
2054
        if (!ek1keyalgo_str)
130✔
2055
            ek1keyalgo_str = get_config_value(config_file_lines, "ek1keyalgo");
125✔
2056
        if (ek1keyalgo_str &&
130✔
2057
            !parse_keyalgo(ek1keyalgo_str, &ek1keyalgo, &ek1keyalgo_param, &flags))
5✔
UNCOV
2058
            goto error;
×
2059

2060
        if (!ek2keyalgo_str)
130✔
2061
            ek2keyalgo_str = get_config_value(config_file_lines, "ek2keyalgo");
125✔
2062
        if (ek2keyalgo_str &&
130✔
2063
            !parse_keyalgo(ek2keyalgo_str, &ek2keyalgo, &ek2keyalgo_param, &flags))
5✔
UNCOV
2064
            goto error;
×
2065

2066
        if (ek1keyalgo_param == 0 && ek1keyalgo == KEYALGO_RSA) {
130✔
2067
            if ((flags & SETUP_RSA_KEYSIZE_BY_USER_F) == 0)
125✔
2068
                rsa_keysize_str = get_default_rsa_keysize(config_file_lines);
105✔
2069

2070
            rsa_keysize = parse_rsa_keysize(flags, &rsa_keysize_str, swtpm_prg_l);
125✔
2071
            if (!rsa_keysize)
125✔
NEW
2072
                goto error;
×
2073
        } else {
2074
            if (ek1keyalgo == KEYALGO_RSA &&
9✔
2075
                !is_rsa_keysize_supported(flags, ek1keyalgo_param, swtpm_prg_l))
4✔
NEW
2076
                goto error;
×
2077
            if (ek2keyalgo == KEYALGO_RSA &&
8✔
2078
                !is_rsa_keysize_supported(flags, ek2keyalgo_param, swtpm_prg_l))
3✔
NEW
2079
                goto error;
×
2080
        }
2081
    }
2082

2083
    if (flags & SETUP_RECONFIGURE_F) {
156✔
2084
        if (flags & (SETUP_CREATE_EK_F | SETUP_EK_CERT_F | SETUP_PLATFORM_CERT_F)) {
6✔
UNCOV
2085
            logerr(gl_LOGFILE, "Reconfiguration is not supported with creation of EK or certificates\n");
×
2086
            goto error;
×
2087
        }
2088
    }
2089

2090
    now = time(NULL);
156✔
2091
    tm = localtime(&now);
156✔
2092
    if (strftime(tmpbuffer, sizeof(tmpbuffer), "%a %d %h %Y %I:%M:%S %p %Z", tm) == 0) {
156✔
UNCOV
2093
        logerr(gl_LOGFILE, "Could not format time/date string.\n");
×
UNCOV
2094
        goto error;
×
2095
    }
2096
    curr_grp = getgrgid(getgid());
156✔
2097
    logit(gl_LOGFILE, "Starting vTPM %s as %s:%s @ %s\n",
306✔
2098
          flags & SETUP_RECONFIGURE_F ? "reconfiguration" : "manufacturing",
2099
          curr_user ? curr_user->pw_name : "<unknown>",
2100
          curr_grp ? curr_grp->gr_name : "<unknown>",
2101
          tmpbuffer);
2102

2103
    if (flags & (SETUP_EK_CERT_F | SETUP_PLATFORM_CERT_F)) {
156✔
2104
        certsdir = g_dir_make_tmp("swtpm_setup.certs.XXXXXX", &error);
52✔
2105
        if (certsdir == NULL) {
52✔
UNCOV
2106
            logerr(gl_LOGFILE, "Could not create temporary directory for certs: %s\n",
×
UNCOV
2107
                   error->message);
×
UNCOV
2108
            goto error;
×
2109
        }
2110
    }
2111

2112
    if ((flags & SETUP_TPM2_F) == 0) {
156✔
2113
        ret = init_tpm(flags, swtpm_prg_l, config_file, tpm_state_path, ownerpass, srkpass, vmid,
26✔
2114
                       swtpm_keyopt, fds_to_pass, n_fds_to_pass, certsdir, user_certsdir);
2115
    } else {
2116
        if (ek1keyalgo_param == 0)
130✔
2117
            ek1keyalgo_param = rsa_keysize; // default
125✔
2118
        if (ek2keyalgo_param == 0)
130✔
2119
            ek2keyalgo_param = TPM2_ECC_NIST_P384; // default
125✔
2120

2121
        ret = init_tpm2(flags, swtpm_prg_l, config_file, tpm_state_path, vmid, pcr_banks,
130✔
2122
                       swtpm_keyopt, fds_to_pass, n_fds_to_pass,
2123
                       ek1keyalgo, ek1keyalgo_param,
2124
                       ek2keyalgo, ek2keyalgo_param,
2125
                       certsdir, user_certsdir, json_profile, json_profile_fd,
2126
                       profile_remove_disabled_param);
2127
    }
2128

2129
    if (ret == 0) {
156✔
2130
        logit(gl_LOGFILE, "Successfully authored TPM state.\n");
148✔
2131
    } else {
2132
        logerr(gl_LOGFILE, "An error occurred. Authoring the TPM state failed.\n");
8✔
2133
        backend_ops->delete_state(backend_state);
8✔
2134
    }
2135

2136
    now = time(NULL);
156✔
2137
    tm = localtime(&now);
156✔
2138
    if (strftime(tmpbuffer, sizeof(tmpbuffer), "%a %d %h %Y %I:%M:%S %p %Z", tm) == 0) {
156✔
UNCOV
2139
        logerr(gl_LOGFILE, "Could not format time/date string.\n");
×
UNCOV
2140
        goto error;
×
2141
    }
2142
    logit(gl_LOGFILE, "Ending vTPM manufacturing @ %s\n",
156✔
2143
          tmpbuffer);
2144

2145
out:
187✔
2146
    if (certsdir && g_rmdir(certsdir) != 0)
187✔
UNCOV
2147
        logerr(gl_LOGFILE, "Could not remove temporary directory for certs: %s\n",
×
UNCOV
2148
               strerror(errno));
×
2149

2150
    if (backend_ops && backend_state)
187✔
2151
        backend_ops->free_backend(backend_state);
162✔
2152
    g_strfreev(swtpm_prg_l);
187✔
2153
    g_free(gl_LOGFILE);
187✔
2154

2155
    return ret;
187✔
2156

2157
error:
15✔
2158
    ret = 1;
15✔
2159
    goto out;
15✔
2160
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc