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

stefanberger / swtpm / 621325588

05 May 2024 09:04PM UTC coverage: 73.542% (+0.2%) from 73.324%
621325588

push

travis-ci

web-flow
Merge defd1f468 into bfd6b8270

7163 of 9740 relevant lines covered (73.54%)

14121.07 hits per line

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

92.36
/src/swtpm/mainloop.c
1
/*
2
 * mainloop.c -- The TPM Emulator's main processing loop
3
 *
4
 * (c) Copyright IBM Corporation 2014, 2015, 2016
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
/* mainLoop() is the main server loop.
39

40
   It reads a TPM request, processes the ordinal, and writes the response
41
*/
42

43
#include <errno.h>
44
#include <stdio.h>
45
#include <stdint.h>
46
#include <stdbool.h>
47
#include <stdlib.h>
48
#include <string.h>
49
#include <poll.h>
50
#include <sys/stat.h>
51
#include <fcntl.h>
52
#include <sys/socket.h>
53

54
#include <libtpms/tpm_error.h>
55
#include <libtpms/tpm_library.h>
56
#include <libtpms/tpm_memory.h>
57

58
#include "swtpm_debug.h"
59
#include "swtpm_io.h"
60
#include "tpmlib.h"
61
#include "locality.h"
62
#include "logging.h"
63
#include "ctrlchannel.h"
64
#include "mainloop.h"
65
#include "utils.h"
66
#include "sys_dependencies.h"
67
#include "compiler_dependencies.h"
68
#include "swtpm_utils.h"
69
#include "swtpm_nvstore.h"
70

71
/* local variables */
72
static TPM_MODIFIER_INDICATOR locality;
73
bool tpm_running = false;
74

75
bool mainloop_terminate;
76

77
TPM_RESULT
78
mainloop_cb_get_locality(TPM_MODIFIER_INDICATOR *loc,
27,716✔
79
                         uint32_t tpmnum SWTPM_ATTR_UNUSED)
80
{
81
    *loc = locality;
27,716✔
82

83
    return TPM_SUCCESS;
27,716✔
84
}
85

86
/* ensure that the storage is locked; returns false in case of failure */
87
bool mainloop_ensure_locked_storage(struct mainLoopParams *mlp)
41,884✔
88
{
89
    TPM_RESULT res;
41,884✔
90

91
    if (mlp->storage_locked)
41,884✔
92
        return true;
93

94
    /* if NVRAM hasn't been initialized yet locking may need to be retried */
95
    res = SWTPM_NVRAM_Lock_Storage(mlp->locking_retries);
155✔
96
    if (res == TPM_RETRY)
155✔
97
        return true;
98
    if (res != TPM_SUCCESS)
28✔
99
        return false;
100

101
    mlp->locking_retries = 0;
28✔
102
    mlp->storage_locked = true;
28✔
103
    mlp->incoming_migration = false;
28✔
104

105
    return true;
28✔
106
}
107

108
void mainloop_unlock_nvram(struct mainLoopParams *mlp,
7✔
109
                           unsigned int locking_retries)
110
{
111
    SWTPM_NVRAM_Unlock();
7✔
112

113
    mlp->storage_locked = false;
7✔
114
    mlp->locking_retries = locking_retries;
7✔
115
}
7✔
116

117
int mainLoop(struct mainLoopParams *mlp,
295✔
118
             int notify_fd)
119
{
120
    TPM_RESULT          rc = 0;
295✔
121
    TPM_CONNECTION_FD   connection_fd;             /* file descriptor for read/write */
295✔
122
    unsigned char       *command = NULL;           /* command buffer */
295✔
123
    uint32_t            command_length;            /* actual length of command bytes */
295✔
124
    uint32_t            max_command_length;        /* command buffer size */
295✔
125
    off_t               cmd_offset;
295✔
126
    /* The response buffer is reused for each command. Thus it can grow but never shrink */
127
    unsigned char       *rbuffer = NULL;           /* actual response bytes */
295✔
128
    uint32_t            rlength = 0;               /* bytes in response buffer */
295✔
129
    uint32_t            rTotal = 0;                /* total allocated bytes */
295✔
130
    int                 ctrlfd;
295✔
131
    int                 ctrlclntfd;
295✔
132
    int                 sockfd;
295✔
133
    int                 ready;
295✔
134
    struct iovec        iov[3];
295✔
135
    uint32_t            ack = htobe32(0);
295✔
136
    struct tpm2_resp_prefix respprefix;
295✔
137
    uint32_t            lastCommand;
295✔
138

139
    /* poolfd[] indexes */
140
    enum {
295✔
141
        DATA_CLIENT_FD = 0,
142
        NOTIFY_FD,
143
        CTRL_SERVER_FD,
144
        CTRL_CLIENT_FD,
145
        DATA_SERVER_FD
146
    };
147

148
    TPM_DEBUG("mainLoop:\n");
295✔
149

150
    max_command_length = tpmlib_get_tpm_property(TPMPROP_TPM_BUFFER_MAX) +
295✔
151
                         sizeof(struct tpm2_send_command_prefix);
152

153
    command = malloc(max_command_length);
295✔
154
    if (!command) {
295✔
155
        logprintf(STDERR_FILENO, "Could not allocate %u bytes for buffer.\n",
×
156
                  max_command_length);
157
        return TPM_FAIL;
×
158
    }
159

160
    /* header and trailer that we may send by setting iov_len */
161
    iov[0].iov_base = &respprefix;
295✔
162
    iov[0].iov_len = 0;
295✔
163
    iov[2].iov_base = &ack;
295✔
164
    iov[2].iov_len = 0;
295✔
165

166
    connection_fd.fd = -1;
295✔
167
    ctrlfd = ctrlchannel_get_fd(mlp->cc);
295✔
168
    ctrlclntfd = ctrlchannel_get_client_fd(mlp->cc);
295✔
169

170
    sockfd = SWTPM_IO_GetSocketFD();
295✔
171

172
    if (mlp->startupType != _TPM_ST_NONE) {
295✔
173
        command_length = tpmlib_create_startup_cmd(
85✔
174
                                  mlp->startupType,
175
                                  mlp->tpmversion,
176
                                  command, max_command_length);
177
        if (command_length > 0) {
85✔
178
            mlp->lastCommand = tpmlib_get_cmd_ordinal(command, command_length);
85✔
179
            rc = TPMLIB_Process(&rbuffer, &rlength, &rTotal,
85✔
180
                                command, command_length);
181
        }
182

183
        if (rc || command_length == 0) {
85✔
184
            mainloop_terminate = true;
×
185
            if (rc)
×
186
                logprintf(STDERR_FILENO, "Could not send Startup: 0x%x\n", rc);
×
187
        }
188
    }
189

190
    while (!mainloop_terminate) {
20,989✔
191

192
        while (rc == 0) {
139,721✔
193
            if (mlp->flags & MAIN_LOOP_FLAG_USE_FD)
119,807✔
194
                connection_fd.fd = mlp->fd;
1,030✔
195

196
            struct pollfd pollfds[] = {
119,807✔
197
                [DATA_CLIENT_FD] = {
198
                    .fd = connection_fd.fd,
119,807✔
199
                    .events = POLLIN | POLLHUP,
200
                    .revents = 0,
201
                },
202
                [NOTIFY_FD] = {
203
                    .fd = notify_fd,
204
                    .events = POLLIN,
205
                    .revents = 0,
206
                },
207
                [CTRL_SERVER_FD] = {
208
                    .fd = -1,
209
                    .events = POLLIN,
210
                    .revents = 0,
211
                },
212
                [CTRL_CLIENT_FD] = {
213
                    .fd = ctrlclntfd,
214
                    .events = POLLIN | POLLHUP,
215
                    .revents = 0,
216
                },
217
                [DATA_SERVER_FD] = {
218
                    /* listen socket for accepting clients */
219
                    .fd = -1,
220
                    .events = POLLIN,
221
                    .revents = 0,
222
                }
223
            };
224

225
            /* only listend for clients if we don't have one */
226
            if (connection_fd.fd < 0)
119,807✔
227
                pollfds[DATA_SERVER_FD].fd = sockfd;
77,785✔
228
            if (ctrlclntfd < 0)
119,807✔
229
                pollfds[CTRL_SERVER_FD].fd = ctrlfd;
79,564✔
230

231
            ready = poll(pollfds, 5, -1);
119,807✔
232
            if (ready < 0 && errno == EINTR)
119,807✔
233
                continue;
77,724✔
234

235
            if (ready < 0 ||
119,804✔
236
                (pollfds[NOTIFY_FD].revents & POLLIN) != 0) {
119,804✔
237
                SWTPM_IO_Disconnect(&connection_fd);
3✔
238
                break;
787✔
239
            }
240

241
            if (pollfds[DATA_CLIENT_FD].revents & (POLLHUP | POLLERR)) {
119,801✔
242
                logprintf(STDERR_FILENO, "Data client disconnected\n");
158✔
243
                mlp->fd = -1;
158✔
244
                /* chardev and unixio get this signal, not tcp */
245
                if (mlp->flags & MAIN_LOOP_FLAG_END_ON_HUP) {
158✔
246
                    /* only the chardev terminates here */
247
                    mainloop_terminate = true;
×
248
                    break;
×
249
                }
250
            }
251

252
            if (pollfds[DATA_SERVER_FD].revents & POLLIN)
119,801✔
253
                connection_fd.fd = accept(pollfds[DATA_SERVER_FD].fd, NULL, 0);
20,404✔
254

255
            if (pollfds[CTRL_SERVER_FD].revents & POLLIN)
119,801✔
256
                ctrlclntfd = accept(ctrlfd, NULL, 0);
18,190✔
257

258
            if (pollfds[CTRL_CLIENT_FD].revents & POLLIN) {
119,801✔
259
                ctrlclntfd = ctrlchannel_process_fd(ctrlclntfd,
39,440✔
260
                                                    &mainloop_terminate,
261
                                                    &locality, &tpm_running,
262
                                                    mlp);
263
                if (ctrlclntfd < 0 &&
39,440✔
264
                    mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP)
17,981✔
265
                    mainloop_terminate = true;
4✔
266

267
                if (mainloop_terminate)
39,440✔
268
                    break;
269
            }
270

271
            if (pollfds[CTRL_CLIENT_FD].revents & POLLHUP) {
119,512✔
272
                if (ctrlclntfd >= 0)
529✔
273
                    close(ctrlclntfd);
×
274
                ctrlclntfd = -1;
529✔
275
                /* unixio gets this signal, not tcp */
276
                if (mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP) {
529✔
277
                    mainloop_terminate = true;
×
278
                    break;
×
279
                }
280
            }
281

282
            if (!(pollfds[DATA_CLIENT_FD].revents & POLLIN))
119,512✔
283
                continue;
77,721✔
284

285
            /* before processing a command ensure that the storage is locked */
286
            if ((mainloop_terminate = !mainloop_ensure_locked_storage(mlp)))
41,791✔
287
                break;
288

289
            /* Read the command.  The number of bytes is determined by 'paramSize' in the stream */
290
            if (rc == 0) {
41,791✔
291
                rc = SWTPM_IO_Read(&connection_fd, command, &command_length,
41,791✔
292
                                   max_command_length);
293
                if (rc != 0) {
41,791✔
294
                    /* connection broke */
295
                    SWTPM_IO_Disconnect(&connection_fd);
20,029✔
296
                }
297
            }
298

299
            cmd_offset = 0;
41,791✔
300
            /* Handle optional TCG Header in front of TPM 2 Command */
301
            if (rc == 0 && mlp->tpmversion == TPMLIB_TPM_VERSION_2) {
41,791✔
302
                cmd_offset = tpmlib_handle_tcg_tpm2_cmd_header(command,
9,647✔
303
                                                               command_length,
304
                                                               &locality);
305
                if (cmd_offset > 0) {
9,647✔
306
                    /* send header and trailer */
307
                    iov[0].iov_len = sizeof(respprefix);
6,301✔
308
                    iov[2].iov_len = sizeof(ack);
6,301✔
309
                } else {
310
                    iov[0].iov_len = 0;
3,346✔
311
                    iov[2].iov_len = 0;
3,346✔
312
                }
313
            }
314

315
            if (rc == 0) {
41,791✔
316
                if (!tpm_running) {
21,762✔
317
                    tpmlib_write_fatal_error_response(&rbuffer, &rlength,
15✔
318
                                                      &rTotal,
319
                                                      mlp->tpmversion);
320
                    goto skip_process;
15✔
321
                }
322
            }
323

324
            if (rc == 0) {
41,776✔
325
                lastCommand =
21,747✔
326
                    tpmlib_get_cmd_ordinal(&command[cmd_offset],
43,494✔
327
                                           command_length - cmd_offset);
21,747✔
328
                if (lastCommand != TPM_ORDINAL_NONE)
21,747✔
329
                    mlp->lastCommand = lastCommand;
21,747✔
330
            }
331

332
            if (rc == 0) {
41,776✔
333
                rlength = 0;                                /* clear the response buffer */
21,747✔
334
                rc = tpmlib_process(&rbuffer,
21,747✔
335
                                    &rlength,
336
                                    &rTotal,
337
                                    &command[cmd_offset],
338
                                    command_length - cmd_offset,
339
                                    mlp->locality_flags,
340
                                    &locality,
341
                                    mlp->tpmversion);
342
                if (rlength)
21,747✔
343
                    goto skip_process;
×
344
            }
345

346
            if (rc == 0) {
41,776✔
347
                rlength = 0;                                /* clear the response buffer */
21,747✔
348
                rc = TPMLIB_Process(&rbuffer,
21,747✔
349
                                    &rlength,
350
                                    &rTotal,
351
                                    &command[cmd_offset],
352
                                    command_length - cmd_offset);
353
            }
354

355
skip_process:
20,029✔
356
            /* write the results */
357
            if (rc == 0) {
41,791✔
358
                respprefix.size = htobe32(rlength);
21,762✔
359
                iov[1].iov_base = rbuffer;
21,762✔
360
                iov[1].iov_len  = rlength;
21,762✔
361

362
                SWTPM_IO_Write(&connection_fd, iov, ARRAY_LEN(iov));
21,762✔
363
            }
364

365
            if (!(mlp->flags & MAIN_LOOP_FLAG_KEEP_CONNECTION)) {
41,791✔
366
                SWTPM_IO_Disconnect(&connection_fd);
492✔
367
                break;
492✔
368
            }
369
        }
370

371
        rc = 0; /* A fatal TPM_Process() error should cause the TPM to enter shutdown.  IO errors
20,698✔
372
                   are outside the TPM, so the TPM does not shut down.  The main loop should
373
                   continue to function.*/
374
        if (connection_fd.fd < 0 && mlp->flags & MAIN_LOOP_FLAG_TERMINATE)
20,698✔
375
            break;
376
    }
377

378
    if (tpm_running && !mlp->disable_auto_shutdown)
295✔
379
        tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion, &mlp->lastCommand);
5✔
380

381
    free(rbuffer);
295✔
382
    free(command);
295✔
383

384
    if (ctrlclntfd >= 0)
295✔
385
        close(ctrlclntfd);
287✔
386
    ctrlchannel_set_client_fd(mlp->cc, -1);
295✔
387

388
    if (connection_fd.fd >= 0 && !(mlp->flags & MAIN_LOOP_FLAG_USE_FD))
295✔
389
        close(connection_fd.fd);
×
390

391
    if (mlp->fd >= 0) {
295✔
392
        close(mlp->fd);
248✔
393
        mlp->fd = -1;
248✔
394
    }
395

396
    return rc;
295✔
397
}
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