1 /********************************************************************************/
4 /* IBM Thomas J. Watson Research Center */
6 /* (c) Copyright IBM Corporation 2014-2015. */
8 /* All rights reserved. */
10 /* Redistribution and use in source and binary forms, with or without */
11 /* modification, are permitted provided that the following conditions are */
14 /* Redistributions of source code must retain the above copyright notice, */
15 /* this list of conditions and the following disclaimer. */
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. */
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. */
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 /********************************************************************************/
40 * Eric Richter, erichte@us.ibm.com
41 * Stefan Berger, stefanb@us.ibm.com
42 * David Safford, safford@us.ibm.com
54 #include <arpa/inet.h>
57 #include <fuse/cuse_lowlevel.h>
61 #include <libtpms/tpm_library.h>
62 #include <libtpms/tpm_tis.h>
63 #include <libtpms/tpm_error.h>
64 #include <libtpms/tpm_memory.h>
72 #include "tpm_ioctl.h"
73 #include "swtpm_nvfile.h"
77 #include "threadpool.h"
79 /* maximum size of request buffer */
80 #define TPM_REQ_MAX 4096
82 /* version of the TPM (1.2 or 2) */
83 static TPMLIB_TPMVersion tpmversion
;
85 /* buffer containing the TPM request */
86 static unsigned char *ptm_request
;
88 /* buffer containing the TPM response */
89 static unsigned char *ptm_response
;
91 /* the sizes of the data in the buffers */
92 static uint32_t ptm_req_len
, ptm_res_len
, ptm_res_tot
;
94 /* locality applied to TPM commands */
95 static TPM_MODIFIER_INDICATOR locality
;
97 /* whether the TPM is running (TPM_Init was received) */
98 static bool tpm_running
;
100 /* flags on how to handle locality */
101 static uint32_t locality_flags
;
103 #if GLIB_MAJOR_VERSION >= 2
104 # if GLIB_MINOR_VERSION >= 32
106 GMutex file_ops_lock
;
107 # define FILE_OPS_LOCK &file_ops_lock
111 GMutex
*file_ops_lock
;
112 # define FILE_OPS_LOCK file_ops_lock
117 #error Unsupport glib version
131 /* single message to send to the worker thread */
132 static struct thread_message msg
;
138 TPM_BOOL is_encrypted
;
141 typedef struct stateblob_desc
{
144 TPM_BOOL is_encrypted
;
146 uint32_t data_length
;
149 typedef enum tx_state_type
{
150 TX_STATE_RW_COMMAND
= 1,
151 TX_STATE_SET_STATE_BLOB
= 2,
152 TX_STATE_GET_STATE_BLOB
= 3,
155 typedef struct transfer_state
{
157 /* while in TX_STATE_GET/SET_STATEBLOB */
159 TPM_BOOL blob_is_encrypted
;
160 /* while in TX_STATE_GET */
164 typedef struct TPM_Response_Header
{
168 } __attribute__ ((packed
)) TPM_Response_Header
;
170 /*********************************** data *************************************/
172 static const char *usage
=
173 "usage: %s %s [options]\n"
175 "The following options are supported:\n"
177 "-n NAME|--name=NAME : device name (mandatory)\n"
178 "-M MAJ|--maj=MAJ : device major number\n"
179 "-m MIN|--min=MIN : device minor number\n"
180 "--key file=<path>[,mode=aes-cbc][,format=hex|binary][,remove=[true|false]]\n"
181 " : use an AES key for the encryption of the TPM's state\n"
182 " files; use the given mode for the block encryption;\n"
183 " the key is to be provided as a hex string or in binary\n"
184 " format; the keyfile can be automatically removed using\n"
185 " the remove parameter\n"
186 "--key pwdfile=<path>[,mode=aes-cbc][,remove=[true|false]]\n"
187 " : provide a passphrase in a file; the AES key will be\n"
188 " derived from this passphrase\n"
189 "--locality [reject-locality-4][,allow-set-locality]\n"
190 " : reject-locality-4: reject any command in locality 4\n"
191 " allow-set-locality: accept SetLocality command\n"
192 "--migration-key file=<path>[,mode=aes-cbc][,format=hex|binary][,remove=[true|false]]\n"
193 " : use an AES key for the encryption of the TPM's state\n"
194 " when it is retrieved from the TPM via ioctls;\n"
195 " Setting this key ensures that the TPM's state will always\n"
196 " be encrypted when migrated\n"
197 "--migration-key pwdfile=<path>[,mode=aes-cbc][,remove=[true|false]]\n"
198 " : provide a passphrase in a file; the AES key will be\n"
199 " derived from this passphrase\n"
200 "--log file=<path>|fd=<filedescriptor>[,level=n][,prefix=<prefix>][,truncate]\n"
201 " : write the TPM's log into the given file rather than\n"
202 " to the console; provide '-' for path to avoid logging\n"
203 " log level 5 and higher will enable libtpms logging;\n"
204 " all logged output will be prefixed with prefix;\n"
205 " the log file can be reset (truncate)\n"
206 "--pid file=<path>|fd=<filedescriptor>\n"
207 " : write the process ID into the given file\n"
208 "--tpmstate dir=<dir>[,mode=0...]\n"
209 " : set the directory where the TPM's state will be written\n"
210 " into; the TPM_PATH environment variable can be used\n"
212 " mode allows to set the file mode bits of the state\n"
213 " files; the default mode is 0640;\n"
214 "-r|--runas <user> : after creating the CUSE device, change to the given\n"
216 "--tpm2 : choose TPM2 functionality\n"
217 "-h|--help : display this help screen and terminate\n"
221 ptm_io_getlocality(TPM_MODIFIER_INDICATOR
*loc
, uint32_t tpmnum
)
227 static struct libtpms_callbacks cbs
= {
228 .sizeOfStruct
= sizeof(struct libtpms_callbacks
),
229 .tpm_nvram_init
= SWTPM_NVRAM_Init
,
230 .tpm_nvram_loaddata
= SWTPM_NVRAM_LoadData
,
231 .tpm_nvram_storedata
= SWTPM_NVRAM_StoreData
,
232 .tpm_nvram_deletename
= SWTPM_NVRAM_DeleteName
,
233 .tpm_io_getlocality
= ptm_io_getlocality
,
236 /* the current state the transfer interface is in */
237 static transfer_state tx_state
;
239 /* function prototypes */
240 static void ptm_cleanup(void);
242 /************************* cached stateblob *********************************/
244 static stateblob_desc cached_stateblob
;
247 * cached_stateblob_is_loaded: is the stateblob with the given properties
248 * the one in the cache?
250 static bool cached_stateblob_is_loaded(uint32_t blobtype
,
253 return (cached_stateblob
.data
!= NULL
) &&
254 (cached_stateblob
.blobtype
== blobtype
) &&
255 (cached_stateblob
.decrypt
== decrypt
);
259 * cached_stateblob_free: Free any previously loaded state blob
261 static void cached_stateblob_free(void)
263 free(cached_stateblob
.data
);
264 cached_stateblob
.data
= NULL
;
265 cached_stateblob
.data_length
= 0;
269 * cached_stateblob_get_bloblength: get the total length of the cached blob
271 static uint32_t cached_stateblob_get_bloblength(void)
273 return cached_stateblob
.data_length
;
277 * cached_statblob_get: get stateblob data without copying them
279 * @offset: at which offset to get the data
280 * @bufptr: pointer to a buffer pointer used to return buffer start
281 * @length: pointer used to return number of available bytes in returned buffer
283 static int cached_stateblob_get(uint32_t offset
,
284 unsigned char **bufptr
, size_t *length
)
286 if (cached_stateblob
.data
== NULL
||
287 offset
> cached_stateblob
.data_length
)
290 *bufptr
= &cached_stateblob
.data
[offset
];
291 *length
= cached_stateblob
.data_length
- offset
;
297 * cached_stateblob_load: load a state blob into the cache
299 * blobtype: the type of blob
300 * decrypt: whether the blob is to be decrypted
302 static TPM_RESULT
cached_stateblob_load(uint32_t blobtype
, TPM_BOOL decrypt
)
305 const char *blobname
= tpmlib_get_blobname(blobtype
);
306 uint32_t tpm_number
= 0;
309 return TPM_BAD_PARAMETER
;
311 cached_stateblob_free();
313 if (blobtype
== PTM_BLOB_TYPE_VOLATILE
)
314 res
= SWTPM_NVRAM_Store_Volatile();
317 res
= SWTPM_NVRAM_GetStateBlob(&cached_stateblob
.data
,
318 &cached_stateblob
.data_length
,
319 tpm_number
, blobname
, decrypt
,
320 &cached_stateblob
.is_encrypted
);
322 /* make sure the volatile state file is gone */
323 if (blobtype
== PTM_BLOB_TYPE_VOLATILE
)
324 SWTPM_NVRAM_DeleteName(tpm_number
, blobname
, FALSE
);
327 cached_stateblob
.blobtype
= blobtype
;
328 cached_stateblob
.decrypt
= decrypt
;
335 * cached_state_blob_copy: copy the cached state blob to a destination buffer
337 * dest: destination buffer
338 * destlen: size of the buffer
339 * srcoffset: offset to copy from
340 * copied: variable to return the number of copied bytes
341 * is_encrypted: variable to return whether the blob is encrypted
343 static int cached_stateblob_copy(void *dest
, size_t destlen
,
344 uint32_t srcoffset
, uint32_t *copied
,
345 TPM_BOOL
*is_encrypted
)
351 if (cached_stateblob
.data
!= NULL
&& cached_stateblob
.data_length
> 0) {
353 if (srcoffset
< cached_stateblob
.data_length
) {
354 *copied
= min(cached_stateblob
.data_length
- srcoffset
, destlen
);
356 memcpy(dest
, &cached_stateblob
.data
[srcoffset
], *copied
);
358 *is_encrypted
= cached_stateblob
.is_encrypted
;
367 /************************* worker thread ************************************/
370 * worker_thread: the worker thread
372 static void worker_thread(gpointer data
, gpointer user_data
)
374 struct thread_message
*msg
= (struct thread_message
*)data
;
377 case MESSAGE_TPM_CMD
:
378 TPMLIB_Process(&ptm_response
, &ptm_res_len
, &ptm_res_tot
,
379 ptm_request
, ptm_req_len
);
385 /* results are ready */
386 worker_thread_mark_done();
389 /***************************** utility functions ****************************/
392 * tpm_start: Start the TPM
394 * Check whether the TPM's state directory exists and if it does
395 * not exists, try to creat it. Start the thread pool, initilize
396 * libtpms and allocate a global TPM request buffer.
398 * @flags: libtpms init flags
400 static int tpm_start(uint32_t flags
, TPMLIB_TPMVersion l_tpmversion
)
403 const char *tpmdir
= tpmstate_get_dir();
405 dir
= opendir(tpmdir
);
409 if (mkdir(tpmdir
, 0775)) {
410 logprintf(STDERR_FILENO
,
411 "Error: Could not open tpmstate dir %s\n",
417 pool
= g_thread_pool_new(worker_thread
,
423 logprintf(STDERR_FILENO
,
424 "Error: Could not create the thread pool.\n");
429 ptm_request
= malloc(4096);
431 logprintf(STDERR_FILENO
,
432 "Error: Could not allocate memory for request buffer.\n");
436 if (tpmlib_start(flags
, l_tpmversion
) != TPM_SUCCESS
)
439 logprintf(STDOUT_FILENO
,
440 "CUSE TPM successfully initialized.\n");
445 g_thread_pool_free(pool
, TRUE
, TRUE
);
452 * ptm_write_fatal_error_response: Write fatal error response
454 * Write a fatal error response into the global ptm_response buffer.
456 static void ptm_write_fatal_error_response(TPMLIB_TPMVersion l_tpmversion
)
458 tpmlib_write_fatal_error_response(&ptm_response
,
464 /************************************ read() support ***************************/
467 * ptm_read_result: Return the TPM response packet
469 * @req: the fuse_req_t
470 * @size: the max. number of bytes to return to the requester
472 static void ptm_read_result(fuse_req_t req
, size_t size
)
477 /* wait until results are ready */
478 worker_thread_wait_done();
483 if (ptm_res_len
> size
) {
490 fuse_reply_buf(req
, (const char *)ptm_response
, len
);
494 * ptm_read_stateblob: get a TPM stateblob via the read() interface
496 * @req: the fuse_req_t
497 * @size: the number of bytes to read
499 * The internal offset into the buffer is advanced by the number
500 * of bytes that were copied. We switch back to command read/write
501 * mode if an error occurred or once all bytes were read.
503 static void ptm_read_stateblob(fuse_req_t req
, size_t size
)
505 unsigned char *bufptr
= NULL
;
509 if (cached_stateblob_get(tx_state
.offset
, &bufptr
, &numbytes
) < 0) {
510 fuse_reply_err(req
, EIO
);
511 tx_state
.state
= TX_STATE_RW_COMMAND
;
513 tocopy
= MIN(size
, numbytes
);
514 tx_state
.offset
+= tocopy
;
516 fuse_reply_buf(req
, (char *)bufptr
, tocopy
);
517 /* last transfer indicated by less bytes available than requested */
518 if (numbytes
< size
) {
519 tx_state
.state
= TX_STATE_RW_COMMAND
;
525 * ptm_read: interface to POSIX read()
528 * @size: number of bytes to read
529 * @off: offset (not used)
530 * @fi: fuse_file_info (not used)
532 * Depending on the current state of the transfer interface (read/write)
533 * return either the results of TPM commands or a data of a TPM state blob.
535 static void ptm_read(fuse_req_t req
, size_t size
, off_t off
,
536 struct fuse_file_info
*fi
)
538 switch (tx_state
.state
) {
539 case TX_STATE_RW_COMMAND
:
540 ptm_read_result(req
, size
);
542 case TX_STATE_SET_STATE_BLOB
:
543 fuse_reply_err(req
, EIO
);
544 tx_state
.state
= TX_STATE_RW_COMMAND
;
546 case TX_STATE_GET_STATE_BLOB
:
547 ptm_read_stateblob(req
, size
);
552 /*************************read/write stateblob support ***********************/
555 * ptm_set_stateblob_append: Append a piece of TPM state blob and transfer to TPM
557 * blobtype: the type of blob
558 * data: the data to append
559 * length: length of the data
560 * is_encrypted: whether the blob is encrypted
561 * is_last: whether this is the last part of the TPM state blob; if it is, the TPM
562 * state blob will then be transferred to the TPM
565 ptm_set_stateblob_append(uint32_t blobtype
,
566 const unsigned char *data
, uint32_t length
,
567 bool is_encrypted
, bool is_last
)
570 static struct stateblob stateblob
;
573 if (stateblob
.type
!= blobtype
) {
574 /* new blob; clear old data */
575 free(stateblob
.data
);
576 stateblob
.data
= NULL
;
577 stateblob
.length
= 0;
578 stateblob
.type
= blobtype
;
579 stateblob
.is_encrypted
= is_encrypted
;
582 * on the first call for a new state blob we allow 0 bytes to be written
583 * this allows the user to transfer via write()
590 tmp
= realloc(stateblob
.data
, stateblob
.length
+ length
);
592 logprintf(STDERR_FILENO
,
593 "Could not allocate %u bytes.\n", stateblob
.length
+ length
);
595 free(stateblob
.data
);
596 stateblob
.data
= NULL
;
597 stateblob
.length
= 0;
602 stateblob
.data
= tmp
;
604 memcpy(&stateblob
.data
[stateblob
.length
], data
, length
);
605 stateblob
.length
+= length
;
608 /* full packet -- expecting more data */
612 res
= SWTPM_NVRAM_SetStateBlob(stateblob
.data
,
614 stateblob
.is_encrypted
,
618 logprintf(STDERR_FILENO
,
619 "Deserialized state type %d (%s), length=%d, res=%d\n",
620 blobtype
, tpmlib_get_blobname(blobtype
),
621 stateblob
.length
, res
);
623 free(stateblob
.data
);
624 stateblob
.data
= NULL
;
625 stateblob
.length
= 0;
628 /* transfer of blob is complete */
629 tx_state
.state
= TX_STATE_RW_COMMAND
;
635 * ptm_set_stateblob: set part of a TPM state blob
638 * pss: ptm_setstate provided via ioctl()
641 ptm_set_stateblob(fuse_req_t req
, ptm_setstate
*pss
)
644 TPM_BOOL is_encrypted
=
645 ((pss
->u
.req
.state_flags
& PTM_STATE_FLAG_ENCRYPTED
) != 0);
646 bool is_last
= (sizeof(pss
->u
.req
.data
) != pss
->u
.req
.length
);
648 if (pss
->u
.req
.length
> sizeof(pss
->u
.req
.data
)) {
649 res
= TPM_BAD_PARAMETER
;
653 /* transfer of blob initiated */
654 tx_state
.state
= TX_STATE_SET_STATE_BLOB
;
655 tx_state
.blobtype
= pss
->u
.req
.type
;
656 tx_state
.blob_is_encrypted
= is_encrypted
;
659 res
= ptm_set_stateblob_append(pss
->u
.req
.type
,
666 tx_state
.state
= TX_STATE_RW_COMMAND
;
669 pss
->u
.resp
.tpm_result
= res
;
671 fuse_reply_ioctl(req
, 0, pss
, sizeof(*pss
));
675 * ptm_get_stateblob_part: get part of a state blob
677 * @blobtype: the type of blob to get
678 * @buffer: the buffer this function will write the blob into
679 * @buffer_size: the size of the buffer
680 * @offset: the offset into the state blob
681 * @copied: pointer to int to indicate the number of bytes that were copied
682 * @is_encryped: returns whether the state blob is encrypted
685 ptm_get_stateblob_part(uint32_t blobtype
,
686 unsigned char *buffer
, size_t buffer_size
,
687 uint32_t offset
, uint32_t *copied
,
688 TPM_BOOL decrypt
, TPM_BOOL
*is_encrypted
)
692 if (!cached_stateblob_is_loaded(blobtype
, decrypt
)) {
693 res
= cached_stateblob_load(blobtype
, decrypt
);
697 cached_stateblob_copy(buffer
, buffer_size
,
698 offset
, copied
, is_encrypted
);
705 * ptm_get_stateblob: Get the state blob from the TPM using ioctl()
708 ptm_get_stateblob(fuse_req_t req
, ptm_getstate
*pgs
)
711 uint32_t blobtype
= pgs
->u
.req
.type
;
713 ((pgs
->u
.req
.state_flags
& PTM_STATE_FLAG_DECRYPTED
) != 0);
714 TPM_BOOL is_encrypted
= FALSE
;
716 uint32_t offset
= pgs
->u
.req
.offset
;
719 res
= ptm_get_stateblob_part(blobtype
,
720 pgs
->u
.resp
.data
, sizeof(pgs
->u
.resp
.data
),
721 pgs
->u
.req
.offset
, &copied
,
722 decrypt
, &is_encrypted
);
724 totlength
= cached_stateblob_get_bloblength();
726 pgs
->u
.resp
.state_flags
= 0;
728 pgs
->u
.resp
.state_flags
|= PTM_STATE_FLAG_ENCRYPTED
;
730 pgs
->u
.resp
.length
= copied
;
731 pgs
->u
.resp
.totlength
= totlength
;
732 pgs
->u
.resp
.tpm_result
= res
;
733 logprintf(STDERR_FILENO
,
734 "Serialized state type %d, length=%d, totlength=%d, res=%d\n",
735 blobtype
, copied
, totlength
, res
);
738 if (offset
+ copied
< totlength
) {
739 /* last byte was not copied */
740 tx_state
.state
= TX_STATE_GET_STATE_BLOB
;
741 tx_state
.blobtype
= pgs
->u
.req
.type
;
742 tx_state
.blob_is_encrypted
= is_encrypted
;
743 tx_state
.offset
= copied
;
745 /* last byte was copied */
746 tx_state
.state
= TX_STATE_RW_COMMAND
;
750 tx_state
.state
= TX_STATE_RW_COMMAND
;
753 fuse_reply_ioctl(req
, 0, pgs
, sizeof(pgs
->u
.resp
));
756 /*********************************** write() support *************************/
759 * ptm_write_stateblob: Write the state blob using the write() interface
761 * @req: the fuse_req_t
762 * @buf: the buffer with the data
763 * @size: the number of bytes in the buffer
765 * The data are appended to an existing buffer that was created with the
768 static void ptm_write_stateblob(fuse_req_t req
, const char *buf
, size_t size
)
772 res
= ptm_set_stateblob_append(tx_state
.blobtype
,
773 (unsigned char *)buf
, size
,
774 tx_state
.blob_is_encrypted
,
777 tx_state
.state
= TX_STATE_RW_COMMAND
;
778 fuse_reply_err(req
, EIO
);
780 fuse_reply_write(req
, size
);
785 * ptm_write_cmd: User writing a TPM command
788 * buf: the buffer containing the TPM command
789 * size: the size of the buffer
790 * tpmversion: the version of the TPM
792 static void ptm_write_cmd(fuse_req_t req
, const char *buf
, size_t size
,
793 TPMLIB_TPMVersion l_tpmversion
)
798 /* prevent other threads from writing or doing ioctls */
799 g_mutex_lock(FILE_OPS_LOCK
);
802 /* ensure that we only ever work on one TPM command */
803 if (worker_thread_is_busy()) {
804 fuse_reply_err(req
, EBUSY
);
808 if (ptm_req_len
> TPM_REQ_MAX
)
809 ptm_req_len
= TPM_REQ_MAX
;
811 /* process SetLocality command, if */
812 tpmlib_process(&ptm_response
, &ptm_res_len
, &ptm_res_tot
,
813 (unsigned char *)buf
, ptm_req_len
,
814 locality_flags
, &locality
, tpmversion
);
818 if (tpmlib_is_request_cancelable(l_tpmversion
,
819 (const unsigned char*)buf
,
821 /* have command processed by thread pool */
822 memcpy(ptm_request
, buf
, ptm_req_len
);
824 msg
.type
= MESSAGE_TPM_CMD
;
826 worker_thread_mark_busy();
828 g_thread_pool_push(pool
, &msg
, NULL
);
830 /* direct processing */
831 TPMLIB_Process(&ptm_response
, &ptm_res_len
, &ptm_res_tot
,
832 (unsigned char *)buf
, ptm_req_len
);
835 /* TPM not initialized; return error */
836 ptm_write_fatal_error_response(l_tpmversion
);
840 fuse_reply_write(req
, ptm_req_len
);
843 g_mutex_unlock(FILE_OPS_LOCK
);
849 * ptm_write: low-level write() interface; calls approriate function depending
850 * on what is being transferred using the write()
852 static void ptm_write(fuse_req_t req
, const char *buf
, size_t size
,
853 off_t off
, struct fuse_file_info
*fi
)
855 switch (tx_state
.state
) {
856 case TX_STATE_RW_COMMAND
:
857 ptm_write_cmd(req
, buf
, size
, tpmversion
);
859 case TX_STATE_GET_STATE_BLOB
:
860 fuse_reply_err(req
, EIO
);
861 tx_state
.state
= TX_STATE_RW_COMMAND
;
863 case TX_STATE_SET_STATE_BLOB
:
864 ptm_write_stateblob(req
, buf
, size
);
870 * ptm_open: interface to POSIX open()
872 static void ptm_open(fuse_req_t req
, struct fuse_file_info
*fi
)
874 tx_state
.state
= TX_STATE_RW_COMMAND
;
876 fuse_reply_open(req
, fi
);
880 * ptm_ioctl : ioctl execution
882 * req: the fuse_req_t used to send response with
883 * cmd: the ioctl request code
884 * arg: the pointer the application used for calling the ioctl (3rd param)
886 * flags: some flags provided by fuse
887 * in_buf: the copy of the input buffer
888 * in_bufsz: size of the input buffer; provided by fuse and has size of
890 * out_bufsz: size of the output buffer; provided by fuse and has size of
893 static void ptm_ioctl(fuse_req_t req
, int cmd
, void *arg
,
894 struct fuse_file_info
*fi
, unsigned flags
,
895 const void *in_buf
, size_t in_bufsz
, size_t out_bufsz
)
897 TPM_RESULT res
= TPM_FAIL
;
898 bool exit_prg
= FALSE
;
900 TPM_MODIFIER_INDICATOR orig_locality
;
902 /* some commands have to wait until the worker thread is done */
904 case PTM_GET_CAPABILITY
:
905 case PTM_SET_LOCALITY
:
906 case PTM_CANCEL_TPM_CMD
:
908 case PTM_SET_BUFFERSIZE
:
909 /* no need to wait */
913 case PTM_GET_TPMESTABLISHED
:
914 case PTM_RESET_TPMESTABLISHED
:
918 case PTM_STORE_VOLATILE
:
919 case PTM_GET_STATEBLOB
:
920 case PTM_SET_STATEBLOB
:
922 worker_thread_wait_done();
926 /* prevent other threads from writing or doing ioctls */
927 g_mutex_lock(FILE_OPS_LOCK
);
930 case PTM_GET_CAPABILITY
:
931 if (out_bufsz
!= sizeof(ptm_cap
)) {
932 struct iovec iov
= { arg
, sizeof(uint8_t) };
933 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
936 switch (tpmversion
) {
937 case TPMLIB_TPM_VERSION_2
:
938 ptm_caps
= PTM_CAP_INIT
| PTM_CAP_SHUTDOWN
939 | PTM_CAP_GET_TPMESTABLISHED
940 | PTM_CAP_SET_LOCALITY
942 | PTM_CAP_CANCEL_TPM_CMD
943 | PTM_CAP_STORE_VOLATILE
944 | PTM_CAP_RESET_TPMESTABLISHED
945 | PTM_CAP_GET_STATEBLOB
946 | PTM_CAP_SET_STATEBLOB
949 | PTM_CAP_SET_BUFFERSIZE
;
951 case TPMLIB_TPM_VERSION_1_2
:
952 ptm_caps
= PTM_CAP_INIT
| PTM_CAP_SHUTDOWN
953 | PTM_CAP_GET_TPMESTABLISHED
954 | PTM_CAP_SET_LOCALITY
956 | PTM_CAP_CANCEL_TPM_CMD
957 | PTM_CAP_STORE_VOLATILE
958 | PTM_CAP_RESET_TPMESTABLISHED
959 | PTM_CAP_GET_STATEBLOB
960 | PTM_CAP_SET_STATEBLOB
963 | PTM_CAP_SET_BUFFERSIZE
;
966 fuse_reply_ioctl(req
, 0, &ptm_caps
, sizeof(ptm_caps
));
971 if (in_bufsz
!= sizeof(ptm_init
)) {
972 struct iovec iov
= { arg
, sizeof(uint8_t) };
973 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
975 init_p
= (ptm_init
*)in_buf
;
982 if (tpm_start(init_p
->u
.req
.init_flags
, tpmversion
) < 0) {
984 logprintf(STDERR_FILENO
,
985 "Error: Could not initialize the TPM.\n");
990 init_p
->u
.resp
.tpm_result
= res
;
991 fuse_reply_ioctl(req
, 0, init_p
, sizeof(*init_p
));
1001 tpm_running
= false;
1004 ptm_response
= NULL
;
1006 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1011 worker_thread_end();
1017 ptm_response
= NULL
;
1019 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1024 case PTM_GET_TPMESTABLISHED
:
1026 goto error_not_running
;
1028 if (out_bufsz
!= sizeof(ptm_est
)) {
1029 struct iovec iov
= { arg
, sizeof(uint8_t) };
1030 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1033 te
.u
.resp
.tpm_result
= TPM_IO_TpmEstablished_Get(&te
.u
.resp
.bit
);
1034 fuse_reply_ioctl(req
, 0, &te
, sizeof(te
));
1038 case PTM_RESET_TPMESTABLISHED
:
1040 goto error_not_running
;
1042 if (in_bufsz
!= sizeof(ptm_reset_est
)) {
1043 struct iovec iov
= { arg
, sizeof(uint32_t) };
1044 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1046 ptm_reset_est
*re
= (ptm_reset_est
*)in_buf
;
1047 if (re
->u
.req
.loc
> 4) {
1048 res
= TPM_BAD_LOCALITY
;
1050 /* set locality and reset flag in one command */
1051 orig_locality
= locality
;
1052 locality
= re
->u
.req
.loc
;
1054 res
= TPM_IO_TpmEstablished_Reset();
1056 locality
= orig_locality
;
1057 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1062 case PTM_SET_LOCALITY
:
1063 if (in_bufsz
!= sizeof(ptm_loc
)) {
1064 struct iovec iov
= { arg
, sizeof(uint32_t) };
1065 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1067 ptm_loc
*l
= (ptm_loc
*)in_buf
;
1068 if (l
->u
.req
.loc
> 4 ||
1069 (l
->u
.req
.loc
== 4 &&
1070 locality_flags
& LOCALITY_FLAG_REJECT_LOCALITY_4
)) {
1071 res
= TPM_BAD_LOCALITY
;
1074 locality
= l
->u
.req
.loc
;
1076 l
->u
.resp
.tpm_result
= res
;
1077 fuse_reply_ioctl(req
, 0, l
, sizeof(*l
));
1081 case PTM_HASH_START
:
1083 goto error_not_running
;
1085 res
= TPM_IO_Hash_Start();
1086 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1091 goto error_not_running
;
1093 if (in_bufsz
!= sizeof(ptm_hdata
)) {
1094 struct iovec iov
= { arg
, sizeof(uint32_t) };
1095 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1097 ptm_hdata
*data
= (ptm_hdata
*)in_buf
;
1098 if (data
->u
.req
.length
<= sizeof(data
->u
.req
.data
)) {
1099 res
= TPM_IO_Hash_Data(data
->u
.req
.data
,
1100 data
->u
.req
.length
);
1104 data
->u
.resp
.tpm_result
= res
;
1105 fuse_reply_ioctl(req
, 0, data
, sizeof(*data
));
1111 goto error_not_running
;
1113 res
= TPM_IO_Hash_End();
1114 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1117 case PTM_CANCEL_TPM_CMD
:
1119 goto error_not_running
;
1121 /* for cancellation to work, the TPM would have to
1122 * execute in another thread that polls on a cancel
1125 res
= TPMLIB_CancelCommand();
1126 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1129 case PTM_STORE_VOLATILE
:
1131 goto error_not_running
;
1133 res
= SWTPM_NVRAM_Store_Volatile();
1134 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1136 cached_stateblob_free();
1139 case PTM_GET_STATEBLOB
:
1141 goto error_not_running
;
1143 if (in_bufsz
!= sizeof(ptm_getstate
)) {
1144 struct iovec iov
= { arg
, sizeof(uint32_t) };
1145 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1147 ptm_get_stateblob(req
, (ptm_getstate
*)in_buf
);
1151 case PTM_SET_STATEBLOB
:
1155 /* tpm state dir must be set */
1158 if (in_bufsz
!= sizeof(ptm_setstate
)) {
1159 struct iovec iov
= { arg
, sizeof(uint32_t) };
1160 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1162 ptm_set_stateblob(req
, (ptm_setstate
*)in_buf
);
1166 case PTM_GET_CONFIG
:
1167 if (out_bufsz
!= sizeof(ptm_getconfig
)) {
1168 struct iovec iov
= { arg
, sizeof(uint32_t) };
1169 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1172 pgs
.u
.resp
.tpm_result
= 0;
1173 pgs
.u
.resp
.flags
= 0;
1174 if (SWTPM_NVRAM_Has_FileKey())
1175 pgs
.u
.resp
.flags
|= PTM_CONFIG_FLAG_FILE_KEY
;
1176 if (SWTPM_NVRAM_Has_MigrationKey())
1177 pgs
.u
.resp
.flags
|= PTM_CONFIG_FLAG_MIGRATION_KEY
;
1178 fuse_reply_ioctl(req
, 0, &pgs
, sizeof(pgs
));
1182 case PTM_SET_BUFFERSIZE
:
1183 if (out_bufsz
!= sizeof(ptm_setbuffersize
)) {
1184 struct iovec iov
= { arg
, sizeof(uint32_t) };
1185 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1187 ptm_setbuffersize
*in_psbs
= (ptm_setbuffersize
*)in_buf
;
1188 ptm_setbuffersize out_psbs
;
1189 uint32_t buffersize
, minsize
, maxsize
;
1191 buffersize
= in_psbs
->u
.req
.buffersize
;
1193 if (buffersize
> 0 && tpm_running
)
1196 buffersize
= TPMLIB_SetBufferSize(buffersize
,
1200 out_psbs
.u
.resp
.tpm_result
= TPM_SUCCESS
;
1201 out_psbs
.u
.resp
.buffersize
= buffersize
;
1202 out_psbs
.u
.resp
.minsize
= minsize
;
1203 out_psbs
.u
.resp
.maxsize
= maxsize
;
1204 fuse_reply_ioctl(req
, 0, &out_psbs
, sizeof(out_psbs
));
1209 if (out_bufsz
!= sizeof(ptm_getinfo
)) {
1210 struct iovec iov
= { arg
, sizeof(uint32_t) };
1211 fuse_reply_ioctl_retry(req
, &iov
, 1, NULL
, 0);
1213 ptm_getinfo
*in_pgi
= (ptm_getinfo
*)in_buf
;
1214 ptm_getinfo out_pgi
;
1216 uint32_t length
, offset
;
1218 info_data
= TPMLIB_GetInfo(in_pgi
->u
.req
.flags
);
1222 offset
= in_pgi
->u
.req
.offset
;
1223 if (offset
>= strlen(info_data
)) {
1225 goto error_bad_input
;
1228 length
= min(strlen(info_data
) + 1 - offset
,
1229 sizeof(out_pgi
.u
.resp
.buffer
));
1231 out_pgi
.u
.resp
.tpm_result
= 0;
1232 out_pgi
.u
.resp
.totlength
= strlen(info_data
) + 1;
1233 out_pgi
.u
.resp
.length
= length
;
1234 /* client has to collect whole string in case buffer is too small */
1235 memcpy(out_pgi
.u
.resp
.buffer
, &info_data
[offset
], length
);
1238 fuse_reply_ioctl(req
, 0, &out_pgi
, sizeof(out_pgi
));
1243 fuse_reply_err(req
, EINVAL
);
1247 g_mutex_unlock(FILE_OPS_LOCK
);
1250 logprintf(STDOUT_FILENO
, "CUSE TPM is shutting down.\n");
1258 res
= TPM_BAD_PARAMETER
;
1259 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1265 res
= TPM_BAD_ORDINAL
;
1266 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1272 fuse_reply_ioctl(req
, 0, &res
, sizeof(res
));
1277 static void ptm_init_done(void *userdata
)
1279 struct cuse_param
*param
= userdata
;
1282 /* at this point the entry in /dev/ is available */
1283 if (pidfile_write(getpid()) < 0) {
1289 ret
= change_process_owner(param
->runas
);
1297 static void ptm_cleanup(void)
1302 static const struct cuse_lowlevel_ops clops
= {
1307 .init_done
= ptm_init_done
,
1310 #ifndef HAVE_SWTPM_CUSE_MAIN
1311 int main(int argc
, char **argv
)
1313 const char *prgname
= argv
[0];
1314 const char *iface
= "";
1316 int swtpm_cuse_main(int argc
, char **argv
, const char *prgname
, const char *iface
)
1319 int opt
, longindex
= 0;
1320 static struct option longopts
[] = {
1321 {"maj" , required_argument
, 0, 'M'},
1322 {"min" , required_argument
, 0, 'm'},
1323 {"name" , required_argument
, 0, 'n'},
1324 {"runas" , required_argument
, 0, 'r'},
1325 {"log" , required_argument
, 0, 'l'},
1326 {"locality" , required_argument
, 0, 'L'},
1327 {"key" , required_argument
, 0, 'k'},
1328 {"migration-key" , required_argument
, 0, 'K'},
1329 {"pid" , required_argument
, 0, 'p'},
1330 {"tpmstate" , required_argument
, 0, 's'},
1331 {"tpm2" , no_argument
, 0, '2'},
1332 {"help" , no_argument
, 0, 'h'},
1333 {"version" , no_argument
, 0, 'v'},
1336 struct cuse_info cinfo
;
1337 struct cuse_param param
;
1338 const char *devname
= NULL
;
1339 char *cinfo_argv
[1];
1341 struct passwd
*passwd
;
1344 char path
[PATH_MAX
];
1347 memset(&cinfo
, 0, sizeof(cinfo
));
1348 memset(¶m
, 0, sizeof(param
));
1350 log_set_prefix("swtpm: ");
1352 tpmversion
= TPMLIB_TPM_VERSION_1_2
;
1355 opt
= getopt_long(argc
, argv
, "M:m:n:r:hv", longopts
, &longindex
);
1361 case 'M': /* major */
1362 if (sscanf(optarg
, "%u", &num
) != 1) {
1363 logprintf(STDERR_FILENO
, "Could not parse major number\n");
1367 logprintf(STDERR_FILENO
,
1368 "Major number outside valid range [0 - 65535]\n");
1371 cinfo
.dev_major
= num
;
1373 case 'm': /* minor */
1374 if (sscanf(optarg
, "%u", &num
) != 1) {
1375 logprintf(STDERR_FILENO
, "Could not parse major number\n");
1379 logprintf(STDERR_FILENO
,
1380 "Major number outside valid range [0 - 65535]\n");
1383 cinfo
.dev_minor
= num
;
1385 case 'n': /* name */
1386 if (!cinfo
.dev_info_argc
) {
1387 cinfo_argv
[0] = calloc(1, strlen("DEVNAME=") + strlen(optarg
) + 1);
1388 if (!cinfo_argv
[0]) {
1389 logprintf(STDERR_FILENO
, "Out of memory\n");
1394 strcpy(cinfo_argv
[0], "DEVNAME=");
1395 strcat(cinfo_argv
[0], optarg
);
1397 cinfo
.dev_info_argc
= 1;
1398 cinfo
.dev_info_argv
= (const char **)cinfo_argv
;
1401 case 'r': /* runas */
1402 param
.runas
= optarg
;
1405 param
.logging
= optarg
;
1408 param
.keydata
= optarg
;
1410 case 'K': /* migration-key */
1411 param
.migkeydata
= optarg
;
1414 param
.piddata
= optarg
;
1416 case 's': /* tpmstate */
1417 param
.tpmstatedata
= optarg
;
1420 param
.localitydata
= optarg
;
1423 tpmversion
= TPMLIB_TPM_VERSION_2
;
1425 case 'h': /* help */
1426 fprintf(stdout
, usage
, prgname
, iface
);
1428 case 'v': /* version */
1429 fprintf(stdout
, "TPM emulator CUSE interface version %d.%d.%d, "
1430 "Copyright (c) 2014-2015 IBM Corp.\n",
1438 if (optind
< argc
) {
1439 logprintf(STDERR_FILENO
,
1440 "Unknown parameter '%s'\n", argv
[optind
]);
1441 return EXIT_FAILURE
;
1445 * choose the TPM version early so that getting/setting
1446 * buffer size works.
1448 if (TPMLIB_ChooseTPMVersion(tpmversion
) != TPM_SUCCESS
) {
1449 logprintf(STDERR_FILENO
,
1450 "Error: Could not choose TPM version.\n");
1451 return EXIT_FAILURE
;
1454 SWTPM_NVRAM_Set_TPMVersion(tpmversion
);
1456 if (!cinfo
.dev_info_argv
) {
1457 logprintf(STDERR_FILENO
, "Error: device name missing\n");
1461 if (handle_log_options(param
.logging
) < 0 ||
1462 handle_key_options(param
.keydata
) < 0 ||
1463 handle_migration_key_options(param
.migkeydata
) < 0 ||
1464 handle_pid_options(param
.piddata
) < 0 ||
1465 handle_tpmstate_options(param
.tpmstatedata
) < 0 ||
1466 handle_locality_options(param
.localitydata
, &locality_flags
) < 0)
1470 logprintf(STDERR_FILENO
, "Error: Unable to setuid root. uid = %d, "
1471 "euid = %d, gid = %d\n", getuid(), geteuid(), getgid());
1476 if (!(passwd
= getpwnam(param
.runas
))) {
1477 logprintf(STDERR_FILENO
, "User '%s' does not exist\n",
1483 tpmdir
= tpmstate_get_dir();
1484 if (tpmdir
== NULL
) {
1485 logprintf(STDERR_FILENO
,
1486 "Error: No TPM state directory is defined; "
1487 "TPM_PATH is not set\n");
1491 n
= snprintf(path
, sizeof(path
), "/dev/%s", devname
);
1493 logprintf(STDERR_FILENO
,
1494 "Error: Could not create device file name\n");
1497 if (n
>= (int)sizeof(path
)) {
1498 logprintf(STDERR_FILENO
,
1499 "Error: Buffer too small to create device file name\n");
1503 tpmfd
= open(path
, O_RDWR
);
1506 logprintf(STDERR_FILENO
,
1507 "Error: A device '%s' already exists.\n",
1512 if (tpmlib_register_callbacks(&cbs
) != TPM_SUCCESS
)
1515 worker_thread_init();
1517 #if GLIB_MINOR_VERSION >= 32
1518 g_mutex_init(FILE_OPS_LOCK
);
1520 FILE_OPS_LOCK
= g_mutex_new();
1523 ret
= cuse_lowlevel_main(1, argv
, &cinfo
, &clops
, ¶m
);