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

stefanberger / swtpm / #2824

13 May 2025 12:34PM UTC coverage: 72.964% (-0.5%) from 73.462%
#2824

push

travis-ci

web-flow
Merge c2b02e9b2 into 1544c99ca

7033 of 9639 relevant lines covered (72.96%)

13748.12 hits per line

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

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

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

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

99
    return cc;
100
}
101

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

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

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

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

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

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

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

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

334
    clock_gettime(CLOCK_REALTIME, &deadline);
27,117✔
335

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

343
    while (recvd < buffer_len) {
27,184✔
344
        if (!recvd) {
27,155✔
345
            n = recvmsg(fd, msg, 0);
27,117✔
346
            /* address a coverity issue by validating msg */
347
            if (msg_iov != msg->msg_iov ||
27,117✔
348
                msg->msg_iov[0].iov_base != input ||
27,117✔
349
                msg->msg_iov[0].iov_len > buffer_len)
27,117✔
350
                return -1;
351
        } else
352
            n = read_eintr(fd, msg->msg_iov[0].iov_base + recvd, buffer_len - recvd);
38✔
353
        if (n <= 0)
27,155✔
354
            return n;
11,824✔
355
        recvd += n;
15,331✔
356
        /* we need to at least see the cmd */
357
        if (recvd < offsetof(struct input, body))
15,331✔
358
            goto wait_chunk;
×
359

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

415
        if (recvd >= needed)
15,331✔
416
            break;
417

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

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

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

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

464
    return caps;
12✔
465
}
466

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

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

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

536
    if (fd < 0)
27,117✔
537
        return -1;
538

539
    n = ctrlchannel_recv_cmd(fd, &msg);
27,117✔
540
    if (n <= 0) {
27,117✔
541
        goto err_socket;
11,824✔
542
    }
543

544
    SWTPM_PrintAll(" Ctrl Cmd:", " ", msg.msg_iov->iov_base, min(n, 1024));
15,293✔
545

546
    if ((size_t)n < sizeof(input.cmd)) {
15,293✔
547
        goto err_bad_input;
×
548
    }
549

550
    n -= sizeof(input.cmd);
15,293✔
551

552
    switch (be32toh(input.cmd)) {
15,293✔
553
    case CMD_GET_CAPABILITY:
12✔
554
        *ptm_caps = htobe64(get_ptm_caps_supported(mlp->tpmversion));
17✔
555

556
        out_len = sizeof(*ptm_caps);
12✔
557
        break;
12✔
558

559
    case CMD_INIT:
5,753✔
560
        if (n != (ssize_t)sizeof(ptm_init)) /* r/w */
5,753✔
561
            goto err_bad_input;
×
562

563
        if (*tpm_running && !mlp->disable_auto_shutdown)
5,753✔
564
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
5,554✔
565
                                            &mlp->lastCommand);
566

567
        init_p = (ptm_init *)input.body;
5,753✔
568

569
        TPMLIB_Terminate();
5,753✔
570

571
        *tpm_running = false;
5,753✔
572

573
        mlp->storage_locked = !mlp->incoming_migration;
5,753✔
574

575
        res = tpmlib_start(be32toh(init_p->u.req.init_flags),
5,753✔
576
                           mlp->tpmversion, mlp->storage_locked);
577
        if (res) {
5,753✔
578
            logprintf(STDERR_FILENO,
12✔
579
                      "Error: Could not initialize the TPM\n");
580
        } else {
581
            *tpm_running = true;
5,741✔
582
        }
583

584
        *res_p = htobe32(res);
5,753✔
585
        out_len = sizeof(ptm_res);
5,753✔
586
        break;
5,753✔
587

588
    case CMD_STOP:
42✔
589
        if (n != 0) /* wo */
42✔
590
            goto err_bad_input;
×
591

592
        if (*tpm_running && !mlp->disable_auto_shutdown)
42✔
593
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
24✔
594
                                            &mlp->lastCommand);
595

596
        TPMLIB_Terminate();
42✔
597

598
        *tpm_running = false;
42✔
599

600
        *res_p = htobe32(TPM_SUCCESS);
42✔
601
        out_len = sizeof(ptm_res);
42✔
602
        break;
42✔
603

604
    case CMD_SHUTDOWN:
277✔
605
        if (n != 0) /* wo */
277✔
606
            goto err_bad_input;
×
607

608
        if (*tpm_running && !mlp->disable_auto_shutdown)
277✔
609
            tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion,
251✔
610
                                            &mlp->lastCommand);
611

612
        TPMLIB_Terminate();
277✔
613

614
        *tpm_running = false;
277✔
615

616
        *res_p = htobe32(TPM_SUCCESS);
277✔
617
        out_len = sizeof(ptm_res);
277✔
618

619
        *terminate = true;
277✔
620
        break;
277✔
621

622
    case CMD_GET_TPMESTABLISHED:
72✔
623
        if (!*tpm_running)
72✔
624
            goto err_not_running;
6✔
625

626
        if (n != 0) /* wo */
66✔
627
            goto err_bad_input;
×
628

629
        out_len = sizeof(te->u.resp);
66✔
630
        memset(output.body, 0, out_len);
66✔
631

632
        res = htobe32(TPM_IO_TpmEstablished_Get(&te->u.resp.bit));
66✔
633
        te->u.resp.tpm_result = res;
66✔
634

635
        break;
66✔
636

637
    case CMD_RESET_TPMESTABLISHED:
26✔
638
        if (!*tpm_running)
26✔
639
            goto err_not_running;
×
640

641
        if (n < (ssize_t)sizeof(re->u.req.loc)) /* rw */
26✔
642
            goto err_bad_input;
×
643

644
        re = (ptm_reset_est *)input.body;
26✔
645

646
        if (re->u.req.loc > 4) {
26✔
647
            res = htobe32(TPM_BAD_LOCALITY);
648
        } else {
649
            orig_locality = *locality;
26✔
650
            *locality = re->u.req.loc;
26✔
651

652
            res = htobe32(TPM_IO_TpmEstablished_Reset());
26✔
653

654
            *locality = orig_locality;
26✔
655
        }
656

657
        *res_p = res;
26✔
658
        out_len = sizeof(re->u.resp);
26✔
659
        break;
26✔
660

661
    case CMD_SET_LOCALITY:
57✔
662
        if (n < (ssize_t)sizeof(pl->u.req.loc)) /* rw */
57✔
663
            goto err_bad_input;
×
664

665
        pl = (ptm_loc *)input.body;
57✔
666
        if (pl->u.req.loc > 4 ||
57✔
667
            (pl->u.req.loc == 4 &&
6✔
668
             mlp->locality_flags & LOCALITY_FLAG_REJECT_LOCALITY_4)) {
6✔
669
            res = TPM_BAD_LOCALITY;
670
        } else {
671
            res = TPM_SUCCESS;
57✔
672
            *locality = pl->u.req.loc;
57✔
673
        }
674

675
        *res_p = htobe32(res);
57✔
676
        out_len = sizeof(re->u.resp);
57✔
677
        break;
57✔
678

679
    case CMD_HASH_START:
57✔
680
        if (!*tpm_running)
57✔
681
            goto err_not_running;
×
682

683
        if (n != 0) /* wo */
57✔
684
            goto err_bad_input;
×
685

686
        *res_p = htobe32(TPM_IO_Hash_Start());
57✔
687
        out_len = sizeof(ptm_res);
57✔
688

689
        break;
57✔
690

691
    case CMD_HASH_DATA:
3,131✔
692
        if (!*tpm_running)
3,131✔
693
             goto err_not_running;
×
694

695
        if (n < (ssize_t)offsetof(ptm_hdata, u.req.data)) /* rw */
3,131✔
696
             goto err_bad_input;
×
697

698
        data = (ptm_hdata *)&input.body;
3,131✔
699
        remain = htobe32(data->u.req.length);
3,131✔
700
        n -= sizeof(data->u.req.length);
3,131✔
701
        /* n has the available number of bytes to hash */
702

703
        while (true) {
3,131✔
704
            res = TPM_IO_Hash_Data(data->u.req.data, n);
3,131✔
705
            if (res)
3,131✔
706
                break;
707
            remain -= n;
3,131✔
708
            if (!remain)
3,131✔
709
                break;
710

711
            n = read_eintr(fd, &data->u.req.data, sizeof(data->u.req.data));
×
712
            if (n <= 0) {
×
713
                res = TPM_IOERROR;
714
                break;
715
            }
716
        }
717

718
        data = (ptm_hdata *)&output.body;
3,131✔
719

720
        data->u.resp.tpm_result = htobe32(res);
3,131✔
721
        out_len = sizeof(data->u.resp.tpm_result);
3,131✔
722

723
        break;
3,131✔
724

725
    case CMD_HASH_END:
57✔
726
        if (!*tpm_running)
57✔
727
            goto err_not_running;
×
728

729
        if (n != 0) /* wo */
57✔
730
            goto err_bad_input;
×
731

732
        *res_p = htobe32(TPM_IO_Hash_End());
57✔
733
        out_len = sizeof(ptm_res);
57✔
734

735
        break;
57✔
736

737
    case CMD_CANCEL_TPM_CMD:
×
738
        if (!*tpm_running)
×
739
            goto err_not_running;
×
740

741
        if (n != 0) /* wo */
×
742
            goto err_bad_input;
×
743

744
        /* for cancellation to work, the TPM would have to
745
         * execute in another thread that polls on a cancel
746
         * flag
747
         */
748
        *res_p = htobe32(TPMLIB_CancelCommand());
×
749
        out_len = sizeof(ptm_res);
×
750
        break;
×
751

752
    case CMD_STORE_VOLATILE:
5,545✔
753
        if (!*tpm_running)
5,545✔
754
            goto err_not_running;
×
755

756
        if (n != 0) /* wo */
5,545✔
757
            goto err_bad_input;
×
758

759
        *res_p = htobe32(SWTPM_NVRAM_Store_Volatile());
5,545✔
760
        out_len = sizeof(ptm_res);
5,545✔
761
        break;
5,545✔
762

763
    case CMD_GET_STATEBLOB:
56✔
764
        if (!*tpm_running)
56✔
765
            goto err_not_running;
×
766

767
        pgs = (ptm_getstate *)input.body;
56✔
768
        if (n < (ssize_t)sizeof(pgs->u.req)) /* rw */
56✔
769
            goto err_bad_input;
×
770

771
        return ctrlchannel_return_state(pgs, fd, mlp);
56✔
772

773
    case CMD_SET_STATEBLOB:
63✔
774
        if (*tpm_running)
63✔
775
            goto err_running;
×
776

777
        /* tpm state dir must be set */
778
        SWTPM_NVRAM_Init();
63✔
779
        if ((*terminate = !mainloop_ensure_locked_storage(mlp)))
63✔
780
            goto err_io;
×
781

782
        pss = (ptm_setstate *)input.body;
63✔
783
        if (n < (ssize_t)offsetof(ptm_setstate, u.req.data)) /* rw */
63✔
784
            goto err_bad_input;
×
785

786
        return ctrlchannel_receive_state(pss, n, fd);
63✔
787

788
    case CMD_GET_CONFIG:
17✔
789
        if (n != 0) /* wo */
17✔
790
            goto err_bad_input;
×
791

792
        pgc->u.resp.tpm_result = htobe32(0);
17✔
793
        pgc->u.resp.flags = htobe32(0);
17✔
794
        if (SWTPM_NVRAM_Has_FileKey())
17✔
795
            pgc->u.resp.flags |= htobe32(PTM_CONFIG_FLAG_FILE_KEY);
6✔
796
        if (SWTPM_NVRAM_Has_MigrationKey())
17✔
797
            pgc->u.resp.flags |= htobe32(PTM_CONFIG_FLAG_MIGRATION_KEY);
6✔
798

799
        out_len = sizeof(pgc->u.resp);
800
        break;
801

802
    case CMD_SET_DATAFD:
2✔
803
#ifdef __CYGWIN__
804
        if (1)
805
            goto err_running;
806
#endif
807
        if (mlp->fd != -1)
2✔
808
            goto err_io;
×
809

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

821
        mlp->flags |= MAIN_LOOP_FLAG_USE_FD | MAIN_LOOP_FLAG_KEEP_CONNECTION;
2✔
822
        mlp->fd = *data_fd;
2✔
823

824
        *res_p = htobe32(TPM_SUCCESS);
2✔
825
        out_len = sizeof(ptm_res);
2✔
826
        break;
2✔
827

828
    case CMD_SET_BUFFERSIZE:
18✔
829
        psbs = (ptm_setbuffersize *)input.body;
18✔
830
        if (n < (ssize_t)sizeof(psbs->u.req)) /* rw */
18✔
831
            goto err_bad_input;
×
832

833
        buffersize = be32toh(psbs->u.req.buffersize);
18✔
834

835
        if (buffersize > 0 && *tpm_running)
18✔
836
            goto err_running;
6✔
837

838
        buffersize = TPMLIB_SetBufferSize(buffersize,
12✔
839
                                          &minsize,
840
                                          &maxsize);
841

842
        *res_p = htobe32(TPM_SUCCESS);
12✔
843

844
        psbs = (ptm_setbuffersize *)&output.body;
12✔
845
        out_len = sizeof(psbs->u.resp);
12✔
846

847
        psbs->u.resp.buffersize = htobe32(buffersize);
12✔
848
        psbs->u.resp.minsize = htobe32(minsize);
12✔
849
        psbs->u.resp.maxsize = htobe32(maxsize);
12✔
850

851
        break;
12✔
852

853
    case CMD_GET_INFO:
77✔
854
        if (n < (ssize_t)sizeof(pgi->u.req)) /* rw */
77✔
855
            goto err_bad_input;
×
856

857
        /* copy since flags needs to be 8-byte aligned  */
858
        memcpy(&_pgi, input.body, sizeof(_pgi));
77✔
859
        pgi = &_pgi;
77✔
860

861
        info_flags = be64toh(pgi->u.req.flags);
77✔
862

863
        info_data = TPMLIB_GetInfo(info_flags);
77✔
864
        if (!info_data)
77✔
865
            goto err_memory;
×
866

867
        offset = be32toh(pgi->u.req.offset);
77✔
868
        if (offset >= strlen(info_data)) {
77✔
869
            free(info_data);
×
870
            goto err_bad_input;
×
871
        }
872

873
        length = min(strlen(info_data) + 1 - offset,
77✔
874
                     sizeof(pgi->u.resp.buffer));
875

876
        pgi = (ptm_getinfo *)&output.body;
77✔
877
        pgi->u.resp.tpm_result = htobe32(0);
77✔
878
        pgi->u.resp.totlength = htobe32(strlen(info_data) + 1);
77✔
879
        pgi->u.resp.length = htobe32(length);
77✔
880
        /* client has to collect whole string in case buffer is too small */
881
        memcpy(pgi->u.resp.buffer, &info_data[offset], length);
77✔
882
        free(info_data);
77✔
883

884
        out_len = offsetof(ptm_getinfo, u.resp.buffer) + length;
77✔
885

886
        break;
77✔
887

888
    case CMD_LOCK_STORAGE:
30✔
889
        if (n < (ssize_t)sizeof(pls->u.req)) /* rw */
30✔
890
            goto err_bad_input;
×
891

892
        pls = (ptm_lockstorage *)input.body;
30✔
893

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

896
        pls = (ptm_lockstorage *)&output.body;
30✔
897
        out_len = sizeof(pls->u.resp);
30✔
898

899
        if (!mainloop_ensure_locked_storage(mlp))
30✔
900
            pls->u.resp.tpm_result = htobe32(TPM_FAIL);
×
901
        else
902
            pls->u.resp.tpm_result = htobe32(TPM_SUCCESS);
30✔
903

904
        break;
905

906
    default:
1✔
907
        logprintf(STDERR_FILENO,
1✔
908
                  "Error: Unknown command: 0x%08x\n", be32toh(input.cmd));
909

910
        *res_p = htobe32(TPM_BAD_ORDINAL);
1✔
911
        out_len = sizeof(ptm_res);
1✔
912
    }
913

914
send_resp:
15,174✔
915
    SWTPM_PrintAll(" Ctrl Rsp:", " ", output.body, min(out_len, 1024));
15,174✔
916

917
    n = write_full(fd, output.body, out_len);
15,174✔
918
    if (n < 0) {
15,174✔
919
        logprintf(STDERR_FILENO,
×
920
                  "Error: Could not send response: %s\n", strerror(errno));
×
921
        close(fd);
×
922
        fd = -1;
×
923
    }
924

925
    return fd;
926

927
err_bad_input:
×
928
    *res_p = htobe32(TPM_BAD_PARAMETER);
×
929
    out_len = sizeof(ptm_res);
×
930

931
    goto send_resp;
×
932

933
err_running:
12✔
934
err_not_running:
12✔
935
    *res_p = htobe32(TPM_BAD_ORDINAL);
12✔
936
    out_len = sizeof(ptm_res);
12✔
937

938
    goto send_resp;
12✔
939

940
err_io:
×
941
    *res_p = htobe32(TPM_IOERROR);
×
942
    out_len = sizeof(ptm_res);
×
943

944
    goto send_resp;
×
945

946
err_memory:
×
947
    *res_p = htobe32(TPM_SIZE);
×
948
    out_len = sizeof(ptm_res);
×
949

950
    goto send_resp;
×
951

952
err_socket:
11,824✔
953
    close(fd);
11,824✔
954

955
    return -1;
11,824✔
956
}
957

958
void ctrlchannel_free(struct ctrlchannel *cc)
364✔
959
{
960
    if (!cc)
364✔
961
        return;
962

963
    if (cc->fd >= 0)
284✔
964
        close(cc->fd);
211✔
965
    if (cc->clientfd >= 0)
284✔
966
        close(cc->clientfd);
×
967
    if (cc->sockpath) {
284✔
968
        unlink(cc->sockpath);
143✔
969
        free(cc->sockpath);
143✔
970
    }
971
    free(cc);
284✔
972
}
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