Fixed bug at checking error code from file stat
[strongswan.git] / src / libpts / pts / pts.c
1 /*
2 * Copyright (C) 2011 Sansar Choinyambuu
3 * HSR Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "pts.h"
17
18 #include <debug.h>
19 #include <crypto/hashers/hasher.h>
20 #include <bio/bio_writer.h>
21 #include <bio/bio_reader.h>
22
23 #include <trousers/tss.h>
24 #include <trousers/trousers.h>
25
26 #include <sys/stat.h>
27 #include <sys/utsname.h>
28 #include <errno.h>
29
30 #define PTS_BUF_SIZE 4096
31
32 typedef struct private_pts_t private_pts_t;
33
34 /**
35 * Private data of a pts_t object.
36 *
37 */
38 struct private_pts_t {
39
40 /**
41 * Public pts_t interface.
42 */
43 pts_t public;
44
45 /**
46 * PTS Protocol Capabilities
47 */
48 pts_proto_caps_flag_t proto_caps;
49
50 /**
51 * PTS Measurement Algorithm
52 */
53 pts_meas_algorithms_t algorithm;
54
55 /**
56 * DH Hash Algorithm
57 */
58 pts_meas_algorithms_t dh_hash_algorithm;
59
60 /**
61 * PTS Diffie-Hellman Secret
62 */
63 diffie_hellman_t *dh;
64
65 /**
66 * PTS Diffie-Hellman Initiator Nonce
67 */
68 chunk_t initiator_nonce;
69
70 /**
71 * PTS Diffie-Hellman Responder Nonce
72 */
73 chunk_t responder_nonce;
74
75 /**
76 * Secret assessment value to be used for TPM Quote as an external data
77 */
78 chunk_t secret;
79
80 /**
81 * Platform and OS Info
82 */
83 char *platform_info;
84
85 /**
86 * TRUE if IMC-PTS, FALSE if IMV-PTS
87 */
88 bool is_imc;
89
90 /**
91 * Do we have an activated TPM
92 */
93 bool has_tpm;
94
95 /**
96 * Contains a TPM_CAP_VERSION_INFO struct
97 */
98 chunk_t tpm_version_info;
99
100 /**
101 * Contains TSS Blob structure for AIK
102 */
103 chunk_t aik_blob;
104
105 /**
106 * Contains a Attestation Identity Key or Certificate
107 */
108 certificate_t *aik;
109
110 /**
111 * List of extended PCR's with corresponding values
112 */
113 linked_list_t *pcrs;
114 };
115
116 METHOD(pts_t, get_proto_caps, pts_proto_caps_flag_t,
117 private_pts_t *this)
118 {
119 return this->proto_caps;
120 }
121
122 METHOD(pts_t, set_proto_caps, void,
123 private_pts_t *this, pts_proto_caps_flag_t flags)
124 {
125 this->proto_caps = flags;
126 DBG2(DBG_PTS, "supported PTS protocol capabilities: %s%s%s%s%s",
127 flags & PTS_PROTO_CAPS_C ? "C" : ".",
128 flags & PTS_PROTO_CAPS_V ? "V" : ".",
129 flags & PTS_PROTO_CAPS_D ? "D" : ".",
130 flags & PTS_PROTO_CAPS_T ? "T" : ".",
131 flags & PTS_PROTO_CAPS_X ? "X" : ".");
132 }
133
134 METHOD(pts_t, get_meas_algorithm, pts_meas_algorithms_t,
135 private_pts_t *this)
136 {
137 return this->algorithm;
138 }
139
140 METHOD(pts_t, set_meas_algorithm, void,
141 private_pts_t *this, pts_meas_algorithms_t algorithm)
142 {
143 hash_algorithm_t hash_alg;
144
145 hash_alg = pts_meas_algo_to_hash(algorithm);
146 DBG2(DBG_PTS, "selected PTS measurement algorithm is %N",
147 hash_algorithm_names, hash_alg);
148 if (hash_alg != HASH_UNKNOWN)
149 {
150 this->algorithm = algorithm;
151 }
152 }
153
154 METHOD(pts_t, get_dh_hash_algorithm, pts_meas_algorithms_t,
155 private_pts_t *this)
156 {
157 return this->dh_hash_algorithm;
158 }
159
160 METHOD(pts_t, set_dh_hash_algorithm, void,
161 private_pts_t *this, pts_meas_algorithms_t algorithm)
162 {
163 hash_algorithm_t hash_alg;
164
165 hash_alg = pts_meas_algo_to_hash(algorithm);
166 DBG2(DBG_PTS, "selected DH hash algorithm is %N",
167 hash_algorithm_names, hash_alg);
168 if (hash_alg != HASH_UNKNOWN)
169 {
170 this->dh_hash_algorithm = algorithm;
171 }
172 }
173
174
175 METHOD(pts_t, create_dh_nonce, bool,
176 private_pts_t *this, pts_dh_group_t group, int nonce_len)
177 {
178 diffie_hellman_group_t dh_group;
179 chunk_t *nonce;
180 rng_t *rng;
181
182 dh_group = pts_dh_group_to_ike(group);
183 DBG2(DBG_PTS, "selected PTS DH group is %N",
184 diffie_hellman_group_names, dh_group);
185 DESTROY_IF(this->dh);
186 this->dh = lib->crypto->create_dh(lib->crypto, dh_group);
187
188 rng = lib->crypto->create_rng(lib->crypto, RNG_STRONG);
189 if (!rng)
190 {
191 DBG1(DBG_PTS, "no rng available");
192 return FALSE;
193 }
194 DBG2(DBG_PTS, "nonce length is %d", nonce_len);
195 nonce = this->is_imc ? &this->responder_nonce : &this->initiator_nonce;
196 chunk_free(nonce);
197 rng->allocate_bytes(rng, nonce_len, nonce);
198 rng->destroy(rng);
199
200 return TRUE;
201 }
202
203 METHOD(pts_t, get_my_public_value, void,
204 private_pts_t *this, chunk_t *value, chunk_t *nonce)
205 {
206 this->dh->get_my_public_value(this->dh, value);
207 *nonce = this->is_imc ? this->responder_nonce : this->initiator_nonce;
208 }
209
210 METHOD(pts_t, set_peer_public_value, void,
211 private_pts_t *this, chunk_t value, chunk_t nonce)
212 {
213 this->dh->set_other_public_value(this->dh, value);
214
215 nonce = chunk_clone(nonce);
216 if (this->is_imc)
217 {
218 this->initiator_nonce = nonce;
219 }
220 else
221 {
222 this->responder_nonce = nonce;
223 }
224 }
225
226 METHOD(pts_t, calculate_secret, bool,
227 private_pts_t *this)
228 {
229 hasher_t *hasher;
230 hash_algorithm_t hash_alg;
231 chunk_t shared_secret;
232
233 /* Check presence of nonces */
234 if (!this->initiator_nonce.len || !this->responder_nonce.len)
235 {
236 DBG1(DBG_PTS, "initiator and/or responder nonce is not available");
237 return FALSE;
238 }
239 DBG3(DBG_PTS, "initiator nonce: %B", &this->initiator_nonce);
240 DBG3(DBG_PTS, "responder nonce: %B", &this->responder_nonce);
241
242 /* Calculate the DH secret */
243 if (this->dh->get_shared_secret(this->dh, &shared_secret) != SUCCESS)
244 {
245 DBG1(DBG_PTS, "shared DH secret computation failed");
246 return FALSE;
247 }
248 DBG3(DBG_PTS, "shared DH secret: %B", &shared_secret);
249
250 /* Calculate the secret assessment value */
251 hash_alg = pts_meas_algo_to_hash(this->dh_hash_algorithm);
252 hasher = lib->crypto->create_hasher(lib->crypto, hash_alg);
253
254 hasher->allocate_hash(hasher, chunk_from_chars('1'), NULL);
255 hasher->allocate_hash(hasher, this->initiator_nonce, NULL);
256 hasher->allocate_hash(hasher, this->responder_nonce, NULL);
257 hasher->allocate_hash(hasher, shared_secret, &this->secret);
258 hasher->destroy(hasher);
259
260 /* The DH secret must be destroyed */
261 chunk_clear(&shared_secret);
262
263 /*
264 * Truncate the hash to 20 bytes to fit the ExternalData
265 * argument of the TPM Quote command
266 */
267 this->secret.len = min(this->secret.len, 20);
268 DBG3(DBG_PTS, "secret assessment value: %B", &this->secret);
269 return TRUE;
270 }
271
272 /**
273 * Print TPM 1.2 Version Info
274 */
275 static void print_tpm_version_info(private_pts_t *this)
276 {
277 TPM_CAP_VERSION_INFO versionInfo;
278 UINT64 offset = 0;
279 TSS_RESULT result;
280
281 result = Trspi_UnloadBlob_CAP_VERSION_INFO(&offset,
282 this->tpm_version_info.ptr, &versionInfo);
283 if (result != TSS_SUCCESS)
284 {
285 DBG1(DBG_PTS, "could not parse tpm version info: tss error 0x%x",
286 result);
287 }
288 else
289 {
290 DBG2(DBG_PTS, "TPM 1.2 Version Info: Chip Version: %hhu.%hhu.%hhu.%hhu,"
291 " Spec Level: %hu, Errata Rev: %hhu, Vendor ID: %.4s",
292 versionInfo.version.major, versionInfo.version.minor,
293 versionInfo.version.revMajor, versionInfo.version.revMinor,
294 versionInfo.specLevel, versionInfo.errataRev,
295 versionInfo.tpmVendorID);
296 }
297 }
298
299 METHOD(pts_t, get_platform_info, char*,
300 private_pts_t *this)
301 {
302 return this->platform_info;
303 }
304
305 METHOD(pts_t, set_platform_info, void,
306 private_pts_t *this, char *info)
307 {
308 free(this->platform_info);
309 this->platform_info = strdup(info);
310 }
311
312 METHOD(pts_t, get_tpm_version_info, bool,
313 private_pts_t *this, chunk_t *info)
314 {
315 if (!this->has_tpm)
316 {
317 return FALSE;
318 }
319 *info = this->tpm_version_info;
320 print_tpm_version_info(this);
321 return TRUE;
322 }
323
324 METHOD(pts_t, set_tpm_version_info, void,
325 private_pts_t *this, chunk_t info)
326 {
327 this->tpm_version_info = chunk_clone(info);
328 print_tpm_version_info(this);
329 }
330
331 /**
332 * Load an AIK Blob (TSS_TSPATTRIB_KEYBLOB_BLOB attribute)
333 */
334 static void load_aik_blob(private_pts_t *this)
335 {
336 char *blob_path;
337 FILE *fp;
338 u_int32_t aikBlobLen;
339
340 blob_path = lib->settings->get_str(lib->settings,
341 "libimcv.plugins.imc-attestation.aik_blob", NULL);
342
343 if (blob_path)
344 {
345 /* Read aik key blob from a file */
346 if ((fp = fopen(blob_path, "r")) == NULL)
347 {
348 DBG1(DBG_PTS, "unable to open AIK Blob file: %s", blob_path);
349 return;
350 }
351
352 fseek(fp, 0, SEEK_END);
353 aikBlobLen = ftell(fp);
354 fseek(fp, 0L, SEEK_SET);
355
356 this->aik_blob = chunk_alloc(aikBlobLen);
357 if (fread(this->aik_blob.ptr, 1, aikBlobLen, fp))
358 {
359 DBG2(DBG_PTS, "loaded AIK Blob from '%s'", blob_path);
360 DBG3(DBG_PTS, "AIK Blob: %B", &this->aik_blob);
361 }
362 else
363 {
364 DBG1(DBG_PTS, "unable to read AIK Blob file '%s'", blob_path);
365 }
366 fclose(fp);
367 return;
368 }
369
370 DBG1(DBG_PTS, "AIK Blob is not available");
371 }
372
373 /**
374 * Load an AIK certificate or public key
375 * the certificate having precedence over the public key if both are present
376 */
377 static void load_aik(private_pts_t *this)
378 {
379 char *cert_path, *key_path;
380
381 cert_path = lib->settings->get_str(lib->settings,
382 "libimcv.plugins.imc-attestation.aik_cert", NULL);
383 key_path = lib->settings->get_str(lib->settings,
384 "libimcv.plugins.imc-attestation.aik_key", NULL);
385
386 if (cert_path)
387 {
388 this->aik = lib->creds->create(lib->creds, CRED_CERTIFICATE,
389 CERT_X509, BUILD_FROM_FILE,
390 cert_path, BUILD_END);
391 if (this->aik)
392 {
393 DBG2(DBG_PTS, "loaded AIK certificate from '%s'", cert_path);
394 return;
395 }
396 }
397 if (key_path)
398 {
399 this->aik = lib->creds->create(lib->creds, CRED_CERTIFICATE,
400 CERT_TRUSTED_PUBKEY, BUILD_FROM_FILE,
401 key_path, BUILD_END);
402 if (this->aik)
403 {
404 DBG2(DBG_PTS, "loaded AIK public key from '%s'", key_path);
405 return;
406 }
407 }
408
409 DBG1(DBG_PTS, "neither AIK certificate nor public key is available");
410 }
411
412 METHOD(pts_t, get_aik, certificate_t*,
413 private_pts_t *this)
414 {
415 return this->aik;
416 }
417
418 METHOD(pts_t, set_aik, void,
419 private_pts_t *this, certificate_t *aik)
420 {
421 DESTROY_IF(this->aik);
422 this->aik = aik->get_ref(aik);
423 }
424
425 METHOD(pts_t, hash_file, bool,
426 private_pts_t *this, hasher_t *hasher, char *pathname, u_char *hash)
427 {
428 u_char buffer[PTS_BUF_SIZE];
429 FILE *file;
430 int bytes_read;
431
432 file = fopen(pathname, "rb");
433 if (!file)
434 {
435 DBG1(DBG_PTS," file '%s' can not be opened, %s", pathname,
436 strerror(errno));
437 return FALSE;
438 }
439 while (TRUE)
440 {
441 bytes_read = fread(buffer, 1, sizeof(buffer), file);
442 if (bytes_read > 0)
443 {
444 hasher->get_hash(hasher, chunk_create(buffer, bytes_read), NULL);
445 }
446 else
447 {
448 hasher->get_hash(hasher, chunk_empty, hash);
449 break;
450 }
451 }
452 fclose(file);
453
454 return TRUE;
455 }
456
457 /**
458 * Get the relative filename of a fully qualified file pathname
459 */
460 static char* get_filename(char *pathname)
461 {
462 char *pos, *filename;
463
464 pos = filename = pathname;
465 while (pos && *(++pos) != '\0')
466 {
467 filename = pos;
468 pos = strchr(filename, '/');
469 }
470 return filename;
471 }
472
473 METHOD(pts_t, is_path_valid, bool,
474 private_pts_t *this, char *path, pts_error_code_t *error_code)
475 {
476 struct stat st;
477
478 *error_code = 0;
479
480 if (!stat(path, &st))
481 {
482 return TRUE;
483 }
484 else if (errno == ENOENT || errno == ENOTDIR)
485 {
486 DBG1(DBG_PTS, "file/directory does not exist %s", path);
487 *error_code = TCG_PTS_FILE_NOT_FOUND;
488 }
489 else if (errno == EFAULT)
490 {
491 DBG1(DBG_PTS, "bad address %s", path);
492 *error_code = TCG_PTS_INVALID_PATH;
493 }
494 else
495 {
496 DBG1(DBG_PTS, "error: %s occured while validating path: %s",
497 strerror(errno), path);
498 return FALSE;
499 }
500
501 return TRUE;
502 }
503
504 METHOD(pts_t, do_measurements, pts_file_meas_t*,
505 private_pts_t *this, u_int16_t request_id, char *pathname, bool is_directory)
506 {
507 hasher_t *hasher;
508 hash_algorithm_t hash_alg;
509 u_char hash[HASH_SIZE_SHA384];
510 chunk_t measurement;
511 pts_file_meas_t *measurements;
512
513 /* Create a hasher */
514 hash_alg = pts_meas_algo_to_hash(this->algorithm);
515 hasher = lib->crypto->create_hasher(lib->crypto, hash_alg);
516 if (!hasher)
517 {
518 DBG1(DBG_PTS, "hasher %N not available", hash_algorithm_names, hash_alg);
519 return NULL;
520 }
521
522 /* Create a measurement object */
523 measurements = pts_file_meas_create(request_id);
524
525 /* Link the hash to the measurement and set the measurement length */
526 measurement = chunk_create(hash, hasher->get_hash_size(hasher));
527
528 if (is_directory)
529 {
530 enumerator_t *enumerator;
531 char *rel_name, *abs_name;
532 struct stat st;
533
534 enumerator = enumerator_create_directory(pathname);
535 if (!enumerator)
536 {
537 DBG1(DBG_PTS," directory '%s' can not be opened, %s", pathname,
538 strerror(errno));
539 hasher->destroy(hasher);
540 measurements->destroy(measurements);
541 return NULL;
542 }
543 while (enumerator->enumerate(enumerator, &rel_name, &abs_name, &st))
544 {
545 /* measure regular files only */
546 if (S_ISREG(st.st_mode) && *rel_name != '.')
547 {
548 if (!hash_file(this, hasher, abs_name, hash))
549 {
550 enumerator->destroy(enumerator);
551 hasher->destroy(hasher);
552 measurements->destroy(measurements);
553 return NULL;
554 }
555 DBG2(DBG_PTS, " %#B for '%s'", &measurement, rel_name);
556 measurements->add(measurements, rel_name, measurement);
557 }
558 }
559 enumerator->destroy(enumerator);
560 }
561 else
562 {
563 char *filename;
564
565 if (!hash_file(this, hasher, pathname, hash))
566 {
567 hasher->destroy(hasher);
568 measurements->destroy(measurements);
569 return NULL;
570 }
571 filename = get_filename(pathname);
572 DBG2(DBG_PTS, " %#B for '%s'", &measurement, filename);
573 measurements->add(measurements, filename, measurement);
574 }
575 hasher->destroy(hasher);
576
577 return measurements;
578 }
579
580 /**
581 * Obtain statistical information describing a file
582 */
583 static bool file_metadata(char *pathname, pts_file_metadata_t **entry)
584 {
585 struct stat st;
586 pts_file_metadata_t *this;
587
588 this = malloc_thing(pts_file_metadata_t);
589
590 if (stat(pathname, &st))
591 {
592 DBG1(DBG_PTS, "Unable to obtain statistics about '%s'", pathname);
593 return FALSE;
594 }
595
596 if (S_ISREG(st.st_mode))
597 {
598 this->type = PTS_FILE_REGULAR;
599 }
600 else if (S_ISDIR(st.st_mode))
601 {
602 this->type = PTS_FILE_DIRECTORY;
603 }
604 else if (S_ISCHR(st.st_mode))
605 {
606 this->type = PTS_FILE_CHAR_SPEC;
607 }
608 else if (S_ISBLK(st.st_mode))
609 {
610 this->type = PTS_FILE_BLOCK_SPEC;
611 }
612 else if (S_ISFIFO(st.st_mode))
613 {
614 this->type = PTS_FILE_FIFO;
615 }
616 else if (S_ISLNK(st.st_mode))
617 {
618 this->type = PTS_FILE_SYM_LINK;
619 }
620 else if (S_ISSOCK(st.st_mode))
621 {
622 this->type = PTS_FILE_SOCKET;
623 }
624 else
625 {
626 this->type = PTS_FILE_OTHER;
627 }
628
629 this->filesize = st.st_size;
630 this->created = st.st_ctime;
631 this->modified = st.st_mtime;
632 this->accessed = st.st_atime;
633 this->owner = st.st_uid;
634 this->group = st.st_gid;
635
636 *entry = this;
637 return TRUE;
638 }
639
640 METHOD(pts_t, get_metadata, pts_file_meta_t*,
641 private_pts_t *this, char *pathname, bool is_directory)
642 {
643 pts_file_meta_t *metadata;
644 pts_file_metadata_t *entry;
645
646 /* Create a metadata object */
647 metadata = pts_file_meta_create();
648
649 if (is_directory)
650 {
651 enumerator_t *enumerator;
652 char *rel_name, *abs_name;
653 struct stat st;
654
655 enumerator = enumerator_create_directory(pathname);
656 if (!enumerator)
657 {
658 DBG1(DBG_PTS," directory '%s' can not be opened, %s", pathname,
659 strerror(errno));
660 metadata->destroy(metadata);
661 return NULL;
662 }
663 while (enumerator->enumerate(enumerator, &rel_name, &abs_name, &st))
664 {
665 /* measure regular files only */
666 if (S_ISREG(st.st_mode) && *rel_name != '.')
667 {
668 if (!file_metadata(abs_name, &entry))
669 {
670 enumerator->destroy(enumerator);
671 metadata->destroy(metadata);
672 return NULL;
673 }
674 entry->filename = strdup(rel_name);
675 metadata->add(metadata, entry);
676 }
677 }
678 enumerator->destroy(enumerator);
679 }
680 else
681 {
682 if (!file_metadata(pathname, &entry))
683 {
684 metadata->destroy(metadata);
685 return NULL;
686 }
687 entry->filename = strdup(get_filename(pathname));
688 metadata->add(metadata, entry);
689 }
690
691 return metadata;
692 }
693
694 METHOD(pts_t, read_pcr, bool,
695 private_pts_t *this, u_int32_t pcr_num, chunk_t *output)
696 {
697 TSS_HCONTEXT hContext;
698 TSS_HTPM hTPM;
699 TSS_RESULT result;
700 u_int32_t pcr_length;
701 chunk_t pcr_value;
702
703 result = Tspi_Context_Create(&hContext);
704 if (result != TSS_SUCCESS)
705 {
706 DBG1(DBG_PTS, "TPM context could not be created: tss error 0x%x",
707 result);
708 return FALSE;
709 }
710
711 result = Tspi_Context_Connect(hContext, NULL);
712 if (result != TSS_SUCCESS)
713 {
714 goto err;
715 }
716 result = Tspi_Context_GetTpmObject (hContext, &hTPM);
717 if (result != TSS_SUCCESS)
718 {
719 goto err;
720 }
721 pcr_value = chunk_alloc(PCR_LEN);
722 result = Tspi_TPM_PcrRead(hTPM, pcr_num, &pcr_length, &pcr_value.ptr);
723 if (result != TSS_SUCCESS)
724 {
725 goto err;
726 }
727
728 *output = pcr_value;
729 *output = chunk_clone(*output);
730
731 chunk_clear(&pcr_value);
732 DBG3(DBG_PTS, "PCR %d value:%B", pcr_num, output);
733 Tspi_Context_Close(hContext);
734 return TRUE;
735
736 err:
737 chunk_clear(&pcr_value);
738 DBG1(DBG_PTS, "TPM not available: tss error 0x%x", result);
739 Tspi_Context_Close(hContext);
740 return FALSE;
741 }
742
743 METHOD(pts_t, extend_pcr, bool,
744 private_pts_t *this, u_int32_t pcr_num, chunk_t input, chunk_t *output)
745 {
746 TSS_HCONTEXT hContext;
747 TSS_HTPM hTPM;
748 TSS_RESULT result;
749 u_int32_t pcr_length;
750 chunk_t pcr_value;
751
752 result = Tspi_Context_Create(&hContext);
753 if (result != TSS_SUCCESS)
754 {
755 DBG1(DBG_PTS, "TPM context could not be created: tss error 0x%x",
756 result);
757 return FALSE;
758 }
759 result = Tspi_Context_Connect(hContext, NULL);
760 if (result != TSS_SUCCESS)
761 {
762 goto err;
763 }
764 result = Tspi_Context_GetTpmObject (hContext, &hTPM);
765 if (result != TSS_SUCCESS)
766 {
767 goto err;
768 }
769
770 pcr_value = chunk_alloc(PCR_LEN);
771 result = Tspi_TPM_PcrExtend(hTPM, pcr_num, PCR_LEN, input.ptr,
772 NULL, &pcr_length, &pcr_value.ptr);
773 if (result != TSS_SUCCESS)
774 {
775 goto err;
776 }
777
778 *output = pcr_value;
779 *output = chunk_clone(*output);
780
781 chunk_clear(&pcr_value);
782 Tspi_Context_Close(hContext);
783 DBG3(DBG_PTS, "PCR %d extended with: %B", pcr_num, &input);
784 DBG3(DBG_PTS, "PCR %d value after extend: %B", pcr_num, output);
785 return TRUE;
786
787 err:
788 chunk_clear(&pcr_value);
789 DBG1(DBG_PTS, "TPM not available: tss error 0x%x", result);
790 Tspi_Context_Close(hContext);
791 return FALSE;
792 }
793
794 METHOD(pts_t, quote_tpm, bool,
795 private_pts_t *this, u_int32_t *pcrs, u_int32_t num_of_pcrs,
796 chunk_t *pcr_composite, chunk_t *quote_signature)
797 {
798 TSS_HCONTEXT hContext;
799 TSS_HTPM hTPM;
800 TSS_HKEY hAIK;
801 TSS_HKEY hSRK;
802 TSS_HPOLICY srkUsagePolicy;
803 TSS_UUID SRK_UUID = TSS_UUID_SRK;
804 BYTE secret[] = TSS_WELL_KNOWN_SECRET;
805 TSS_HPCRS hPcrComposite;
806 TSS_VALIDATION valData;
807 u_int32_t i;
808 TSS_RESULT result;
809 chunk_t pcr_comp, quote_sign;
810
811 result = Tspi_Context_Create(&hContext);
812 if (result != TSS_SUCCESS)
813 {
814 DBG1(DBG_PTS, "TPM context could not be created: tss error 0x%x",
815 result);
816 return FALSE;
817 }
818 result = Tspi_Context_Connect(hContext, NULL);
819 if (result != TSS_SUCCESS)
820 {
821 goto err1;
822 }
823 result = Tspi_Context_GetTpmObject (hContext, &hTPM);
824 if (result != TSS_SUCCESS)
825 {
826 goto err1;
827 }
828
829 /* Retrieve SRK from TPM and set the authentication to well known secret*/
830 result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM,
831 SRK_UUID, &hSRK);
832 if (result != TSS_SUCCESS)
833 {
834 goto err1;
835 }
836
837 result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &srkUsagePolicy);
838 if (result != TSS_SUCCESS)
839 {
840 goto err1;
841 }
842 result = Tspi_Policy_SetSecret(srkUsagePolicy, TSS_SECRET_MODE_SHA1,
843 20, secret);
844 if (result != TSS_SUCCESS)
845 {
846 goto err1;
847 }
848
849 result = Tspi_Context_LoadKeyByBlob (hContext, hSRK, this->aik_blob.len,
850 this->aik_blob.ptr, &hAIK);
851 if (result != TSS_SUCCESS)
852 {
853 goto err1;
854 }
855
856 /* Create PCR composite object */
857 result = Tspi_Context_CreateObject(hContext,
858 TSS_OBJECT_TYPE_PCRS, 0, &hPcrComposite);
859 if (result != TSS_SUCCESS)
860 {
861 goto err2;
862 }
863
864 /* Select PCR's */
865 for (i = 0; i < num_of_pcrs ; i++)
866 {
867 if (pcrs[i] < 0 || pcrs[i] >= MAX_NUM_PCR )
868 {
869 DBG1(DBG_PTS, "Invalid PCR number: %d", pcrs[i]);
870 goto err3;
871 }
872 result = Tspi_PcrComposite_SelectPcrIndex(hPcrComposite, pcrs[i]);
873 if (result != TSS_SUCCESS)
874 {
875 goto err3;
876 }
877 }
878
879 /* Set the Validation Data */
880 valData.ulExternalDataLength = this->secret.len;
881 valData.rgbExternalData = (BYTE *)this->secret.ptr;
882
883
884 /* TPM Quote */
885 result = Tspi_TPM_Quote(hTPM, hAIK, hPcrComposite, &valData);
886 if (result != TSS_SUCCESS)
887 {
888 goto err4;
889 }
890
891 /* Set output chunks */
892 pcr_comp = chunk_alloc(HASH_SIZE_SHA1);
893 memcpy(pcr_comp.ptr, valData.rgbData + 8, HASH_SIZE_SHA1);
894 *pcr_composite = pcr_comp;
895 *pcr_composite = chunk_clone(*pcr_composite);
896 DBG3(DBG_PTS, "Hash of PCR Composite: %B",pcr_composite);
897
898 chunk_t tmp = chunk_create(valData.rgbData, valData.ulDataLength);
899 DBG3(DBG_PTS, "TPM Quote Info: %B",&tmp);
900
901 quote_sign = chunk_alloc(valData.ulValidationDataLength);
902 memcpy(quote_sign.ptr, valData.rgbValidationData,
903 valData.ulValidationDataLength);
904 *quote_signature = quote_sign;
905 *quote_signature = chunk_clone(*quote_signature);
906 DBG3(DBG_PTS, "TOM Quote Signature: %B",quote_signature);
907
908 chunk_clear(&quote_sign);
909 Tspi_Context_FreeMemory(hContext, NULL);
910 Tspi_Context_CloseObject(hContext, hPcrComposite);
911 Tspi_Context_CloseObject(hContext, hAIK);
912 Tspi_Context_Close(hContext);
913 free(pcrs);
914 return TRUE;
915
916 /* Cleanup */
917 err4:
918 Tspi_Context_FreeMemory(hContext, NULL);
919
920 err3:
921 Tspi_Context_CloseObject(hContext, hPcrComposite);
922
923 err2:
924 Tspi_Context_CloseObject(hContext, hAIK);
925
926 err1:
927 Tspi_Context_Close(hContext);
928 free(pcrs);
929 DBG1(DBG_PTS, "TPM not available: tss error 0x%x", result);
930 return FALSE;
931 }
932
933 METHOD(pts_t, add_pcr_entry, void,
934 private_pts_t *this, pcr_entry_t *new)
935 {
936 enumerator_t *e;
937 pcr_entry_t *entry;
938
939 if (!this->pcrs)
940 {
941 this->pcrs = linked_list_create();
942 }
943
944 e = this->pcrs->create_enumerator(this->pcrs);
945 while (e->enumerate(e, &entry))
946 {
947 if (entry->pcr_number == new->pcr_number)
948 {
949 DBG3(DBG_PTS, "updating already added PCR%d value",
950 entry->pcr_number);
951 this->pcrs->remove_at(this->pcrs, e);
952 free(entry);
953 break;
954 }
955 }
956 DESTROY_IF(e);
957 this->pcrs->insert_last(this->pcrs, new);
958 }
959
960 /**
961 * Get the maximum PCR index received in pcr_after_value field
962 */
963 static u_int32_t get_max_pcr_index(private_pts_t *this)
964 {
965 enumerator_t *e;
966 pcr_entry_t *pcr_entry;
967 u_int32_t ret = 0;
968
969 if (this->pcrs->get_count(this->pcrs) == 0)
970 {
971 return -1;
972 }
973
974 e = this->pcrs->create_enumerator(this->pcrs);
975 while (e->enumerate(e, &pcr_entry))
976 {
977 if (pcr_entry->pcr_number > ret)
978 {
979 ret = pcr_entry->pcr_number;
980 }
981 }
982 e->destroy(e);
983
984 return ret;
985 }
986
987 /**
988 * 1. build a TCPA_PCR_COMPOSITE structure which contains (pcrCompositeBuf)
989 * TCPA_PCR_SELECTION structure (bitmask length + bitmask)
990 * UINT32 (network order) gives the number of bytes following (pcr entries * 20)
991 * TCPA_PCRVALUE[] with the pcr values
992 *
993 * The first two bytes of the message represent the length
994 * of the bitmask that follows. The bitmask represents the
995 * requested PCRs to be quoted.
996 *
997 * TPM Main-Part 2 TPM Structures_v1.2 8.1
998 * The bitmask is in big endian order"
999 *
1000 * BYTE 1 BYTE 2 ...
1001 * Bit: 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 ...
1002 * Pcr: 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 ...
1003 *
1004 * 2. SHA1(pcrCompositeBuf)
1005 *
1006 * 3. build a TCPA_QUOTE_INFO structure which contains
1007 * 4 bytes of version
1008 * 4 bytes 'Q' 'U' 'O' 'T'
1009 * 20 byte SHA1 of TCPA_PCR_COMPOSITE
1010 * 20 byte nonce
1011 */
1012
1013 METHOD(pts_t, get_quote_info, bool,
1014 private_pts_t *this, pts_meas_algorithms_t composite_algo,
1015 chunk_t *out_pcr_composite, chunk_t *out_quote_info)
1016 {
1017 enumerator_t *e;
1018 pcr_entry_t *pcr_entry;
1019 chunk_t pcr_composite, hash_pcr_composite;
1020 u_int32_t pcr_composite_len, i, maximum_pcr_index, bitmask_len;
1021 bio_writer_t *writer;
1022 hasher_t *hasher;
1023
1024 maximum_pcr_index = get_max_pcr_index(this);
1025 if (maximum_pcr_index == -1)
1026 {
1027 DBG1(DBG_PTS, "PCR entries unavailable, unable to construct "
1028 "TPM Quote Info");
1029 return FALSE;
1030 }
1031
1032 bitmask_len = maximum_pcr_index/8 +1;
1033 u_int8_t mask_bytes[MAX_NUM_PCR/8] = {0};
1034
1035 pcr_composite_len = 2 + bitmask_len + 4 +
1036 this->pcrs->get_count(this->pcrs) * PCR_LEN;
1037
1038 writer = bio_writer_create(pcr_composite_len);
1039 /* Lenght of the bist mask field */
1040 writer->write_uint16(writer, bitmask_len);
1041 /* Bit mask indicating selected PCRs */
1042 e = this->pcrs->create_enumerator(this->pcrs);
1043 while (e->enumerate(e, &pcr_entry))
1044 {
1045 u_int32_t index = pcr_entry->pcr_number;
1046 mask_bytes[index / 8] |= (1 << (index % 8));
1047 }
1048 e->destroy(e);
1049
1050 for (i = 0; i< bitmask_len ; i++)
1051 {
1052 writer->write_uint8(writer, mask_bytes[i]);
1053 }
1054
1055 /* Lenght of the pcr entries */
1056 writer->write_uint32(writer, this->pcrs->get_count(this->pcrs) * PCR_LEN);
1057 /* Actual PCR values */
1058 e = this->pcrs->create_enumerator(this->pcrs);
1059 while (e->enumerate(e, &pcr_entry))
1060 {
1061 writer->write_data(writer, chunk_create(pcr_entry->pcr_value, PCR_LEN));
1062 }
1063 free(pcr_entry);
1064 e->destroy(e);
1065
1066 /* PCR Composite structure */
1067 pcr_composite = chunk_clone(writer->get_buf(writer));
1068 DBG3(DBG_PTS, "PCR Composite: %B", &pcr_composite);
1069 writer->destroy(writer);
1070
1071 writer = bio_writer_create(TPM_QUOTE_INFO_LEN);
1072 /* Version number */
1073 writer->write_uint8(writer, 1);
1074 writer->write_uint8(writer, 1);
1075 writer->write_uint8(writer, 0);
1076 writer->write_uint8(writer, 0);
1077
1078 /* Magic QUOT value, depends on TPM Ordinal */
1079 writer->write_uint8(writer, 'Q');
1080 writer->write_uint8(writer, 'U');
1081 writer->write_uint8(writer, 'O');
1082 writer->write_uint8(writer, 'T');
1083
1084 /* Output the TPM_PCR_COMPOSITE expected from IMC */
1085 if (composite_algo)
1086 {
1087 hash_algorithm_t algo;
1088
1089 algo = pts_meas_algo_to_hash(composite_algo);
1090 hasher = lib->crypto->create_hasher(lib->crypto, algo);
1091
1092 /* Hash the PCR Composite Structure */
1093 hasher->allocate_hash(hasher, pcr_composite, out_pcr_composite);
1094 DBG3(DBG_PTS, "Hash of calculated PCR Composite: %B", out_pcr_composite);
1095 hasher->destroy(hasher);
1096 }
1097 else
1098 {
1099 *out_pcr_composite = chunk_clone(pcr_composite);
1100 DBG3(DBG_PTS, "calculated PCR Composite: %B", out_pcr_composite);
1101 }
1102
1103 /* SHA1 hash of PCR Composite to construct TPM_QUOTE_INFO */
1104 hasher = lib->crypto->create_hasher(lib->crypto, HASH_SHA1);
1105 hasher->allocate_hash(hasher, pcr_composite, &hash_pcr_composite);
1106 hasher->destroy(hasher);
1107
1108 writer->write_data(writer, hash_pcr_composite);
1109 chunk_clear(&pcr_composite);
1110 chunk_clear(&hash_pcr_composite);
1111
1112 if (!this->secret.ptr)
1113 {
1114 DBG1(DBG_PTS, "Secret assessment value unavailable",
1115 "unable to construct TPM Quote Info");
1116 chunk_clear(out_pcr_composite);
1117 writer->destroy(writer);
1118 return FALSE;
1119 }
1120 /* Secret assessment value 20 bytes (nonce) */
1121 writer->write_data(writer, this->secret);
1122 /* TPM Quote Info */
1123 *out_quote_info = chunk_clone(writer->get_buf(writer));
1124 DBG3(DBG_PTS, "Calculated TPM Quote Info: %B", out_quote_info);
1125 writer->destroy(writer);
1126
1127 return TRUE;
1128 }
1129
1130 METHOD(pts_t, verify_quote_signature, bool,
1131 private_pts_t *this, chunk_t data, chunk_t signature)
1132 {
1133 public_key_t *aik_pub_key;
1134
1135 aik_pub_key = this->aik->get_public_key(this->aik);
1136 if (!aik_pub_key)
1137 {
1138 DBG1(DBG_PTS, "failed to get public key from AIK certificate");
1139 return FALSE;
1140 }
1141
1142 if (!aik_pub_key->verify(aik_pub_key, SIGN_RSA_EMSA_PKCS1_SHA1,
1143 data, signature))
1144 {
1145 DBG1(DBG_PTS, "signature verification failed for TPM Quote Info");
1146 DESTROY_IF(aik_pub_key);
1147 return FALSE;
1148 }
1149
1150 aik_pub_key->destroy(aik_pub_key);
1151 return TRUE;
1152 }
1153
1154 METHOD(pts_t, destroy, void,
1155 private_pts_t *this)
1156 {
1157 DESTROY_IF(this->aik);
1158 DESTROY_IF(this->dh);
1159 DESTROY_IF(this->pcrs);
1160 free(this->initiator_nonce.ptr);
1161 free(this->responder_nonce.ptr);
1162 free(this->secret.ptr);
1163 free(this->platform_info);
1164 free(this->aik_blob.ptr);
1165 free(this->tpm_version_info.ptr);
1166 free(this);
1167 }
1168
1169 /**
1170 * Determine Linux distribution and hardware platform
1171 */
1172 static char* extract_platform_info(void)
1173 {
1174 FILE *file;
1175 char buf[BUF_LEN], *pos, *value = NULL;
1176 int i, len;
1177 struct utsname uninfo;
1178
1179 /* Linux/Unix distribution release info (from http://linuxmafia.com) */
1180 const char* releases[] = {
1181 "/etc/lsb-release", "/etc/debian_version",
1182 "/etc/SuSE-release", "/etc/novell-release",
1183 "/etc/sles-release", "/etc/redhat-release",
1184 "/etc/fedora-release", "/etc/gentoo-release",
1185 "/etc/slackware-version", "/etc/annvix-release",
1186 "/etc/arch-release", "/etc/arklinux-release",
1187 "/etc/aurox-release", "/etc/blackcat-release",
1188 "/etc/cobalt-release", "/etc/conectiva-release",
1189 "/etc/debian_release", "/etc/immunix-release",
1190 "/etc/lfs-release", "/etc/linuxppc-release",
1191 "/etc/mandrake-release", "/etc/mandriva-release",
1192 "/etc/mandrakelinux-release", "/etc/mklinux-release",
1193 "/etc/pld-release", "/etc/redhat_version",
1194 "/etc/slackware-release", "/etc/e-smith-release",
1195 "/etc/release", "/etc/sun-release",
1196 "/etc/tinysofa-release", "/etc/turbolinux-release",
1197 "/etc/ultrapenguin-release", "/etc/UnitedLinux-release",
1198 "/etc/va-release", "/etc/yellowdog-release"
1199 };
1200
1201 const char description[] = "DISTRIB_DESCRIPTION=\"";
1202
1203 for (i = 0; i < countof(releases); i++)
1204 {
1205 file = fopen(releases[i], "r");
1206 if (!file)
1207 {
1208 continue;
1209 }
1210 fseek(file, 0, SEEK_END);
1211 len = min(ftell(file), sizeof(buf)-1);
1212 rewind(file);
1213 buf[len] = '\0';
1214 if (fread(buf, 1, len, file) != len)
1215 {
1216 DBG1(DBG_PTS, "failed to read file '%s'", releases[i]);
1217 fclose(file);
1218 return NULL;
1219 }
1220 fclose(file);
1221
1222 if (i == 0) /* LSB release */
1223 {
1224 pos = strstr(buf, description);
1225 if (!pos)
1226 {
1227 DBG1(DBG_PTS, "failed to find begin of lsb-release "
1228 "DESCRIPTION field");
1229 return NULL;
1230 }
1231 value = pos + strlen(description);
1232 pos = strchr(value, '"');
1233 if (!pos)
1234 {
1235 DBG1(DBG_PTS, "failed to find end of lsb-release "
1236 "DESCRIPTION field");
1237 return NULL;
1238 }
1239 }
1240 else
1241 {
1242 value = buf;
1243 pos = strchr(value, '\n');
1244 if (!pos)
1245 {
1246 DBG1(DBG_PTS, "failed to find end of release string");
1247 return NULL;
1248 }
1249 }
1250 break;
1251 }
1252
1253 if (!value)
1254 {
1255 DBG1(DBG_PTS, "no distribution release file found");
1256 return NULL;
1257 }
1258
1259 if (uname(&uninfo) < 0)
1260 {
1261 DBG1(DBG_PTS, "could not retrieve machine architecture");
1262 return NULL;
1263 }
1264
1265 *pos++ = ' ';
1266 len = sizeof(buf)-1 + (pos - buf);
1267 strncpy(pos, uninfo.machine, len);
1268
1269 DBG1(DBG_PTS, "platform is '%s'", value);
1270 return strdup(value);
1271 }
1272
1273 /**
1274 * Check for a TPM by querying for TPM Version Info
1275 */
1276 static bool has_tpm(private_pts_t *this)
1277 {
1278 TSS_HCONTEXT hContext;
1279 TSS_HTPM hTPM;
1280 TSS_RESULT result;
1281 u_int32_t version_info_len;
1282
1283 result = Tspi_Context_Create(&hContext);
1284 if (result != TSS_SUCCESS)
1285 {
1286 DBG1(DBG_PTS, "TPM context could not be created: tss error 0x%x",
1287 result);
1288 return FALSE;
1289 }
1290 result = Tspi_Context_Connect(hContext, NULL);
1291 if (result != TSS_SUCCESS)
1292 {
1293 goto err;
1294 }
1295 result = Tspi_Context_GetTpmObject (hContext, &hTPM);
1296 if (result != TSS_SUCCESS)
1297 {
1298 goto err;
1299 }
1300 result = Tspi_TPM_GetCapability(hTPM, TSS_TPMCAP_VERSION_VAL, 0, NULL,
1301 &version_info_len,
1302 &this->tpm_version_info.ptr);
1303 this->tpm_version_info.len = version_info_len;
1304 if (result != TSS_SUCCESS)
1305 {
1306 goto err;
1307 }
1308 this->tpm_version_info = chunk_clone(this->tpm_version_info);
1309
1310 Tspi_Context_FreeMemory(hContext, NULL);
1311 Tspi_Context_Close(hContext);
1312 return TRUE;
1313
1314 err:
1315 DBG1(DBG_PTS, "TPM not available: tss error 0x%x", result);
1316 Tspi_Context_FreeMemory(hContext, NULL);
1317 Tspi_Context_Close(hContext);
1318 return FALSE;
1319 }
1320
1321 /**
1322 * See header
1323 */
1324 pts_t *pts_create(bool is_imc)
1325 {
1326 private_pts_t *this;
1327
1328 INIT(this,
1329 .public = {
1330 .get_proto_caps = _get_proto_caps,
1331 .set_proto_caps = _set_proto_caps,
1332 .get_meas_algorithm = _get_meas_algorithm,
1333 .set_meas_algorithm = _set_meas_algorithm,
1334 .get_dh_hash_algorithm = _get_dh_hash_algorithm,
1335 .set_dh_hash_algorithm = _set_dh_hash_algorithm,
1336 .create_dh_nonce = _create_dh_nonce,
1337 .get_my_public_value = _get_my_public_value,
1338 .set_peer_public_value = _set_peer_public_value,
1339 .calculate_secret = _calculate_secret,
1340 .get_platform_info = _get_platform_info,
1341 .set_platform_info = _set_platform_info,
1342 .get_tpm_version_info = _get_tpm_version_info,
1343 .set_tpm_version_info = _set_tpm_version_info,
1344 .get_aik = _get_aik,
1345 .set_aik = _set_aik,
1346 .is_path_valid = _is_path_valid,
1347 .hash_file = _hash_file,
1348 .do_measurements = _do_measurements,
1349 .get_metadata = _get_metadata,
1350 .read_pcr = _read_pcr,
1351 .extend_pcr = _extend_pcr,
1352 .quote_tpm = _quote_tpm,
1353 .add_pcr_entry = _add_pcr_entry,
1354 .get_quote_info = _get_quote_info,
1355 .verify_quote_signature = _verify_quote_signature,
1356 .destroy = _destroy,
1357 },
1358 .is_imc = is_imc,
1359 .proto_caps = PTS_PROTO_CAPS_V,
1360 .algorithm = PTS_MEAS_ALGO_SHA256,
1361 .dh_hash_algorithm = PTS_MEAS_ALGO_SHA256,
1362 );
1363
1364 if (is_imc)
1365 {
1366 this->platform_info = extract_platform_info();
1367
1368 if (has_tpm(this))
1369 {
1370 this->has_tpm = TRUE;
1371 this->proto_caps |= PTS_PROTO_CAPS_T | PTS_PROTO_CAPS_D;
1372 load_aik(this);
1373 load_aik_blob(this);
1374 }
1375 }
1376 else
1377 {
1378 this->proto_caps |= PTS_PROTO_CAPS_T | PTS_PROTO_CAPS_D;
1379 }
1380
1381 return &this->public;
1382 }