aikgen generates AIK private/public key pairs
[strongswan.git] / src / aikgen / aikgen.c
1 /*
2 * Copyright (C) 2014 Andreas Steffen
3 * HSR Hochschule fuer Technik Rapperswil
4 *
5 * Copyright (c) 2008 Hal Finney
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25
26 #include <library.h>
27 #include <utils/debug.h>
28 #include <utils/optionsfrom.h>
29 #include <credentials/certificates/x509.h>
30 #include <credentials/keys/public_key.h>
31 #include <asn1/oid.h>
32 #include <asn1/asn1.h>
33
34 #include <trousers/tss.h>
35 #include <trousers/trousers.h>
36
37 #include <syslog.h>
38 #include <getopt.h>
39 #include <errno.h>
40
41 /* default directory where AIK keys are stored */
42 #define AIK_DIR IPSEC_CONFDIR "/pts/"
43
44 /* default name of AIK private key blob */
45 #define DEFAULT_FILENAME_AIKBLOB AIK_DIR "aikBlob.bin"
46
47 /* default name of AIK private key blob */
48 #define DEFAULT_FILENAME_AIKPUBKEY AIK_DIR "aikPub.der"
49
50 /* size in bytes of a TSS AIK public key blob */
51 #define AIK_PUBKEY_BLOB_SIZE 284
52
53 /* logging */
54 static bool log_to_stderr = TRUE;
55 static bool log_to_syslog = TRUE;
56 static level_t default_loglevel = 1;
57
58 /* options read by optionsfrom */
59 options_t *options;
60
61 /* global variables */
62 certificate_t *cacert;
63 public_key_t *ca_pubkey;
64 chunk_t ca_modulus;
65 chunk_t aik_pubkey;
66 chunk_t aik_keyid;
67
68 /* TPM context */
69 TSS_HCONTEXT hContext;
70
71 /**
72 * logging function for aikgen
73 */
74 static void aikgen_dbg(debug_t group, level_t level, char *fmt, ...)
75 {
76 char buffer[8192];
77 char *current = buffer, *next;
78 va_list args;
79
80 if (level <= default_loglevel)
81 {
82 if (log_to_stderr)
83 {
84 va_start(args, fmt);
85 vfprintf(stderr, fmt, args);
86 va_end(args);
87 fprintf(stderr, "\n");
88 }
89 if (log_to_syslog)
90 {
91 /* write in memory buffer first */
92 va_start(args, fmt);
93 vsnprintf(buffer, sizeof(buffer), fmt, args);
94 va_end(args);
95
96 /* do a syslog with every line */
97 while (current)
98 {
99 next = strchr(current, '\n');
100 if (next)
101 {
102 *(next++) = '\0';
103 }
104 syslog(LOG_INFO, "%s\n", current);
105 current = next;
106 }
107 }
108 }
109 }
110
111 /**
112 * Initialize logging to stderr/syslog
113 */
114 static void init_log(const char *program)
115 {
116 dbg = aikgen_dbg;
117
118 if (log_to_stderr)
119 {
120 setbuf(stderr, NULL);
121 }
122 if (log_to_syslog)
123 {
124 openlog(program, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_AUTHPRIV);
125 }
126 }
127
128 /**
129 * @brief exit aikgen
130 *
131 * @param status 0 = OK, 1 = general discomfort
132 */
133 static void exit_aikgen(err_t message, ...)
134 {
135 int status = 0;
136
137 DESTROY_IF(cacert);
138 DESTROY_IF(ca_pubkey);
139 free(ca_modulus.ptr);
140 free(aik_pubkey.ptr);
141 free(aik_keyid.ptr);
142 options->destroy(options);
143
144 /* clean up TPM context */
145 if (hContext)
146 {
147 Tspi_Context_FreeMemory(hContext, NULL);
148 Tspi_Context_Close(hContext);
149 }
150
151 /* print any error message to stderr */
152 if (message != NULL && *message != '\0')
153 {
154 va_list args;
155 char m[8192];
156
157 va_start(args, message);
158 vsnprintf(m, sizeof(m), message, args);
159 va_end(args);
160
161 fprintf(stderr, "error: %s\n", m);
162 status = -1;
163 }
164 library_deinit();
165 exit(status);
166 }
167
168 /**
169 * @brief prints the usage of the program to the stderr output
170 *
171 * If message is set, program is exited with 1 (error)
172 * @param message message in case of an error
173 */
174 static void usage(const char *message)
175 {
176 fprintf(stderr,
177 "Usage: aikgen --cacert|capubkey <filename>"
178 " [--aikblob <filename>] [--aikpubkey <filename>] \n"
179 " [--idreq <filename>] [--force]"
180 " [--quiet] [--debug <level>]\n"
181 " aikgen --help\n"
182 "\n"
183 "Options:\n"
184 " --cacert (-c) certificate of [privacy] CA\n"
185 " --capubkey (-k) public key of [privacy] CA\n"
186 " --aikblob (-b) encrypted blob with AIK private key\n"
187 " --aikpubkey (-p) AIK public key\n"
188 " --idreq (-i) encrypted identity request\n"
189 " --force (-f) force to overwrite existing files\n"
190 " --help (-h) show usage and exit\n"
191 "\n"
192 "Debugging output:\n"
193 " --debug (-l) changes the log level (-1..4, default: 1)\n"
194 " --quiet (-q) do not write log output to stderr\n"
195 );
196 exit_aikgen(message);
197 }
198
199 /**
200 * @brief main of aikgen which generates an Attestation Identity Key (AIK)
201 *
202 * @param argc number of arguments
203 * @param argv pointer to the argument values
204 */
205 int main(int argc, char *argv[])
206 {
207 /* external values */
208 extern char * optarg;
209 extern int optind;
210
211 char *cacert_filename = NULL;
212 char *capubkey_filename = NULL;
213 char *aikblob_filename = DEFAULT_FILENAME_AIKBLOB;
214 char *aikpubkey_filename = DEFAULT_FILENAME_AIKPUBKEY;
215 char *idreq_filename = NULL;
216 bool force = FALSE;
217 chunk_t identity_req;
218 chunk_t aik_blob;
219 chunk_t aik_pubkey_blob;
220 chunk_t aik_modulus;
221 chunk_t aik_exponent;
222
223 /* TPM variables */
224 TSS_RESULT result;
225 TSS_HTPM hTPM;
226 TSS_HKEY hSRK;
227 TSS_HKEY hPCAKey;
228 TSS_HPOLICY hSrkPolicy;
229 TSS_HPOLICY hTPMPolicy;
230 TSS_HKEY hIdentKey;
231 TSS_UUID SRK_UUID = TSS_UUID_SRK;
232 BYTE secret[] = TSS_WELL_KNOWN_SECRET;
233 BYTE *IdentityReq;
234 UINT32 IdentityReqLen;
235 BYTE *blob;
236 UINT32 blobLen;
237
238 atexit(library_deinit);
239 if (!library_init(NULL, "aikgen"))
240 {
241 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
242 }
243 if (lib->integrity &&
244 !lib->integrity->check_file(lib->integrity, "aikgen", argv[0]))
245 {
246 fprintf(stderr, "integrity check of aikgen failed\n");
247 exit(SS_RC_DAEMON_INTEGRITY);
248 }
249
250 /* initialize global variables */
251 options = options_create();
252
253 for (;;)
254 {
255 static const struct option long_opts[] = {
256 /* name, has_arg, flag, val */
257 { "help", no_argument, NULL, 'h' },
258 { "optionsfrom", required_argument, NULL, '+' },
259 { "cacert", required_argument, NULL, 'c' },
260 { "capubkey", required_argument, NULL, 'k' },
261 { "aikblob", required_argument, NULL, 'b' },
262 { "aikpubkey", required_argument, NULL, 'p' },
263 { "idreq", required_argument, NULL, 'i' },
264 { "force", no_argument, NULL, 'f' },
265 { "quiet", no_argument, NULL, 'q' },
266 { "debug", required_argument, NULL, 'l' },
267 { 0,0,0,0 }
268 };
269
270 /* parse next option */
271 int c = getopt_long(argc, argv, "ho:c:b:p:fqd:", long_opts, NULL);
272
273 switch (c)
274 {
275 case EOF: /* end of flags */
276 break;
277
278 case 'h': /* --help */
279 usage(NULL);
280
281 case '+': /* --optionsfrom <filename> */
282 if (!options->from(options, optarg, &argc, &argv, optind))
283 {
284 exit_aikgen("optionsfrom failed");
285 }
286 continue;
287
288 case 'c': /* --cacert <filename> */
289 cacert_filename = optarg;
290 continue;
291
292 case 'k': /* --capubkey <filename> */
293 capubkey_filename = optarg;
294 continue;
295
296 case 'b': /* --aikblob <filename> */
297 aikblob_filename = optarg;
298 continue;
299
300 case 'p': /* --aikpubkey <filename> */
301 aikpubkey_filename = optarg;
302 continue;
303
304 case 'i': /* --idreq <filename> */
305 idreq_filename = optarg;
306 continue;
307
308 case 'f': /* --force */
309 force = TRUE;
310 continue;
311
312 case 'q': /* --quiet */
313 log_to_stderr = FALSE;
314 continue;
315
316 case 'l': /* --debug <level> */
317 default_loglevel = atoi(optarg);
318 continue;
319
320 default:
321 usage("unknown option");
322 }
323 /* break from loop */
324 break;
325 }
326
327 init_log("aikgen");
328
329 if (!lib->plugins->load(lib->plugins,
330 lib->settings->get_str(lib->settings, "aikgen.load", PLUGINS)))
331 {
332 exit_aikgen("plugin loading failed");
333 }
334
335 /* read certificate of [privacy] CA if it exists */
336 if (cacert_filename)
337 {
338 cacert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
339 BUILD_FROM_FILE, cacert_filename, BUILD_END);
340 if (!cacert)
341 {
342 exit_aikgen("could not read ca certificate file '%s'",
343 cacert_filename);
344 }
345 }
346
347 /* optionally read public key of [privacy CA] if it exists */
348 if (!cacert)
349 {
350 if (!capubkey_filename)
351 {
352 usage("either --cacert or --capubkey option is required");
353 }
354 cacert = lib->creds->create(lib->creds, CRED_CERTIFICATE,
355 CERT_TRUSTED_PUBKEY, BUILD_FROM_FILE,
356 capubkey_filename, BUILD_END);
357 if (!cacert)
358 {
359 exit_aikgen("could not read ca public key file '%s'",
360 capubkey_filename);
361 }
362 }
363
364 /* extract public key from CA certificate or trusted CA public key */
365 ca_pubkey = cacert->get_public_key(cacert);
366 if (!ca_pubkey)
367 {
368 exit_aikgen("could not extract ca public key");
369 }
370 if (ca_pubkey->get_type(ca_pubkey) != KEY_RSA ||
371 ca_pubkey->get_keysize(ca_pubkey) != 2048)
372 {
373 exit_aikgen("ca public key must be RSA 2048 but is %N %d",
374 key_type_names, ca_pubkey->get_type(ca_pubkey),
375 ca_pubkey->get_keysize(ca_pubkey));
376 }
377 if (!ca_pubkey->get_encoding(ca_pubkey, PUBKEY_RSA_MODULUS, &ca_modulus))
378 {
379 exit_aikgen("could not extract RSA modulus from ca public key");
380 }
381
382 /* initialize TSS context and connect to it */
383 result = Tspi_Context_Create(&hContext);
384 if (result != TSS_SUCCESS)
385 {
386 exit_aikgen("tss 0x%x on Tspi_Context_Create", result);
387 }
388 result = Tspi_Context_Connect(hContext, NULL);
389 if (result != TSS_SUCCESS)
390 {
391 exit_aikgen("tss 0x%x on Tspi_Context_Connect", result);
392 }
393
394 /* get SRK plus SRK policy and set SRK secret */
395 result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM,
396 SRK_UUID, &hSRK);
397 if (result != TSS_SUCCESS)
398 {
399 exit_aikgen("tss 0x%x on Tspi_Context_LoadKeyByUUID for SRK", result);
400 }
401 result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &hSrkPolicy);
402 if (result != TSS_SUCCESS)
403 {
404 exit_aikgen("tss 0x%x on Tspi_GetPolicyObject for SRK", result);
405 }
406 result = Tspi_Policy_SetSecret(hSrkPolicy, TSS_SECRET_MODE_SHA1, 20, secret);
407 if (result != TSS_SUCCESS)
408 {
409 exit_aikgen("tss 0x%x on Tspi_Policy_SetSecret for SRK", result);
410 }
411
412 /* get TPM plus TPM policy and set TPM secret */
413 result = Tspi_Context_GetTpmObject (hContext, &hTPM);
414 if (result != TSS_SUCCESS)
415 {
416 exit_aikgen("tss 0x%x on Tspi_Context_GetTpmObject", result);
417 }
418 result = Tspi_GetPolicyObject(hTPM, TSS_POLICY_USAGE, &hTPMPolicy);
419 if (result != TSS_SUCCESS)
420 {
421 exit_aikgen("tss 0x%x on Tspi_GetPolicyObject for TPM", result);
422 }
423 result = Tspi_Policy_SetSecret(hTPMPolicy, TSS_SECRET_MODE_SHA1, 20, secret);
424 if (result != TSS_SUCCESS)
425 {
426 exit_aikgen("tss 0x%x on Tspi_Policy_SetSecret for TPM", result);
427 }
428
429 /* create context for a 2048 bit AIK */
430 result = Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY,
431 TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 |
432 TSS_KEY_VOLATILE | TSS_KEY_NOT_MIGRATABLE, &hIdentKey);
433 if (result != TSS_SUCCESS)
434 {
435 exit_aikgen("tss 0x%x on Tspi_Context_CreateObject for key", result);
436 }
437
438 /* create context for the Privacy CA public key and assign modulus */
439 result = Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY,
440 TSS_KEY_TYPE_LEGACY|TSS_KEY_SIZE_2048, &hPCAKey);
441 if (result != TSS_SUCCESS)
442 {
443 exit_aikgen("tss 0x%x on Tspi_Context_CreateObject for PCA", result);
444 }
445 result = Tspi_SetAttribData (hPCAKey, TSS_TSPATTRIB_RSAKEY_INFO,
446 TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, ca_modulus.len,
447 ca_modulus.ptr);
448 if (result != TSS_SUCCESS)
449 {
450 exit_aikgen("tss 0x%x on Tspi_SetAttribData for PCA modulus", result);
451 }
452 result = Tspi_SetAttribUint32(hPCAKey, TSS_TSPATTRIB_KEY_INFO,
453 TSS_TSPATTRIB_KEYINFO_ENCSCHEME, TSS_ES_RSAESPKCSV15);
454 if (result != TSS_SUCCESS)
455 {
456 exit_aikgen("tss 0x%x on Tspi_SetAttribUint32 for PCA "
457 "encryption scheme", result);
458 }
459
460 /* generate AIK */
461 DBG1(DBG_LIB, "Generating identity key...");
462 result = Tspi_TPM_CollateIdentityRequest(hTPM, hSRK, hPCAKey, 0, NULL,
463 hIdentKey, TSS_ALG_AES, &IdentityReqLen, &IdentityReq);
464 if (result != TSS_SUCCESS)
465 {
466 exit_aikgen("tss 0x%x on Tspi_TPM_CollateIdentityRequest", result);
467 }
468 identity_req = chunk_create(IdentityReq, IdentityReqLen);
469 DBG3(DBG_LIB, "Identity Request: %B", &identity_req);
470
471 /* optionally output identity request encrypted with ca public key */
472 if (idreq_filename)
473 {
474 if (!chunk_write(identity_req, idreq_filename, 0022, force))
475 {
476 exit_aikgen("could not write AIK identity request file '%s': %s",
477 idreq_filename, strerror(errno));
478 }
479 DBG1(DBG_LIB, "AIK identity request written to '%s' (%u bytes)",
480 idreq_filename, identity_req.len);
481 }
482
483 /* load identity key */
484 result = Tspi_Key_LoadKey (hIdentKey, hSRK);
485 if (result != TSS_SUCCESS)
486 {
487 exit_aikgen("tss 0x%x on Tspi_Key_LoadKey for AIK\n", result);
488 }
489
490 /* output AIK private key in TSS blob format */
491 result = Tspi_GetAttribData (hIdentKey, TSS_TSPATTRIB_KEY_BLOB,
492 TSS_TSPATTRIB_KEYBLOB_BLOB, &blobLen, &blob);
493 if (result != TSS_SUCCESS)
494 {
495 exit_aikgen("tss 0x%x on Tspi_GetAttribData for private key blob",
496 result);
497 }
498 aik_blob = chunk_create(blob, blobLen);
499 DBG3(DBG_LIB, "AIK private key blob: %B", &aik_blob);
500
501 if (!chunk_write(aik_blob, aikblob_filename, 0022, force))
502 {
503 exit_aikgen("could not write AIK blob file '%s': %s",
504 aikblob_filename, strerror(errno));
505 }
506 DBG1(DBG_LIB, "AIK private key blob written to '%s' (%u bytes)",
507 aikblob_filename, aik_blob.len);
508
509 /* output AIK Public Key in TSS blob format */
510 result = Tspi_GetAttribData (hIdentKey, TSS_TSPATTRIB_KEY_BLOB,
511 TSS_TSPATTRIB_KEYBLOB_PUBLIC_KEY, &blobLen, &blob);
512 if (result != TSS_SUCCESS)
513 {
514 exit_aikgen("tss 0x%x on Tspi_GetAttribData for public key blob",
515 result);
516 }
517 aik_pubkey_blob = chunk_create(blob, blobLen);
518 DBG3(DBG_LIB, "AIK public key blob: %B", &aik_pubkey_blob);
519
520 /* create a trusted AIK public key */
521 if (aik_pubkey_blob.len != AIK_PUBKEY_BLOB_SIZE)
522 {
523 exit_aikgen("AIK public key is not in TSS blob format");
524 }
525 aik_modulus = chunk_skip(aik_pubkey_blob, AIK_PUBKEY_BLOB_SIZE - 256);
526 aik_exponent = chunk_from_chars(0x01, 0x00, 0x01);
527
528 /* output subjectPublicKeyInfo encoding of AIK public key */
529 if (!lib->encoding->encode(lib->encoding, PUBKEY_SPKI_ASN1_DER, NULL,
530 &aik_pubkey, CRED_PART_RSA_MODULUS, aik_modulus,
531 CRED_PART_RSA_PUB_EXP, aik_exponent, CRED_PART_END))
532 {
533 exit_aikgen("subjectPublicKeyInfo encoding of AIK key failed");
534 }
535 if (!chunk_write(aik_pubkey, aikpubkey_filename, 0022, force))
536 {
537 exit_aikgen("could not write AIK public key file '%s': %s",
538 aikpubkey_filename, strerror(errno));
539 }
540 DBG1(DBG_LIB, "AIK public key written to '%s' (%u bytes)",
541 aikpubkey_filename, aik_pubkey.len);
542
543 /* display AIK keyid derived from subjectPublicKeyInfo encoding */
544 if (!lib->encoding->encode(lib->encoding, KEYID_PUBKEY_INFO_SHA1, NULL,
545 &aik_keyid, CRED_PART_RSA_MODULUS, aik_modulus,
546 CRED_PART_RSA_PUB_EXP, aik_exponent, CRED_PART_END))
547 {
548 exit_aikgen("computation of AIK keyid failed");
549 }
550 DBG1(DBG_LIB, "AIK keyid: %#B", &aik_keyid);
551
552 exit_aikgen(NULL);
553 return -1; /* should never be reached */
554 }