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

stefanberger / swtpm / #2829

20 May 2025 10:47PM UTC coverage: 73.458%. Remained the same
#2829

push

travis-ci

web-flow
Merge 16c8a26bc into 4da66c66f

2 of 5 new or added lines in 1 file covered. (40.0%)

33 existing lines in 1 file now uncovered.

8145 of 11088 relevant lines covered (73.46%)

13465.88 hits per line

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

82.94
/src/swtpm/ctrlchannel.c
1
/*
2
 * ctrlchannel.c -- control channel implementation
3
 *
4
 * (c) Copyright IBM Corporation 2015.
5
 *
6
 * Author: Stefan Berger <stefanb@us.ibm.com>
7
 *
8
 * All rights reserved.
9
 *
10
 * Redistribution and use in source and binary forms, with or without
11
 * modification, are permitted provided that the following conditions are
12
 * met:
13
 *
14
 * Redistributions of source code must retain the above copyright notice,
15
 * this list of conditions and the following disclaimer.
16
 *
17
 * Redistributions in binary form must reproduce the above copyright
18
 * notice, this list of conditions and the following disclaimer in the
19
 * documentation and/or other materials provided with the distribution.
20
 *
21
 * Neither the names of the IBM Corporation nor the names of its
22
 * contributors may be used to endorse or promote products derived from
23
 * this software without specific prior written permission.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
 */
37

38
#include "config.h"
39

40
#include <errno.h>
41
#include <string.h>
42
#include <stdlib.h>
43
#include <sys/socket.h>
44
#include <stdint.h>
45
#include <stddef.h>
46
#include <time.h>
47
#include <poll.h>
48

49
#include <libtpms/tpm_library.h>
50
#include <libtpms/tpm_error.h>
51
#include <libtpms/tpm_tis.h>
52
#include <libtpms/tpm_memory.h>
53

54
#include "sys_dependencies.h"
55
#include "ctrlchannel.h"
56
#include "logging.h"
57
#include "tpm_ioctl.h"
58
#include "tpmlib.h"
59
#include "swtpm_nvstore.h"
60
#include "locality.h"
61
#include "mainloop.h"
62
#include "utils.h"
63
#include "swtpm_debug.h"
64
#include "swtpm_utils.h"
65

66
/* local variables */
67

68
struct ctrlchannel {
69
    int fd;
70
    int clientfd;
71
    char *sockpath;
72
};
73

74
struct ctrlchannel *ctrlchannel_new(int fd, bool is_client,
419✔
75
                                    const char *sockpath)
76
{
77
    struct ctrlchannel *cc = calloc(1, sizeof(struct ctrlchannel));
419✔
78

79
    if (!cc) {
419✔
80
        logprintf(STDERR_FILENO, "Out of memory");
×
81
        return NULL;
×
82
    }
83

84
    if (sockpath) {
419✔
85
        cc->sockpath = strdup(sockpath);
143✔
86
        if (!cc->sockpath) {
143✔
87
            logprintf(STDERR_FILENO, "Out of memory");
×
88
            free(cc);
×
89
            return NULL;
×
90
        }
91
    }
92

93
    cc->fd = cc->clientfd = -1;
419✔
94
    if (is_client)
419✔
95
        cc->clientfd = fd;
143✔
96
    else
97
        cc->fd = fd;
276✔
98

99
    return cc;
100
}
101

102
int ctrlchannel_get_fd(struct ctrlchannel *cc)
411✔
103
{
104
    if (!cc)
411✔
105
        return -1;
106

107
    return cc->fd;
408✔
108
}
109

110
int ctrlchannel_get_client_fd(struct ctrlchannel *cc)
411✔
111
{
112
    if (!cc)
411✔
113
        return -1;
114

115
    return cc->clientfd;
408✔
116
}
117

118
int ctrlchannel_set_client_fd(struct ctrlchannel *cc, int fd)
411✔
119
{
120
    int clientfd;
411✔
121

122
    if (!cc)
411✔
123
        return -1;
124

125
    clientfd = cc->clientfd;
408✔
126
    cc->clientfd = fd;
408✔
127

128
    return clientfd;
408✔
129
}
130

131
static int ctrlchannel_return_state(ptm_getstate *pgs, int fd,
56✔
132
                                    struct mainLoopParams *mlp)
133
{
134
    uint32_t blobtype = be32toh(pgs->u.req.type);
56✔
135
    const char *blobname;
56✔
136
    uint32_t tpm_number = 0;
56✔
137
    unsigned char *blob = NULL;
56✔
138
    uint32_t blob_length = 0, return_length;
56✔
139
    TPM_BOOL is_encrypted = 0;
56✔
140
    TPM_BOOL decrypt =
56✔
141
        (be32toh(pgs->u.req.state_flags) & PTM_STATE_FLAG_DECRYPTED) != 0;
56✔
142
    TPM_RESULT res = 0;
56✔
143
    uint32_t offset = be32toh(pgs->u.req.offset);
56✔
144
    ptm_getstate pgs_res;
56✔
145
    uint32_t state_flags;
56✔
146
    struct iovec iov[2];
56✔
147
    int iovcnt, n;
56✔
148

149
    blobname = tpmlib_get_blobname(blobtype);
56✔
150
    if (!blobname)
56✔
151
        res = TPM_FAIL;
×
152

153
    if (res == 0 && blobtype == PTM_BLOB_TYPE_VOLATILE)
56✔
154
        res = SWTPM_NVRAM_Store_Volatile();
30✔
155

156
    if (res == 0)
56✔
157
        res = SWTPM_NVRAM_GetStateBlob(&blob, &blob_length,
56✔
158
                                       tpm_number, blobname, decrypt,
159
                                       &is_encrypted);
160

161
    /* make sure the volatile state file is gone */
162
    if (blobtype == PTM_BLOB_TYPE_VOLATILE)
56✔
163
        SWTPM_NVRAM_DeleteName(tpm_number, blobname, FALSE);
30✔
164

165
    if (offset < blob_length) {
56✔
166
        return_length = blob_length - offset;
53✔
167
    } else {
168
        return_length = 0;
169
    }
170

171
    state_flags = (is_encrypted) ? PTM_STATE_FLAG_ENCRYPTED : 0;
56✔
172
    pgs_res.u.resp.tpm_result = htobe32(res);
56✔
173
    pgs_res.u.resp.state_flags = htobe32(state_flags);
56✔
174
    pgs_res.u.resp.totlength = htobe32(return_length);
56✔
175
    pgs_res.u.resp.length = htobe32(return_length);
56✔
176

177
    iov[0].iov_base = &pgs_res;
56✔
178
    iov[0].iov_len = offsetof(ptm_getstate, u.resp.data);
56✔
179
    iovcnt = 1;
56✔
180

181
    SWTPM_PrintAll(" Ctrl Rsp:", " ", iov[0].iov_base, iov[0].iov_len);
56✔
182

183
    if (res == 0 && return_length) {
56✔
184
        iov[1].iov_base = &blob[offset];
53✔
185
        iov[1].iov_len = return_length;
53✔
186
        iovcnt = 2;
53✔
187

188
        SWTPM_PrintAll(" Ctrl Rsp Continued:", " ",
53✔
189
                       iov[1].iov_base, min(iov[1].iov_len, 1024));
53✔
190
    }
191

192
    n = writev_full(fd, iov, iovcnt);
56✔
193
    if (n < 0) {
56✔
194
        logprintf(STDERR_FILENO,
×
195
                  "Error: Could not send response: %s\n", strerror(errno));
×
196
        close(fd);
×
197
        fd = -1;
×
198
    }
199

200
    free(blob);
56✔
201

202
    if (fd >= 0 && blobtype == PTM_BLOB_TYPE_SAVESTATE)
56✔
203
        mainloop_unlock_nvram(mlp, DEFAULT_LOCKING_RETRIES);
7✔
204

205
    return fd;
56✔
206
}
207

208
static int ctrlchannel_receive_state(ptm_setstate *pss, ssize_t n, int fd)
62✔
209
{
210
    uint32_t blobtype = be32toh(pss->u.req.type);
62✔
211
    uint32_t tpm_number = 0;
62✔
212
    unsigned char *blob = NULL;
62✔
213
    uint32_t blob_length = be32toh(pss->u.req.length);
62✔
214
    uint32_t remain = blob_length, offset = 0;
62✔
215
    TPM_RESULT res;
62✔
216
    uint32_t flags = be32toh(pss->u.req.state_flags);
62✔
217
    TPM_BOOL is_encrypted = (flags & PTM_STATE_FLAG_ENCRYPTED) != 0;
62✔
218

219
    blob = malloc(blob_length);
62✔
220
    if (!blob) {
62✔
221
        logprintf(STDERR_FILENO,
×
222
                  "Could not allocated %u bytes.\n", blob_length);
223
        res = TPM_FAIL;
×
224
        goto err_send_resp;
×
225
    }
226

227
    n -= offsetof(ptm_setstate, u.req.data);
62✔
228
    /* n holds the number of available data bytes */
229

230
    while (true) {
111✔
231
        if (n < 0 || (uint32_t)n > remain) {
111✔
232
            res = TPM_BAD_PARAMETER;
×
233
            goto err_send_resp;
×
234
        }
235
        memcpy(&blob[offset], pss->u.req.data, n);
111✔
236
        offset += n;
111✔
237
        remain -= n;
111✔
238
        if (remain) {
111✔
239
            n = read_eintr(fd, pss->u.req.data, sizeof(pss->u.req.data));
49✔
240
            if (n < 0) {
49✔
241
                close(fd);
×
242
                fd = -1;
×
243
                goto err_fd_broken;
×
244
            } else if (n == 0) {
49✔
245
                res = TPM_BAD_PARAMETER;
×
246
                goto err_send_resp;
×
247
            }
248
        } else {
249
            break;
250
        }
251
    }
252

253
    res = SWTPM_NVRAM_SetStateBlob(blob, blob_length, is_encrypted,
62✔
254
                                   tpm_number, blobtype);
255

256
err_send_resp:
62✔
257
    pss->u.resp.tpm_result = htobe32(res);
62✔
258
    n = write_full(fd, pss, sizeof(pss->u.resp.tpm_result));
62✔
259
    if (n < 0) {
62✔
260
        logprintf(STDERR_FILENO,
×
261
                  "Error: Could not send response: %s\n", strerror(errno));
×
262
        close(fd);
×
263
        fd = -1;
×
264
    }
265

266
err_fd_broken:
62✔
267

268
    free(blob);
62✔
269

270
    return fd;
62✔
271
}
272

273
/* timespec_diff: calculate difference between two timespecs
274
 *
275
 * @end: end time
276
 * @start: start time; must be earlier than @end
277
 * @diff: result
278
 *
279
 * This function will return a negative tv_sec in result, if
280
 * @end is earlier than @start, the time difference otherwise.
281
 */
282
static void timespec_diff(struct timespec *end,
57✔
283
                          struct timespec *start,
284
                          struct timespec *diff)
285
{
286
    diff->tv_nsec = end->tv_nsec - start->tv_nsec;
57✔
287
    diff->tv_sec = end->tv_sec - start->tv_sec;
57✔
288
    if (diff->tv_nsec < 0) {
57✔
289
        diff->tv_nsec += 1E9;
27✔
290
        diff->tv_sec -= 1;
27✔
291
    }
292
}
57✔
293

294
struct input {
295
    uint32_t cmd;
296
    /* ptm_hdata is the largest buffer to receive */
297
    uint8_t body[sizeof(ptm_hdata)];
298
};
299

300
/*
301
 * ctrlchannel_recv_cmd: Receive a command on the control channel
302
 *
303
 * @fd: file descriptor for control channel
304
 * @msg: prepared msghdr struct for receiving data with single
305
 *       msg_iov.
306
 *
307
 * This function returns 0 or a negative number if an error receiving
308
 * the command occurred, including a timeout. In case of success,
309
 * the number of bytes received is returned.
310
 */
311
static ssize_t ctrlchannel_recv_cmd(int fd,
40,707✔
312
                                    struct msghdr *msg)
313
{
314
    ssize_t n;
40,707✔
315
    size_t recvd = 0;
40,707✔
316
    size_t needed = offsetof(struct input, body);
40,707✔
317
    struct input *input = (struct input *)msg->msg_iov[0].iov_base;
40,707✔
318
    struct pollfd pollfd =  {
40,707✔
319
        .fd = fd,
320
        .events = POLLIN,
321
    };
322
    struct timespec deadline, now, timeout;
40,707✔
323
    int to;
40,707✔
324
    size_t buffer_len = msg->msg_iov[0].iov_len;
40,707✔
325
    /* Read-write */
326
    ptm_init *init_p;
40,707✔
327
    ptm_reset_est *pre;
40,707✔
328
    ptm_hdata *phd;
40,707✔
329
    ptm_getstate *pgs;
40,707✔
330
    ptm_setstate *pss;
40,707✔
331
    ptm_loc *pl;
40,707✔
332
    const void *msg_iov = msg->msg_iov;
40,707✔
333

334
    clock_gettime(CLOCK_REALTIME, &deadline);
40,707✔
335

336
    /* maximum allowed time is 500ms to receive everything */
337
    deadline.tv_nsec += 500 * 1E6;
40,707✔
338
    if (deadline.tv_nsec >= 1E9) {
40,707✔
339
        deadline.tv_nsec -= 1E9;
20,520✔
340
        deadline.tv_sec += 1;
20,520✔
341
    }
342

343
    while (recvd < buffer_len) {
40,764✔
344
        if (!recvd) {
40,736✔
345
            n = recvmsg(fd, msg, 0);
40,707✔
346
            /* address a coverity issue by validating msg */
347
            if (msg_iov != msg->msg_iov ||
40,707✔
348
                msg->msg_iov[0].iov_base != input ||
40,707✔
349
                msg->msg_iov[0].iov_len > buffer_len)
40,707✔
350
                return -1;
351
        } else
352
            n = read_eintr(fd, (char *)msg->msg_iov[0].iov_base + recvd,
29✔
353
                           buffer_len - recvd);
354
        if (n <= 0)
40,736✔
355
            return n;
18,535✔
356
        recvd += n;
22,201✔
357
        /* we need to at least see the cmd */
358
        if (recvd < offsetof(struct input, body))
22,201✔
359
            goto wait_chunk;
×
360

361
        switch (be32toh(input->cmd)) {
22,201✔
362
        case CMD_GET_CAPABILITY:
363
            break;
364
        case CMD_INIT:
9,049✔
365
            needed = offsetof(struct input, body) +
9,049✔
366
                     sizeof(init_p->u.req);
367
            break;
9,049✔
368
        case CMD_SHUTDOWN:
369
            break;
370
        case CMD_GET_TPMESTABLISHED:
371
            break;
372
        case CMD_SET_LOCALITY:
57✔
373
            needed = offsetof(struct input, body) +
57✔
374
                     sizeof(pl->u.req);
375
            break;
57✔
376
        case CMD_HASH_START:
377
            break;
378
        case CMD_HASH_DATA:
3,131✔
379
            needed = offsetof(struct input, body) +
3,131✔
380
                     offsetof(struct ptm_hdata, u.req.data);
381
            if (recvd >= needed) {
3,131✔
382
                phd = (struct ptm_hdata *)&input->body;
3,131✔
383
                needed += be32toh(phd->u.req.length);
3,131✔
384
            }
385
            break;
386
        case CMD_HASH_END:
387
            break;
388
        case CMD_CANCEL_TPM_CMD:
389
            break;
390
        case CMD_STORE_VOLATILE:
391
            break;
392
        case CMD_RESET_TPMESTABLISHED:
26✔
393
            needed = offsetof(struct input, body) +
26✔
394
                     sizeof(pre->u.req);
395
            break;
26✔
396
        case CMD_GET_STATEBLOB:
56✔
397
            needed = offsetof(struct input, body) +
56✔
398
                     sizeof(pgs->u.req);
399
            break;
56✔
400
        case CMD_SET_STATEBLOB:
91✔
401
            needed = offsetof(struct input, body) +
91✔
402
                     offsetof(struct ptm_setstate, u.req.data);
403
            if (recvd >= needed) {
91✔
404
                pss = (struct ptm_setstate *)&input->body;
91✔
405
                needed += be32toh(pss->u.req.length);
91✔
406
            }
407
            break;
408
        case CMD_STOP:
409
            break;
410
        case CMD_GET_CONFIG:
411
            break;
412
        case CMD_SET_BUFFERSIZE:
413
            break;
414
        }
415

416
        if (recvd >= needed)
22,201✔
417
            break;
418

419
wait_chunk:
57✔
420
        clock_gettime(CLOCK_REALTIME, &now);
57✔
421
        timespec_diff(&deadline, &now, &timeout);
57✔
422

423
        if (timeout.tv_sec < 0)
57✔
424
            break;
425
        to = timeout.tv_sec * 1000 + timeout.tv_nsec / 1E6;
57✔
426

427
        /* wait for the next chunk */
428
        while (true) {
57✔
429
            n = poll(&pollfd, 1, to);
57✔
430
            if (n < 0 && errno == EINTR)
57✔
431
                continue;
×
432
            if (n <= 0)
57✔
433
                return n;
×
434
            break;
435
        }
436
        /* we should have data now */
437
    }
438
    return recvd;
22,172✔
439
}
440

441
static uint32_t get_ptm_caps_supported(TPMLIB_TPMVersion tpmversion)
12✔
442
{
443
    uint32_t caps =
12✔
444
              PTM_CAP_INIT
445
            | PTM_CAP_SHUTDOWN
446
            | PTM_CAP_GET_TPMESTABLISHED
447
            | PTM_CAP_SET_LOCALITY
448
            | PTM_CAP_HASHING
449
            | PTM_CAP_CANCEL_TPM_CMD
450
            | PTM_CAP_STORE_VOLATILE
451
            | PTM_CAP_RESET_TPMESTABLISHED
452
            | PTM_CAP_GET_STATEBLOB
453
            | PTM_CAP_SET_STATEBLOB
454
            | PTM_CAP_STOP
455
            | PTM_CAP_GET_CONFIG
456
#ifndef __CYGWIN__
457
            | PTM_CAP_SET_DATAFD
458
#endif
459
            | PTM_CAP_SET_BUFFERSIZE
460
            | PTM_CAP_GET_INFO
461
            | PTM_CAP_LOCK_STORAGE;
462
    if (tpmversion == TPMLIB_TPM_VERSION_2)
12✔
463
        caps |= PTM_CAP_SEND_COMMAND_HEADER;
5✔
464

465
    return caps;
12✔
466
}
467

468
/*
469
 * ctrlchannel_process_fd: Read command from control channel and execute it
470
 *
471
 * @fd: file descriptor for control channel
472
 * @terminate: pointer to a boolean that will be set to true by this
473
 *             function in case the process should shut down; CMD_SHUTDOWN
474
 *             will set this
475
 * @locality: pointer to locality identifier that must point to the global
476
 *            locality variable and that will receive the new locality
477
 *            number when set via CMD_SET_LOCALITY
478
 * @tpm_running: indicates whether the TPM is running; may be changed by
479
 *               this function in case TPM is stopped or started
480
 * @mlp: mainloop parameters used; may be altered by this function in case of
481
 *       CMD_SET_DATAFD
482
 *
483
 * This function returns the passed file descriptor or -1 in case the
484
 * file descriptor was closed.
485
 */
486
int ctrlchannel_process_fd(int fd,
40,707✔
487
                           bool *terminate,
488
                           TPM_MODIFIER_INDICATOR *locality,
489
                           bool *tpm_running,
490
                           struct mainLoopParams *mlp)
491
{
492
    struct input input = {0, };
40,707✔
493
    struct output {
40,707✔
494
        uint8_t body[sizeof(struct ptm_hdata)]; /* ptm_hdata is largest */
495
    } output;
496
    ssize_t n;
40,707✔
497
    struct iovec iov = {
40,707✔
498
        .iov_base = &input,
499
        .iov_len = sizeof(input),
500
    };
501
    char control[CMSG_SPACE(sizeof(int))];
40,707✔
502
    struct msghdr msg = {
40,707✔
503
        .msg_iov = &iov,
504
        .msg_iovlen = 1,
505
        .msg_control = control,
506
        .msg_controllen = sizeof(control),
507
    };
508
    struct cmsghdr *cmsg = NULL;
40,707✔
509
    int *data_fd = NULL;
40,707✔
510

511
    /* Write-only */
512
    ptm_cap_n *ptm_caps_n = (ptm_cap_n *)&output.body;
40,707✔
513
    ptm_res *res_p = (ptm_res *)&output.body;
40,707✔
514
    ptm_est *te = (ptm_est *)&output.body;
40,707✔
515
    ptm_getconfig *pgc = (ptm_getconfig *)&output.body;
40,707✔
516
    /* Read-write */
517
    ptm_init *init_p;
40,707✔
518
    ptm_reset_est *re;
40,707✔
519
    ptm_hdata *data;
40,707✔
520
    ptm_getstate *pgs;
40,707✔
521
    ptm_setstate *pss;
40,707✔
522
    ptm_loc *pl;
40,707✔
523
    ptm_setbuffersize *psbs;
40,707✔
524
    ptm_getinfo *pgi, _pgi;
40,707✔
525
    ptm_lockstorage *pls;
40,707✔
526

527
    size_t out_len = 0;
40,707✔
528
    TPM_RESULT res;
40,707✔
529
    uint32_t remain;
40,707✔
530
    uint32_t buffersize, maxsize, minsize;
40,707✔
531
    uint64_t info_flags;
40,707✔
532
    uint32_t offset;
40,707✔
533
    char *info_data = NULL;
40,707✔
534
    size_t length;
40,707✔
535
    TPM_MODIFIER_INDICATOR orig_locality;
40,707✔
536

537
    if (fd < 0)
40,707✔
538
        return -1;
539

540
    n = ctrlchannel_recv_cmd(fd, &msg);
40,707✔
541
    if (n <= 0) {
40,707✔
542
        goto err_socket;
18,535✔
543
    }
544

545
    SWTPM_PrintAll(" Ctrl Cmd:", " ", msg.msg_iov->iov_base, min(n, 1024));
22,172✔
546

547
    if ((size_t)n < sizeof(input.cmd)) {
22,172✔
548
        goto err_bad_input;
×
549
    }
550

551
    n -= sizeof(input.cmd);
22,172✔
552

553
    switch (be32toh(input.cmd)) {
22,172✔
554
    case CMD_GET_CAPABILITY:
555
        /* must always succeed */
556
        ptm_caps_n->u.resp.tpm_result = htobe32(TPM_SUCCESS);
12✔
557
        ptm_caps_n->u.resp.caps = htobe32(get_ptm_caps_supported(mlp->tpmversion));
17✔
558

559
        out_len = sizeof(*ptm_caps_n);
12✔
560
        break;
12✔
561

562
    case CMD_INIT:
9,049✔
563
        if (n != (ssize_t)sizeof(ptm_init)) /* r/w */
9,049✔
564
            goto err_bad_input;
×
565

566
        if (*tpm_running && !mlp->disable_auto_shutdown)
9,049✔
567
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
8,850✔
568
                                            &mlp->lastCommand);
569

570
        init_p = (ptm_init *)input.body;
9,049✔
571

572
        TPMLIB_Terminate();
9,049✔
573

574
        *tpm_running = false;
9,049✔
575

576
        mlp->storage_locked = !mlp->incoming_migration;
9,049✔
577

578
        res = tpmlib_start(be32toh(init_p->u.req.init_flags),
18,098✔
579
                           mlp->tpmversion, mlp->storage_locked,
580
                           mlp->json_profile);
9,049✔
581
        if (res) {
9,049✔
582
            logprintf(STDERR_FILENO,
12✔
583
                      "Error: Could not initialize the TPM\n");
584
        } else {
585
            *tpm_running = true;
9,037✔
586
            SWTPM_G_FREE(mlp->json_profile);
9,037✔
587
        }
588

589
        *res_p = htobe32(res);
9,049✔
590
        out_len = sizeof(ptm_res);
9,049✔
591
        break;
9,049✔
592

593
    case CMD_STOP:
41✔
594
        if (n != 0) /* wo */
41✔
595
            goto err_bad_input;
×
596

597
        if (*tpm_running && !mlp->disable_auto_shutdown)
41✔
598
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
24✔
599
                                            &mlp->lastCommand);
600

601
        TPMLIB_Terminate();
41✔
602

603
        *tpm_running = false;
41✔
604

605
        *res_p = htobe32(TPM_SUCCESS);
41✔
606
        out_len = sizeof(ptm_res);
41✔
607
        break;
41✔
608

609
    case CMD_SHUTDOWN:
401✔
610
        if (n != 0) /* wo */
401✔
611
            goto err_bad_input;
×
612

613
        if (*tpm_running && !mlp->disable_auto_shutdown)
401✔
614
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
374✔
615
                                            &mlp->lastCommand);
616

617
        TPMLIB_Terminate();
401✔
618

619
        *tpm_running = false;
401✔
620

621
        *res_p = htobe32(TPM_SUCCESS);
401✔
622
        out_len = sizeof(ptm_res);
401✔
623

624
        *terminate = true;
401✔
625
        break;
401✔
626

627
    case CMD_GET_TPMESTABLISHED:
72✔
628
        if (!*tpm_running)
72✔
629
            goto err_not_running;
6✔
630

631
        if (n != 0) /* wo */
66✔
632
            goto err_bad_input;
×
633

634
        out_len = sizeof(te->u.resp);
66✔
635
        memset(output.body, 0, out_len);
66✔
636

637
        res = htobe32(TPM_IO_TpmEstablished_Get(&te->u.resp.bit));
66✔
638
        te->u.resp.tpm_result = res;
66✔
639

640
        break;
66✔
641

642
    case CMD_RESET_TPMESTABLISHED:
26✔
643
        if (!*tpm_running)
26✔
644
            goto err_not_running;
×
645

646
        if (n < (ssize_t)sizeof(re->u.req.loc)) /* rw */
26✔
647
            goto err_bad_input;
×
648

649
        re = (ptm_reset_est *)input.body;
26✔
650

651
        if (re->u.req.loc > 4) {
26✔
652
            res = htobe32(TPM_BAD_LOCALITY);
653
        } else {
654
            orig_locality = *locality;
26✔
655
            *locality = re->u.req.loc;
26✔
656

657
            res = htobe32(TPM_IO_TpmEstablished_Reset());
26✔
658

659
            *locality = orig_locality;
26✔
660
        }
661

662
        *res_p = res;
26✔
663
        out_len = sizeof(re->u.resp);
26✔
664
        break;
26✔
665

666
    case CMD_SET_LOCALITY:
57✔
667
        if (n < (ssize_t)sizeof(pl->u.req.loc)) /* rw */
57✔
668
            goto err_bad_input;
×
669

670
        pl = (ptm_loc *)input.body;
57✔
671
        if (pl->u.req.loc > 4 ||
57✔
672
            (pl->u.req.loc == 4 &&
6✔
673
             mlp->locality_flags & LOCALITY_FLAG_REJECT_LOCALITY_4)) {
6✔
674
            res = TPM_BAD_LOCALITY;
675
        } else {
676
            res = TPM_SUCCESS;
57✔
677
            *locality = pl->u.req.loc;
57✔
678
        }
679

680
        *res_p = htobe32(res);
57✔
681
        out_len = sizeof(re->u.resp);
57✔
682
        break;
57✔
683

684
    case CMD_HASH_START:
57✔
685
        if (!*tpm_running)
57✔
686
            goto err_not_running;
×
687

688
        if (n != 0) /* wo */
57✔
689
            goto err_bad_input;
×
690

691
        *res_p = htobe32(TPM_IO_Hash_Start());
57✔
692
        out_len = sizeof(ptm_res);
57✔
693

694
        break;
57✔
695

696
    case CMD_HASH_DATA:
3,131✔
697
        if (!*tpm_running)
3,131✔
NEW
698
            goto err_not_running;
×
699

700
        if (n < (ssize_t)offsetof(ptm_hdata, u.req.data)) /* rw */
3,131✔
NEW
701
            goto err_bad_input;
×
702

703
        data = (ptm_hdata *)&input.body;
3,131✔
704
        remain = be32toh(data->u.req.length);
3,131✔
705
        n -= sizeof(data->u.req.length);
3,131✔
706
        if (remain < n)
3,131✔
NEW
707
            goto err_bad_input;
×
708
        /* n has the available number of bytes to hash */
709

710
        while (true) {
3,131✔
711
            res = TPM_IO_Hash_Data(data->u.req.data, n);
3,131✔
712
            if (res)
3,131✔
713
                break;
714
            remain -= n;
3,131✔
715
            if (!remain)
3,131✔
716
                break;
717

UNCOV
718
            n = read_eintr(fd, &data->u.req.data, sizeof(data->u.req.data));
×
UNCOV
719
            if (n <= 0) {
×
720
                res = TPM_IOERROR;
721
                break;
722
            }
723
        }
724

725
        data = (ptm_hdata *)&output.body;
3,131✔
726

727
        data->u.resp.tpm_result = htobe32(res);
3,131✔
728
        out_len = sizeof(data->u.resp.tpm_result);
3,131✔
729

730
        break;
3,131✔
731

732
    case CMD_HASH_END:
57✔
733
        if (!*tpm_running)
57✔
UNCOV
734
            goto err_not_running;
×
735

736
        if (n != 0) /* wo */
57✔
UNCOV
737
            goto err_bad_input;
×
738

739
        *res_p = htobe32(TPM_IO_Hash_End());
57✔
740
        out_len = sizeof(ptm_res);
57✔
741

742
        break;
57✔
743

UNCOV
744
    case CMD_CANCEL_TPM_CMD:
×
UNCOV
745
        if (!*tpm_running)
×
746
            goto err_not_running;
×
747

748
        if (n != 0) /* wo */
×
UNCOV
749
            goto err_bad_input;
×
750

751
        /* for cancellation to work, the TPM would have to
752
         * execute in another thread that polls on a cancel
753
         * flag
754
         */
UNCOV
755
        *res_p = htobe32(TPMLIB_CancelCommand());
×
UNCOV
756
        out_len = sizeof(ptm_res);
×
757
        break;
×
758

759
    case CMD_STORE_VOLATILE:
8,841✔
760
        if (!*tpm_running)
8,841✔
UNCOV
761
            goto err_not_running;
×
762

763
        if (n != 0) /* wo */
8,841✔
UNCOV
764
            goto err_bad_input;
×
765

766
        *res_p = htobe32(SWTPM_NVRAM_Store_Volatile());
8,841✔
767
        out_len = sizeof(ptm_res);
8,841✔
768
        break;
8,841✔
769

770
    case CMD_GET_STATEBLOB:
56✔
771
        if (!*tpm_running)
56✔
UNCOV
772
            goto err_not_running;
×
773

774
        pgs = (ptm_getstate *)input.body;
56✔
775
        if (n < (ssize_t)sizeof(pgs->u.req)) /* rw */
56✔
UNCOV
776
            goto err_bad_input;
×
777

778
        return ctrlchannel_return_state(pgs, fd, mlp);
56✔
779

780
    case CMD_SET_STATEBLOB:
62✔
781
        if (*tpm_running)
62✔
UNCOV
782
            goto err_running;
×
783

784
        /* tpm state dir must be set */
785
        SWTPM_NVRAM_Init();
62✔
786
        if ((*terminate = !mainloop_ensure_locked_storage(mlp)))
62✔
UNCOV
787
            goto err_io;
×
788

789
        pss = (ptm_setstate *)input.body;
62✔
790
        if (n < (ssize_t)offsetof(ptm_setstate, u.req.data)) /* rw */
62✔
UNCOV
791
            goto err_bad_input;
×
792

793
        return ctrlchannel_receive_state(pss, n, fd);
62✔
794

795
    case CMD_GET_CONFIG:
17✔
796
        if (n != 0) /* wo */
17✔
UNCOV
797
            goto err_bad_input;
×
798

799
        pgc->u.resp.tpm_result = htobe32(0);
17✔
800
        pgc->u.resp.flags = htobe32(0);
17✔
801
        if (SWTPM_NVRAM_Has_FileKey())
17✔
802
            pgc->u.resp.flags |= htobe32(PTM_CONFIG_FLAG_FILE_KEY);
6✔
803
        if (SWTPM_NVRAM_Has_MigrationKey())
17✔
804
            pgc->u.resp.flags |= htobe32(PTM_CONFIG_FLAG_MIGRATION_KEY);
6✔
805

806
        out_len = sizeof(pgc->u.resp);
807
        break;
808

809
    case CMD_SET_DATAFD:
2✔
810
#ifdef __CYGWIN__
811
        if (1)
812
            goto err_running;
813
#endif
814
        if (mlp->fd != -1)
2✔
UNCOV
815
            goto err_io;
×
816

817
        cmsg = CMSG_FIRSTHDR(&msg);
2✔
818
        if (!cmsg || cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2✔
819
             cmsg->cmsg_level != SOL_SOCKET ||
2✔
820
             cmsg->cmsg_type != SCM_RIGHTS ||
821
             !(data_fd = (int *)CMSG_DATA(cmsg)) ||
2✔
822
             *data_fd < 0) {
2✔
UNCOV
823
            logprintf(STDERR_FILENO, "no valid data socket in message; cmsg = "
×
824
                                     "%p", cmsg);
825
            goto err_bad_input;
×
826
        }
827

828
        mlp->flags |= MAIN_LOOP_FLAG_USE_FD | MAIN_LOOP_FLAG_KEEP_CONNECTION;
2✔
829
        mlp->fd = *data_fd;
2✔
830

831
        *res_p = htobe32(TPM_SUCCESS);
2✔
832
        out_len = sizeof(ptm_res);
2✔
833
        break;
2✔
834

835
    case CMD_SET_BUFFERSIZE:
18✔
836
        psbs = (ptm_setbuffersize *)input.body;
18✔
837
        if (n < (ssize_t)sizeof(psbs->u.req)) /* rw */
18✔
UNCOV
838
            goto err_bad_input;
×
839

840
        buffersize = be32toh(psbs->u.req.buffersize);
18✔
841

842
        if (buffersize > 0 && *tpm_running)
18✔
843
            goto err_running;
6✔
844

845
        buffersize = TPMLIB_SetBufferSize(buffersize,
12✔
846
                                          &minsize,
847
                                          &maxsize);
848

849
        *res_p = htobe32(TPM_SUCCESS);
12✔
850

851
        psbs = (ptm_setbuffersize *)&output.body;
12✔
852
        out_len = sizeof(psbs->u.resp);
12✔
853

854
        psbs->u.resp.buffersize = htobe32(buffersize);
12✔
855
        psbs->u.resp.minsize = htobe32(minsize);
12✔
856
        psbs->u.resp.maxsize = htobe32(maxsize);
12✔
857

858
        break;
12✔
859

860
    case CMD_GET_INFO:
242✔
861
        if (n < (ssize_t)sizeof(pgi->u.req)) /* rw */
242✔
UNCOV
862
            goto err_bad_input;
×
863

864
        /* copy since flags needs to be 8-byte aligned  */
865
        memcpy(&_pgi, input.body, sizeof(_pgi));
242✔
866
        pgi = &_pgi;
242✔
867

868
        info_flags = be64toh(pgi->u.req.flags);
242✔
869

870
        info_data = TPMLIB_GetInfo(info_flags);
242✔
871
        if (!info_data)
242✔
UNCOV
872
            goto err_memory;
×
873

874
        offset = be32toh(pgi->u.req.offset);
242✔
875
        if (offset >= strlen(info_data)) {
242✔
UNCOV
876
            free(info_data);
×
UNCOV
877
            goto err_bad_input;
×
878
        }
879

880
        length = min(strlen(info_data) + 1 - offset,
242✔
881
                     sizeof(pgi->u.resp.buffer));
882

883
        pgi = (ptm_getinfo *)&output.body;
242✔
884
        pgi->u.resp.tpm_result = htobe32(0);
242✔
885
        pgi->u.resp.totlength = htobe32(strlen(info_data) + 1);
242✔
886
        pgi->u.resp.length = htobe32(length);
242✔
887
        /* client has to collect whole string in case buffer is too small */
888
        memcpy(pgi->u.resp.buffer, &info_data[offset], length);
242✔
889
        free(info_data);
242✔
890

891
        out_len = offsetof(ptm_getinfo, u.resp.buffer) + length;
242✔
892

893
        break;
242✔
894

895
    case CMD_LOCK_STORAGE:
30✔
896
        if (n < (ssize_t)sizeof(pls->u.req)) /* rw */
30✔
UNCOV
897
            goto err_bad_input;
×
898

899
        pls = (ptm_lockstorage *)input.body;
30✔
900

901
        mlp->locking_retries = be32toh(pls->u.req.retries);
30✔
902

903
        pls = (ptm_lockstorage *)&output.body;
30✔
904
        out_len = sizeof(pls->u.resp);
30✔
905

906
        if (!mainloop_ensure_locked_storage(mlp))
30✔
UNCOV
907
            pls->u.resp.tpm_result = htobe32(TPM_FAIL);
×
908
        else
909
            pls->u.resp.tpm_result = htobe32(TPM_SUCCESS);
30✔
910

911
        break;
912

913
    default:
1✔
914
        logprintf(STDERR_FILENO,
1✔
915
                  "Error: Unknown command: 0x%08x\n", be32toh(input.cmd));
916

917
        *res_p = htobe32(TPM_BAD_ORDINAL);
1✔
918
        out_len = sizeof(ptm_res);
1✔
919
    }
920

921
send_resp:
22,054✔
922
    SWTPM_PrintAll(" Ctrl Rsp:", " ", output.body, min(out_len, 1024));
22,054✔
923

924
    n = write_full(fd, output.body, out_len);
22,054✔
925
    if (n < 0) {
22,054✔
UNCOV
926
        logprintf(STDERR_FILENO,
×
UNCOV
927
                  "Error: Could not send response: %s\n", strerror(errno));
×
928
        close(fd);
×
929
        fd = -1;
×
930
    }
931

932
    return fd;
933

UNCOV
934
err_bad_input:
×
UNCOV
935
    *res_p = htobe32(TPM_BAD_PARAMETER);
×
936
    out_len = sizeof(ptm_res);
×
937

938
    goto send_resp;
×
939

940
err_running:
12✔
941
err_not_running:
12✔
942
    *res_p = htobe32(TPM_BAD_ORDINAL);
12✔
943
    out_len = sizeof(ptm_res);
12✔
944

945
    goto send_resp;
12✔
946

UNCOV
947
err_io:
×
UNCOV
948
    *res_p = htobe32(TPM_IOERROR);
×
949
    out_len = sizeof(ptm_res);
×
950

951
    goto send_resp;
×
952

953
err_memory:
×
UNCOV
954
    *res_p = htobe32(TPM_SIZE);
×
955
    out_len = sizeof(ptm_res);
×
956

957
    goto send_resp;
×
958

959
err_socket:
18,535✔
960
    close(fd);
18,535✔
961

962
    return -1;
18,535✔
963
}
964

965
void ctrlchannel_free(struct ctrlchannel *cc)
604✔
966
{
967
    if (!cc)
604✔
968
        return;
969

970
    if (cc->fd >= 0)
419✔
971
        close(cc->fd);
276✔
972
    if (cc->clientfd >= 0)
419✔
973
        close(cc->clientfd);
7✔
974
    if (cc->sockpath) {
419✔
975
        unlink(cc->sockpath);
143✔
976
        free(cc->sockpath);
143✔
977
    }
978
    free(cc);
419✔
979
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc