-
Notifications
You must be signed in to change notification settings - Fork 13
/
tpmproxy.c
1000 lines (914 loc) · 29.9 KB
/
tpmproxy.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************************/
/* */
/* Windows 10 and Linux TPM Proxy */
/* Written by Ken Goldman */
/* IBM Thomas J. Watson Research Center */
/* */
/* (c) Copyright IBM Corporation 2006 - 2021. */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions are */
/* met: */
/* */
/* Redistributions of source code must retain the above copyright notice, */
/* this list of conditions and the following disclaimer. */
/* */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in the */
/* documentation and/or other materials provided with the distribution. */
/* */
/* Neither the names of the IBM Corporation nor the names of its */
/* contributors may be used to endorse or promote products derived from */
/* this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/********************************************************************************/
/*
Use this proxy when using the TSS command line utilities. It keeps the connection to
the TPM device driver open. This prevents a resource manager from flushing resources
after each utiity exits. It also permits remote access to a HW TPM.
The server type (mssim or raw) should agree with the TSS configuration. mssim wrapes the packets
in the MS simulator bytes. raw does not.
For the mssim format, the server socket remains open until the TPM_SESSION_END preamble is
received. Then, the proxy loops back and reopens the connection for the next TSS client side
open.
Windows: Link with:
tbs.lib
ws2_32.lib
*/
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <errno.h>
#include <ibmtss/tss.h>
#include <ibmtss/tsstransmit.h>
#ifdef TPM_WINDOWS
#include <windows.h>
#include <specstrings.h>
#include <tbs.h>
#define SOCKET_FD SOCKET
#define SOCKLEN_T INT
#endif /* TPM_WINDOWS */
#ifdef TPM_POSIX /* Posix sockets */
#include <unistd.h>
#define SOCKET_FD int
#define SOCKLEN_T socklen_t
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#endif /* TPM_POSIX */
#define LOAD32(buffer,offset) ( ntohl(*(uint32_t *)&(buffer)[(offset)]) )
#ifndef SSIZE_MAX
#define SSIZE_MAX INT_MAX
#endif
/* local constants */
#define ERROR_CODE (TPM_RC)-1
#define EOF_CODE (TPM_RC)-2
#define DEFAULT_PORT 2321
#define PACKET_SIZE 4096
#define TRACE_SIZE (PACKET_SIZE * 4)
#define SERVER_TYPE_MSSIM 0
#define SERVER_TYPE_RAW 1
#define TPM_SEND_COMMAND 8 /* simulator command preamble */
#define TPM_SESSION_END 20
/* local prototypes */
void printUsage(void);
long getArgs(short *port,
int *verbose,
char **logFileName,
int argc,
char **argv);
void logAll(const char *message, unsigned long length, const unsigned char* buff);
TPM_RC socketInit(SOCKET_FD *sock_fd, short port);
TPM_RC socketConnect(SOCKET_FD *accept_fd,
SOCKET_FD sock_fd,
short port);
TPM_RC socketRead(SOCKET_FD accept_fd,
uint32_t *commandType,
char *buffer,
uint32_t *bufferLength,
size_t bufferSize);
TPM_RC socketReadBytes(SOCKET_FD accept_fd,
char *buffer,
size_t nbytes);
TPM_RC socketWrite(SOCKET_FD accept_fd,
const char *buffer,
size_t buffer_length);
TPM_RC socketDisconnect(SOCKET_FD accept_fd);
#ifdef TPM_WINDOWS
void TPM_HandleWsaStartupError(const char *prefix,
int irc);
void TPM_HandleWsaError(const char *prefix);
void TPM_GetWsaStartupError(int status,
const char **error_string);
void TPM_GetWsaError(const char **error_string);
void TPM_GetTBSError(const char *prefix,
TBS_RESULT rc);
#endif
/* global variable for trace logging */
int verbose; /* verbose debug tracing */
char *logFilename; /* trace log file name */
char logMsg[TRACE_SIZE]; /* since it's big, put it here rather than on the stack */
/* global socket server format type */
int serverType = SERVER_TYPE_MSSIM; /* default MS simulator format */
#define false 0
#define true 1
int main(int argc, char** argv)
{
TPM_RC rc = 0;
TPM_RC trc = 0;
TSS_CONTEXT *tssContext = NULL; /* TPM connection */
time_t start_time;
SOCKET_FD sock_fd; /* server socket */
SOCKET_FD accept_fd; /* server accept socket for a packet */
int socketOpened = FALSE;
#if 0
TBS_HCONTEXT hContext = 0;
TBS_CONTEXT_PARAMS2 contextParams;
#endif
/* TPM command and response */
BYTE command[PACKET_SIZE];
uint32_t commandLength;
BYTE response[PACKET_SIZE];
uint32_t responseLength;
/* command line arguments */
short port; /* TCPIP server port */
/* command line argument defaults */
port = DEFAULT_PORT;
logFilename = NULL;
verbose = FALSE;
/* initialization */
setvbuf(stdout, 0, _IONBF, 0); /* output may be going through pipe */
start_time = time(NULL);
/* get command line arguments */
if (rc == 0) {
rc = getArgs(&port, &verbose, &logFilename,
argc, argv);
}
if (rc == 0) {
if (verbose) printf("tpmproxy: start at %s", ctime(&start_time));
if (verbose) printf("tpmproxy: server type %s\n",
(serverType == SERVER_TYPE_MSSIM) ? "MS simulator" : "raw");
}
/* open / initialize server socket */
if (rc == 0) {
if (verbose) printf("Opening socket at port %hu\n", port);
rc = socketInit(&sock_fd, port);
if (rc != 0) {
printf("tpmproxy: socket open failed\n");
}
else {
socketOpened = TRUE;
}
}
/* prepare for the HW TPM connection */
if (rc == 0) {
rc = TSS_Create(&tssContext);
}
/* regardless of the env variables, the proxy connects to the device */
if (rc == 0) {
rc = TSS_SetProperty(tssContext, TPM_INTERFACE_TYPE, "dev");
}
/* outer loop, socket connect or reconnect */
while (rc == 0) {
uint32_t commandType = TPM_SEND_COMMAND; /* for first time through inner loop */
/* connect to the client application */
if (rc == 0) {
if (verbose) printf("Connecting on socket %hu\n", port);
rc = socketConnect(&accept_fd, sock_fd, port);
}
/* inner loop, read socket, send command, get response, write socket */
while ((rc == 0) && (commandType == TPM_SEND_COMMAND)) {
/* read a command from client */
if ((rc == 0) && (commandType == TPM_SEND_COMMAND)) {
rc = socketRead(accept_fd,
&commandType,
(char *)command, /* windows wants signed */
&commandLength,
sizeof(command));
}
if ((rc == 0) && (commandType == TPM_SEND_COMMAND)) {
logAll("Command", commandLength, command);
}
/* send command to TPM and receive response */
if ((rc == 0) && (commandType == TPM_SEND_COMMAND)) {
trc = TSS_Transmit(tssContext,
response, &responseLength,
command, commandLength,
NULL); /* message */
trc = trc; /* ignore TPM errors */
}
/* send response to client */
if ((rc == 0) && (commandType == TPM_SEND_COMMAND)) {
logAll("Response", responseLength, response);
rc = socketWrite(accept_fd,
(char *)response, /* windows wants signed char */
responseLength);
}
}
}
/* close socket */
if (socketOpened) {
socketDisconnect(sock_fd);
}
/* close TPM */
{
TPM_RC rc1 = TSS_Delete(tssContext);
if (rc == 0) {
rc = rc1;
}
}
if (verbose) printf("tpmproxy: exit rc %08x\n", rc);
return rc;
}
/*
All the socket code is basically a cut and paste from the TPM 1.2 tpm_io.c
*/
TPM_RC socketInit(SOCKET_FD *sock_fd, short port)
{
TPM_RC rc = 0;
int irc;
struct sockaddr_in serv_addr;
int opt;
#ifdef TPM_WINDOWS
WSADATA wsaData;
#endif
#ifdef TPM_WINDOWS
/* initiate use of the Windows Sockets DLL 2.0 */
if (rc == 0) {
if ((irc = WSAStartup(0x202,&wsaData)) != 0) { /* if not successful */
printf("socketInit: Error, WSAStartup()\n");
TPM_HandleWsaStartupError("socketInit:", irc);
rc = ERROR_CODE;
}
}
#endif
/* create a tcpip protocol socket */
if (rc == 0) {
/* if (verbose) printf(" socketInit: Port %hu\n", port); */
*sock_fd = socket(AF_INET, SOCK_STREAM, 0); /* tcpip socket */
if (*sock_fd == INVALID_SOCKET) {
printf("socketInit: Error, server socket()\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketInit:");
#endif
rc = ERROR_CODE;
}
}
if (rc == 0) {
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET; /* Internet socket */
serv_addr.sin_port = htons(port); /* host to network byte order for short */
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* host to network byte order for long */
opt = 1;
/* Set SO_REUSEADDR before calling bind() for servers that bind to a fixed port number. */
/* For boolean values, opt must be an int, but the setsockopt prototype is IMHO wrong.
It should take void *, but uses char *. Hence the type cast. */
irc = setsockopt(*sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));
if (irc == SOCKET_ERROR) {
printf("socketInit: Error, server setsockopt()\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketInit:");
#endif
socketDisconnect(*sock_fd);
rc = ERROR_CODE;
}
}
/* bind the (local) server port name to the socket */
if (rc == 0) {
irc = bind(*sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (irc == SOCKET_ERROR) {
printf("socketInit: Error, server bind()\n");
printf("socketInit: Is SW TPM listening on this port?\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketInit:");
#endif
socketDisconnect(*sock_fd);
rc = ERROR_CODE;
}
}
/* listen for a connection to the socket */
if (rc == 0) {
irc = listen(*sock_fd, SOMAXCONN);
if (irc == SOCKET_ERROR) {
printf("socketInit: Error, server listen()\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketInit:");
#endif
socketDisconnect(*sock_fd);
rc = ERROR_CODE;
}
}
#ifdef TPM_WINDOWS
if (rc != 0) {
WSACleanup();
}
#endif
return rc;
}
TPM_RC socketConnect(SOCKET_FD *accept_fd,
SOCKET_FD sock_fd,
short port)
{
TPM_RC rc = 0;
SOCKLEN_T cli_len;
struct sockaddr_in cli_addr; /* Internet version of sockaddr */
/* accept a connection */
if (rc == 0) {
cli_len = sizeof(cli_addr);
/* block until connection from client */
port = port;
/* printf(" socketConnect: Waiting for connection on port %hu ...\n", port); */
*accept_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &cli_len);
if (*accept_fd == SOCKET_ERROR) {
printf("socketConnect: Error, accept()\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketConnect: ");
#endif
socketDisconnect(sock_fd);
#ifdef TPM_WINDOWS
WSACleanup();
#endif
rc = ERROR_CODE;
}
}
return rc;
}
/* socketRead() reads a TPM command packet from the host
Puts the result in 'buffer' up to 'bufferSize' bytes.
On success, if commandType is TPM_SEND_COMMAND, the number of bytes in the buffer is equal to
'bufferLength' bytes. If commandType is TPM_SESSION_END, return it. The loop should restart.
This function is intended to be platform independent.
*/
TPM_RC socketRead(SOCKET_FD accept_fd, /* read/write file descriptor */
uint32_t *commandType,
char *buffer, /* output: command stream */
uint32_t *bufferLength, /* output: command stream length */
size_t bufferSize) /* input: max size of output buffer */
{
TPM_RC rc = 0;
int done = false;
uint32_t headerSize; /* minimum required bytes in command through paramSize */
uint32_t paramSize; /* from command stream */
uint32_t commandTypeNbo; /* MS simulator format preamble */
uint8_t locality; /* MS simulator format preamble */
uint32_t lengthNbo; /* MS simulator format preamble */
/* if the MS simulator packet format */
if (serverType == SERVER_TYPE_MSSIM) {
/* read and check the command */
if (rc == 0) {
rc = socketReadBytes(accept_fd, (char *)&commandTypeNbo, sizeof(uint32_t));
}
if (rc == 0) {
*commandType = LOAD32(&commandTypeNbo, 0);
if (*commandType == TPM_SESSION_END) { /* client TSS termination request */
done = true;
}
else if (*commandType != TPM_SEND_COMMAND) {
printf("socketRead: Error, -mssim preamble is %08x not %08x\n",
*commandType, TPM_SEND_COMMAND);
rc = ERROR_CODE;
}
}
/* read and discard the locality */
if ((rc == 0) && !done) {
rc = socketReadBytes(accept_fd, (char *)&locality, sizeof(uint8_t));
}
/* read and discard the redundant length */
if ((rc == 0) && !done) {
rc = socketReadBytes(accept_fd, (char *)&lengthNbo, sizeof(uint32_t));
}
}
/* check that the buffer can at least fit the command through the paramSize */
if ((rc == 0) && !done) {
headerSize = sizeof(TPM_TAG) + sizeof(uint32_t);
if (bufferSize < headerSize) {
printf("socketRead: Error, buffer size %lu less than minimum %lu\n",
(unsigned long)bufferSize, (unsigned long)headerSize);
rc = ERROR_CODE;
}
}
/* read the command through the paramSize from the socket stream */
if ((rc == 0) && !done) {
rc = socketReadBytes(accept_fd, buffer, headerSize);
if ((serverType != SERVER_TYPE_MSSIM) &&
(rc == EOF_CODE)) {
/* if in raw mode and connection closed, signal to start a new connection */
*commandType = TPM_SESSION_END; /* client TSS termination request */
done = true;
rc = 0;
}
}
if ((rc == 0) && !done) {
/* extract the paramSize value, last field in header */
paramSize = LOAD32(buffer, headerSize - sizeof(uint32_t));
*bufferLength = headerSize + paramSize - (sizeof(TPM_TAG) + sizeof(uint32_t));
if (bufferSize < *bufferLength) {
printf("socketRead: Error, buffer size %lu is less than required %u\n",
(unsigned long)bufferSize, *bufferLength);
rc = ERROR_CODE;
}
}
/* read the rest of the command (already read tag and paramSize) */
if ((rc == 0) && !done) {
rc = socketReadBytes(accept_fd,
buffer + headerSize,
paramSize - (sizeof(TPM_TAG) + sizeof(uint32_t)));
}
return rc;
}
/* socketReadBytes() reads nbytes from accept_fd and puts them in buffer.
The buffer has already been checked for sufficient size.
*/
TPM_RC socketReadBytes(SOCKET_FD accept_fd, /* read/write file descriptor */
char *buffer,
size_t nbytes)
{
TPM_RC rc = 0;
int nread = 0;
size_t nleft = nbytes;
/* read() is unspecified with nbytes too large */
if (rc == 0) {
if (nleft > SSIZE_MAX) {
rc = ERROR_CODE;
}
}
while ((rc == 0) && (nleft > 0)) {
nread = recv(accept_fd, buffer, (int)nleft, 0);
if ((nread == SOCKET_ERROR) ||
(nread < 0)) { /* error */
printf("socketReadBytes: Error, read() error\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketReadBytes:");
#endif
socketDisconnect(accept_fd);
rc = ERROR_CODE;
}
else if (nread > 0) {
nleft -= nread;
buffer += nread;
}
else if (nread == 0) { /* EOF */
rc = EOF_CODE;
}
}
return rc;
}
/* socketWrite() writes buffer_length bytes from buffer to accept_fd.
In mmssim mode, it prepends the size and appends the acknowledgement.
*/
TPM_RC socketWrite(SOCKET_FD accept_fd, /* read/write file descriptor */
const char *buffer,
size_t buffer_length)
{
TPM_RC rc = 0;
int nwritten = 0;
/* write() is unspecified with buffer_length too large */
if (rc == 0) {
if (buffer_length > SSIZE_MAX) {
rc = ERROR_CODE;
}
}
/* if the MS simulator packet format */
if (serverType == SERVER_TYPE_MSSIM) {
/* prepend the leading size */
if (rc == 0) {
uint32_t bufferLengthNbo = htonl((uint32_t)buffer_length);
send(accept_fd, (const char *)&bufferLengthNbo, sizeof(uint32_t), 0);
}
}
/* test that connection is open to write */
if (rc == 0) {
if (accept_fd == SOCKET_ERROR) {
printf("socketWrite: Error, connection not open, fd %d\n",
(int)accept_fd);
rc = ERROR_CODE;
}
}
while ((rc == 0) && (buffer_length > 0)) {
nwritten = send(accept_fd, buffer, (int)buffer_length, 0);
if ((nwritten == SOCKET_ERROR) ||
(nwritten < 0)) {
printf("socketWrite: Error, send()\n");
#ifdef TPM_WINDOWS
TPM_HandleWsaError("socketWrite:"); /* report the error */
#endif
socketDisconnect(accept_fd);
rc = ERROR_CODE;
}
else {
buffer_length -= nwritten;
buffer += nwritten;
}
}
/* if the MS simulator packet format */
if (serverType == SERVER_TYPE_MSSIM) {
/* append the trailing acknowledgement */
if (rc == 0) {
uint32_t acknowledgement = 0;
send(accept_fd, (const char *)&acknowledgement, sizeof(uint32_t), 0);
}
}
return rc;
}
/* socketDisconnect() breaks the connection between the TPM server and the host client
*/
TPM_RC socketDisconnect(SOCKET_FD accept_fd)
{
TPM_RC rc = 0;
int irc;
/* close the connection to the client */
if (verbose) printf("Closing socket\n");
if (rc == 0) {
#ifdef TPM_WINDOWS
irc = closesocket(accept_fd);
#endif
#ifdef TPM_POSIX
irc = close(accept_fd);
#endif
if (irc == SOCKET_ERROR) {
printf("socketDisconnect: Error, closesocket()\n");
rc = ERROR_CODE;
}
}
return rc;
}
#ifdef TPM_WINDOWS
void TPM_HandleWsaStartupError(const char *prefix,
int irc)
{
const char *error_string;
TPM_GetWsaStartupError(irc, &error_string);
printf("%s %s\n", prefix, error_string);
return;
}
void TPM_HandleWsaError(const char *prefix)
{
const char *error_string;
TPM_GetWsaError(&error_string);
printf("%s %s\n", prefix, error_string);
return;
}
void TPM_GetWsaStartupError(int status,
const char **error_string)
{
/* convert WSAStartup status to more useful text. Copy the text to error_string */
switch(status) {
case WSASYSNOTREADY:
*error_string = "WSAStartup error: WSASYSNOTREADY underlying network subsystem not ready for "
"network communication";
break;
case WSAVERNOTSUPPORTED:
*error_string = "WSAStartup error: WSAVERNOTSUPPORTED version requested not provided by WinSock "
"implementation";
break;
case WSAEINPROGRESS:
*error_string = "WSAStartup error: WSAEINPROGRESS blocking WinSock 1.1 operation in progress";
break;
case WSAEPROCLIM:
*error_string = "WSAStartup error: WSAEPROCLIM Limit on number of tasks supported by WinSock "
"implementation has been reached";
break;
case WSAEFAULT:
*error_string = "WSAStartup error: WSAEFAULT lpWSAData is not a valid pointer";
break;
default:
*error_string = "WSAStartup error: return code unknown";
break;
}
return;
}
void TPM_GetWsaError(const char **error_string)
{
/* Use WSAGetLastError, and convert the resulting number
to more useful text. Copy the text to error_string */
int error;
error = WSAGetLastError();
switch(error) {
case WSANOTINITIALISED :
*error_string = "A successful WSAStartup must occur before using this function";
break;
case WSAENETDOWN :
*error_string = "The network subsystem or the associated service provider has failed";
break;
case WSAEAFNOSUPPORT :
*error_string = "The specified address family is not supported";
break;
case WSAEINPROGRESS :
*error_string = "A blocking Windows Sockets 1.1 call is in progress, "
"or the service provider is still processing a callback function";
break;
case WSAEMFILE:
*error_string = "No more socket descriptors are available";
break;
case WSAENOBUFS:
*error_string = "No buffer space is available";
break;
case WSAEPROTONOSUPPORT:
*error_string = "The specified protocol is not supported";
break;
case WSAEPROTOTYPE:
*error_string = "The specified protocol is the wrong type for this socket";
break;
case WSAESOCKTNOSUPPORT :
*error_string = "The specified socket type is not supported in this address family";
break;
case WSAEFAULT:
*error_string = "A parameter is too small, bad format, or bad value";
break;
case WSAEINVAL:
*error_string = "The socket has not been bound with bind, or listen not called";
break;
case WSAENETRESET:
*error_string = "The connection has been broken due to the remote host resetting";
break;
case WSAENOPROTOOPT:
*error_string = "The option is unknown or unsupported for the specified provider";
break;
case WSAENOTCONN:
*error_string = "Connection has been reset when SO_KEEPALIVE is set";
break;
case WSAENOTSOCK:
*error_string = "The descriptor is not a socket";
break;
case WSAEADDRINUSE:
*error_string = "The specified address is already in use";
break;
case WSAEISCONN:
*error_string = "The socket is already connected";
break;
case WSAEOPNOTSUPP:
*error_string = "The referenced socket is not of a type that supports the operation";
break;
case WSAEINTR:
*error_string = "The (blocking) call was canceled through WSACancelBlockingCall";
case WSAEWOULDBLOCK:
*error_string = "The socket is marked as nonblocking and no connections are present to be accepted";
break;
case WSAESHUTDOWN:
*error_string = "The socket has been shut down; it is not possible to recv or send on a socket "
"after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH";
break;
case WSAEMSGSIZE:
*error_string = "The message was too large to fit into the specified buffer and was truncated";
break;
case WSAECONNABORTED:
*error_string = "The virtual circuit was terminated due to a time-out or other failure. "
"The application should close the socket as it is no longer usable";
break;
case WSAETIMEDOUT:
*error_string = "The connection has been dropped because of a network failure or because "
"the peer system failed to respond";
break;
case WSAECONNRESET:
*error_string = "The virtual circuit was reset by the remote side executing a hard or abortive close. "
"The application should close the socket as it is no longer usable. On a UDP datagram "
"socket this error would indicate that a previous send operation resulted in an ICMP "
"Port Unreachable message";
break;
case WSAEACCES:
*error_string = "The requested address is a broadcast address, but the appropriate flag was not set";
break;
case WSAEHOSTUNREACH:
*error_string = "The remote host cannot be reached from this host at this time";
break;
default:
*error_string = "unknown error type\n";
break;
}
return;
}
void TPM_GetTBSError(const char *prefix,
TBS_RESULT rc)
{
const char *error_string;
switch (rc) {
/* error codes from the TBS html docs */
case TBS_SUCCESS:
error_string = "The function succeeded.";
break;
case TBS_E_INTERNAL_ERROR:
error_string = "An internal software error occurred.";
break;
case TBS_E_BAD_PARAMETER:
error_string = "One or more parameter values are not valid.";
break;
case TBS_E_INVALID_OUTPUT_POINTER:
error_string = "A specified output pointer is bad.";
break;
case TBS_E_INVALID_CONTEXT:
error_string = "The specified context handle does not refer to a valid context.";
break;
case TBS_E_INSUFFICIENT_BUFFER:
error_string = "The specified output buffer is too small.";
break;
case TBS_E_IOERROR:
error_string = "An error occurred while communicating with the TPM.";
break;
case TBS_E_INVALID_CONTEXT_PARAM:
error_string = "A context parameter that is not valid was passed when attempting to create a "
"TBS context.";
break;
case TBS_E_SERVICE_NOT_RUNNING:
error_string = "The TBS service is not running and could not be started.";
break;
case TBS_E_TOO_MANY_TBS_CONTEXTS:
error_string = "A new context could not be created because there are too many open contexts.";
break;
case TBS_E_TOO_MANY_RESOURCES:
error_string = "A new virtual resource could not be created because there are too many open "
"virtual resources.";
break;
case TBS_E_SERVICE_START_PENDING:
error_string = "The TBS service has been started but is not yet running.";
break;
case TBS_E_PPI_NOT_SUPPORTED:
error_string = "The physical presence interface is not supported.";
break;
case TBS_E_COMMAND_CANCELED:
error_string = "The command was canceled.";
break;
case TBS_E_BUFFER_TOO_LARGE:
error_string = "The input or output buffer is too large.";
break;
case TBS_E_TPM_NOT_FOUND:
error_string = "A compatible Trusted Platform Module (TPM) Security Device cannot be found "
"on this computer.";
break;
case TBS_E_SERVICE_DISABLED:
error_string = "The TBS service has been disabled.";
break;
case TBS_E_NO_EVENT_LOG:
error_string = "The TBS event log is not available.";
break;
case TBS_E_ACCESS_DENIED:
error_string = "The caller does not have the appropriate rights to perform the requested operation.";
break;
case TBS_E_PROVISIONING_NOT_ALLOWED:
error_string = "The TPM provisioning action is not allowed by the specified flags.";
break;
case TBS_E_PPI_FUNCTION_UNSUPPORTED:
error_string = "The Physical Presence Interface of this firmware does not support the "
"requested method.";
break;
case TBS_E_OWNERAUTH_NOT_FOUND:
error_string = "The requested TPM OwnerAuth value was not found.";
break;
/* a few error codes from WinError.h */
case TPM_E_COMMAND_BLOCKED:
error_string = "The command was blocked.";
break;
default:
error_string = "unknown error type\n";
break;
}
printf("%s %s\n", prefix, error_string);
return;
}
#endif /* TPM_WINDOWS */
/* logging, tracing */
void logAll(const char *message, unsigned long length, const unsigned char* buff)
{
unsigned long i;
size_t nextChar = 0;
FILE *logFile; /* trace log file descriptor */
/* construct the log message, keep appending to the character string */
if (buff != NULL) {
nextChar += sprintf(logMsg + nextChar, "%s length %lu\n ", message, length);
for (i = 0 ; i < length ; i++) {
if (i && !( i % 16 )) {
nextChar += sprintf(logMsg + nextChar, "\n ");
}
nextChar += sprintf(logMsg + nextChar, "%.2X ",buff[i]);
}
nextChar += sprintf(logMsg + nextChar, "\n");
}
else {
nextChar += sprintf(logMsg + nextChar, "%s null\n", message);
}
if (verbose) printf("%s", logMsg);
if (logFilename != NULL) {
/* Open the log file if specified. It's a hack to keep opening and closing the file for
each append, but it's easier that trying to catch a signal to close the file. Windows
evidently doesn't automatically close the file when the program exits. */
logFile = fopen(logFilename, "a");
if (logFile == NULL) {
printf("Error, opening %s for write failed, %s\n",
logFilename, strerror(errno));
}
/* if success, print and close */
else {
fprintf(logFile, "%s", logMsg);
fclose(logFile);
}
}
return;
}
/* parse the command line arguments */
long getArgs(short *port,
int *verbose,
char **logFilename,
int argc,
char **argv)
{
long rc = 0;
int irc;
int i;
FILE *logFile; /* trace log file descriptor */
/* get the command line arguments */
for (i=1 ; (i<argc) && (rc == 0) ; i++) {
if ((strcmp(argv[i],"-p") == 0) ||
(strcmp(argv[i],"--port") == 0)) {
i++;
if (i < argc) {
irc = sscanf(argv[i], "%hu", port);
if (irc != 1) {
printf("-p --port (socket port) illegal value %s\n", argv[i]);
rc = ERROR_CODE;
}
} else {
printf("-p --port (socket port) needs a value\n");
rc = ERROR_CODE;
}
}
else if (strcmp(argv[i],"-raw") == 0) {
serverType = SERVER_TYPE_RAW;
}
else if (strcmp(argv[i],"-mssim") == 0) {
serverType = SERVER_TYPE_MSSIM;
}
else if (strcmp(argv[i],"-h") == 0) {
printUsage();
rc = ERROR_CODE;
}
else if ((strcmp(argv[i],"-v") == 0) ||
(strcmp(argv[i],"--verbose") == 0)) {
*verbose = TRUE;
}
else if ((strcmp(argv[i],"-l") == 0) ||
(strcmp(argv[i],"--log") == 0)) {
i++;
if (i < argc) {
if (strlen(argv[i]) < FILENAME_MAX) {
*logFilename = argv[i];
}
else {
printf("-l --log (log file name) too long\n");
rc = ERROR_CODE;
}
}
else {
printf("-l --log option (log file name) needs a value\n");
rc = ERROR_CODE;
}
}
else {
printf("\n%s is not a valid option\n",argv[i]);
printUsage();
rc = ERROR_CODE;
}
}
/* erase old contents of log file */
if ((rc == 0) && (*logFilename != NULL)) {
logFile = fopen(*logFilename, "w");
if (logFile == NULL) {
printf("Cannot open log file %s\n", *logFilename);
rc = ERROR_CODE;
}
else {
fclose(logFile);
}
}
return rc;
}
void printUsage(void)
{
printf("\n");
printf("tpmproxy\n");
printf("\n");
printf("Pass through connecting a TCPIP port to a hardware TPM\n");
printf("\n");
printf("\t--port,-p <n> TCPIP server port (default 2321)\n");
printf("\t-mssim use MS TPM 2.0 socket simulator packet format (default)\n");
printf("\t\twith TSS env variable TPM_SERVER_TYPE=mssim (default)\n");
printf("\t-raw use TPM 2.0 packet format\n");
printf("\t\twith TSS env variable TPM_SERVER_TYPE=raw\n");
printf("\t--verbose,-v verbose mode (default false)\n");
printf("\t--log,-l log transactions into given file (default none)\n");
printf("\t \n");
return;
}