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

stefanberger / swtpm / #2757

20 Jan 2025 04:22PM UTC coverage: 73.325% (+0.1%) from 73.203%
#2757

push

travis-ci

web-flow
Merge a51e38e2b into cfe93d90b

8032 of 10954 relevant lines covered (73.32%)

13619.67 hits per line

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

83.07
/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,
413✔
75
                                    const char *sockpath)
76
{
77
    struct ctrlchannel *cc = calloc(1, sizeof(struct ctrlchannel));
413✔
78

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

84
    if (sockpath) {
413✔
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;
413✔
94
    if (is_client)
413✔
95
        cc->clientfd = fd;
142✔
96
    else
97
        cc->fd = fd;
271✔
98

99
    return cc;
100
}
101

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

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

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

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

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

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

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

128
    return clientfd;
406✔
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)
63✔
209
{
210
    uint32_t blobtype = be32toh(pss->u.req.type);
63✔
211
    uint32_t tpm_number = 0;
63✔
212
    unsigned char *blob = NULL;
63✔
213
    uint32_t blob_length = be32toh(pss->u.req.length);
63✔
214
    uint32_t remain = blob_length, offset = 0;
63✔
215
    TPM_RESULT res;
63✔
216
    uint32_t flags = be32toh(pss->u.req.state_flags);
63✔
217
    TPM_BOOL is_encrypted = (flags & PTM_STATE_FLAG_ENCRYPTED) != 0;
63✔
218

219
    blob = malloc(blob_length);
63✔
220
    if (!blob) {
63✔
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);
63✔
228
    /* n holds the number of available data bytes */
229

230
    while (true) {
114✔
231
        if (n < 0 || (uint32_t)n > remain) {
114✔
232
            res = TPM_BAD_PARAMETER;
×
233
            goto err_send_resp;
×
234
        }
235
        memcpy(&blob[offset], pss->u.req.data, n);
114✔
236
        offset += n;
114✔
237
        remain -= n;
114✔
238
        if (remain) {
114✔
239
            n = read_eintr(fd, pss->u.req.data, sizeof(pss->u.req.data));
51✔
240
            if (n < 0) {
51✔
241
                close(fd);
×
242
                fd = -1;
×
243
                goto err_fd_broken;
×
244
            } else if (n == 0) {
51✔
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,
63✔
254
                                   tpm_number, blobtype);
255

256
err_send_resp:
63✔
257
    pss->u.resp.tpm_result = htobe32(res);
63✔
258
    n = write_full(fd, pss, sizeof(pss->u.resp.tpm_result));
63✔
259
    if (n < 0) {
63✔
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:
63✔
267

268
    free(blob);
63✔
269

270
    return fd;
63✔
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,
81✔
283
                          struct timespec *start,
284
                          struct timespec *diff)
285
{
286
    diff->tv_nsec = end->tv_nsec - start->tv_nsec;
81✔
287
    diff->tv_sec = end->tv_sec - start->tv_sec;
81✔
288
    if (diff->tv_nsec < 0) {
81✔
289
        diff->tv_nsec += 1E9;
41✔
290
        diff->tv_sec -= 1;
41✔
291
    }
292
}
81✔
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,537✔
312
                                    struct msghdr *msg)
313
{
314
    ssize_t n;
40,537✔
315
    size_t recvd = 0;
40,537✔
316
    size_t needed = offsetof(struct input, body);
40,537✔
317
    struct input *input = (struct input *)msg->msg_iov[0].iov_base;
40,537✔
318
    struct pollfd pollfd =  {
40,537✔
319
        .fd = fd,
320
        .events = POLLIN,
321
    };
322
    struct timespec deadline, now, timeout;
40,537✔
323
    int to;
40,537✔
324
    size_t buffer_len = msg->msg_iov[0].iov_len;
40,537✔
325
    /* Read-write */
326
    ptm_init *init_p;
40,537✔
327
    ptm_reset_est *pre;
40,537✔
328
    ptm_hdata *phd;
40,537✔
329
    ptm_getstate *pgs;
40,537✔
330
    ptm_setstate *pss;
40,537✔
331
    ptm_loc *pl;
40,537✔
332
    const void *msg_iov = msg->msg_iov;
40,537✔
333

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

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

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

361
        switch (be32toh(input->cmd)) {
22,138✔
362
        case CMD_GET_CAPABILITY:
363
            break;
364
        case CMD_INIT:
9,007✔
365
            needed = offsetof(struct input, body) +
9,007✔
366
                     sizeof(init_p->u.req);
367
            break;
9,007✔
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:
115✔
401
            needed = offsetof(struct input, body) +
115✔
402
                     offsetof(struct ptm_setstate, u.req.data);
403
            if (recvd >= needed) {
115✔
404
                pss = (struct ptm_setstate *)&input->body;
115✔
405
                needed += be32toh(pss->u.req.length);
115✔
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,138✔
417
            break;
418

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

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

427
        /* wait for the next chunk */
428
        while (true) {
81✔
429
            n = poll(&pollfd, 1, to);
81✔
430
            if (n < 0 && errno == EINTR)
81✔
431
                continue;
×
432
            if (n <= 0)
81✔
433
                return n;
×
434
            break;
435
        }
436
        /* we should have data now */
437
    }
438
    return recvd;
22,086✔
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,537✔
487
                           bool *terminate,
488
                           TPM_MODIFIER_INDICATOR *locality,
489
                           bool *tpm_running,
490
                           struct mainLoopParams *mlp)
491
{
492
    struct input input = {0, };
40,537✔
493
    struct output {
40,537✔
494
        uint8_t body[sizeof(struct ptm_hdata)]; /* ptm_hdata is largest */
495
    } output;
496
    ssize_t n;
40,537✔
497
    struct iovec iov = {
40,537✔
498
        .iov_base = &input,
499
        .iov_len = sizeof(input),
500
    };
501
    char control[CMSG_SPACE(sizeof(int))];
40,537✔
502
    struct msghdr msg = {
40,537✔
503
        .msg_iov = &iov,
504
        .msg_iovlen = 1,
505
        .msg_control = control,
506
        .msg_controllen = sizeof(control),
507
    };
508
    struct cmsghdr *cmsg = NULL;
40,537✔
509
    int *data_fd = NULL;
40,537✔
510

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

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

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

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

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

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

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

553
    switch (be32toh(input.cmd)) {
22,086✔
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,007✔
563
        if (n != (ssize_t)sizeof(ptm_init)) /* r/w */
9,007✔
564
            goto err_bad_input;
×
565

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

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

572
        TPMLIB_Terminate();
9,007✔
573

574
        *tpm_running = false;
9,007✔
575

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

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

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

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

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

601
        TPMLIB_Terminate();
42✔
602

603
        *tpm_running = false;
42✔
604

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

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

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

617
        TPMLIB_Terminate();
399✔
618

619
        *tpm_running = false;
399✔
620

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

624
        *terminate = true;
399✔
625
        break;
399✔
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✔
698
             goto err_not_running;
×
699

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

703
        data = (ptm_hdata *)&input.body;
3,131✔
704
        remain = htobe32(data->u.req.length);
3,131✔
705
        n -= sizeof(data->u.req.length);
3,131✔
706
        /* n has the available number of bytes to hash */
707

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

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

723
        data = (ptm_hdata *)&output.body;
3,131✔
724

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

728
        break;
3,131✔
729

730
    case CMD_HASH_END:
57✔
731
        if (!*tpm_running)
57✔
732
            goto err_not_running;
×
733

734
        if (n != 0) /* wo */
57✔
735
            goto err_bad_input;
×
736

737
        *res_p = htobe32(TPM_IO_Hash_End());
57✔
738
        out_len = sizeof(ptm_res);
57✔
739

740
        break;
57✔
741

742
    case CMD_CANCEL_TPM_CMD:
×
743
        if (!*tpm_running)
×
744
            goto err_not_running;
×
745

746
        if (n != 0) /* wo */
×
747
            goto err_bad_input;
×
748

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

757
    case CMD_STORE_VOLATILE:
8,799✔
758
        if (!*tpm_running)
8,799✔
759
            goto err_not_running;
×
760

761
        if (n != 0) /* wo */
8,799✔
762
            goto err_bad_input;
×
763

764
        *res_p = htobe32(SWTPM_NVRAM_Store_Volatile());
8,799✔
765
        out_len = sizeof(ptm_res);
8,799✔
766
        break;
8,799✔
767

768
    case CMD_GET_STATEBLOB:
56✔
769
        if (!*tpm_running)
56✔
770
            goto err_not_running;
×
771

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

776
        return ctrlchannel_return_state(pgs, fd, mlp);
56✔
777

778
    case CMD_SET_STATEBLOB:
63✔
779
        if (*tpm_running)
63✔
780
            goto err_running;
×
781

782
        /* tpm state dir must be set */
783
        SWTPM_NVRAM_Init();
63✔
784
        if ((*terminate = !mainloop_ensure_locked_storage(mlp)))
63✔
785
            goto err_io;
×
786

787
        pss = (ptm_setstate *)input.body;
63✔
788
        if (n < (ssize_t)offsetof(ptm_setstate, u.req.data)) /* rw */
63✔
789
            goto err_bad_input;
×
790

791
        return ctrlchannel_receive_state(pss, n, fd);
63✔
792

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

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

804
        out_len = sizeof(pgc->u.resp);
805
        break;
806

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

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

826
        mlp->flags |= MAIN_LOOP_FLAG_USE_FD | MAIN_LOOP_FLAG_KEEP_CONNECTION;
2✔
827
        mlp->fd = *data_fd;
2✔
828

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

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

838
        buffersize = be32toh(psbs->u.req.buffersize);
18✔
839

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

843
        buffersize = TPMLIB_SetBufferSize(buffersize,
12✔
844
                                          &minsize,
845
                                          &maxsize);
846

847
        *res_p = htobe32(TPM_SUCCESS);
12✔
848

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

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

856
        break;
12✔
857

858
    case CMD_GET_INFO:
240✔
859
        if (n < (ssize_t)sizeof(pgi->u.req)) /* rw */
240✔
860
            goto err_bad_input;
×
861

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

866
        info_flags = be64toh(pgi->u.req.flags);
240✔
867

868
        info_data = TPMLIB_GetInfo(info_flags);
240✔
869
        if (!info_data)
240✔
870
            goto err_memory;
×
871

872
        offset = be32toh(pgi->u.req.offset);
240✔
873
        if (offset >= strlen(info_data)) {
240✔
874
            free(info_data);
×
875
            goto err_bad_input;
×
876
        }
877

878
        length = min(strlen(info_data) + 1 - offset,
240✔
879
                     sizeof(pgi->u.resp.buffer));
880

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

889
        out_len = offsetof(ptm_getinfo, u.resp.buffer) + length;
240✔
890

891
        break;
240✔
892

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

897
        pls = (ptm_lockstorage *)input.body;
30✔
898

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

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

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

909
        break;
910

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

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

919
send_resp:
21,967✔
920
    SWTPM_PrintAll(" Ctrl Rsp:", " ", output.body, min(out_len, 1024));
21,967✔
921

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

930
    return fd;
931

932
err_bad_input:
×
933
    *res_p = htobe32(TPM_BAD_PARAMETER);
×
934
    out_len = sizeof(ptm_res);
×
935

936
    goto send_resp;
×
937

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

943
    goto send_resp;
12✔
944

945
err_io:
×
946
    *res_p = htobe32(TPM_IOERROR);
×
947
    out_len = sizeof(ptm_res);
×
948

949
    goto send_resp;
×
950

951
err_memory:
×
952
    *res_p = htobe32(TPM_SIZE);
×
953
    out_len = sizeof(ptm_res);
×
954

955
    goto send_resp;
×
956

957
err_socket:
18,451✔
958
    close(fd);
18,451✔
959

960
    return -1;
18,451✔
961
}
962

963
void ctrlchannel_free(struct ctrlchannel *cc)
596✔
964
{
965
    if (!cc)
596✔
966
        return;
967

968
    if (cc->fd >= 0)
413✔
969
        close(cc->fd);
271✔
970
    if (cc->clientfd >= 0)
413✔
971
        close(cc->clientfd);
7✔
972
    if (cc->sockpath) {
413✔
973
        unlink(cc->sockpath);
143✔
974
        free(cc->sockpath);
143✔
975
    }
976
    free(cc);
413✔
977
}
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