VirtualBox

source: vbox/trunk/src/VBox/Runtime/tools/RTSignTool.cpp@ 64731

Last change on this file since 64731 was 64731, checked in by vboxsync, 8 years ago

SUP,IPRT: If link time validation fails with VERR_CR_X509_CPV_NOT_VALID_AT_TIME, retry with current time.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.6 KB
Line 
1/* $Id: RTSignTool.cpp 64731 2016-11-21 14:35:37Z vboxsync $ */
2/** @file
3 * IPRT - Signing Tool.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include <iprt/assert.h>
32#include <iprt/buildconfig.h>
33#include <iprt/err.h>
34#include <iprt/getopt.h>
35#include <iprt/file.h>
36#include <iprt/initterm.h>
37#include <iprt/ldr.h>
38#include <iprt/message.h>
39#include <iprt/mem.h>
40#include <iprt/path.h>
41#include <iprt/stream.h>
42#include <iprt/string.h>
43#include <iprt/crypto/x509.h>
44#include <iprt/crypto/pkcs7.h>
45#include <iprt/crypto/store.h>
46#ifdef VBOX
47# include <VBox/sup.h> /* Certificates */
48#endif
49
50
51/*******************************************************************************
52* Structures and Typedefs *
53*******************************************************************************/
54/** Help detail levels. */
55typedef enum RTSIGNTOOLHELP
56{
57 RTSIGNTOOLHELP_USAGE,
58 RTSIGNTOOLHELP_FULL
59} RTSIGNTOOLHELP;
60
61
62/*******************************************************************************
63* Internal Functions *
64*******************************************************************************/
65static RTEXITCODE HandleHelp(int cArgs, char **papszArgs);
66static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
67static RTEXITCODE HandleVersion(int cArgs, char **papszArgs);
68
69
70
71
72/*
73 * The 'extract-exe-signer-cert' command.
74 */
75static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
76{
77 RT_NOREF_PV(enmLevel);
78 RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
79 return RTEXITCODE_SUCCESS;
80}
81
82static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
83{
84 /*
85 * Parse arguments.
86 */
87 static const RTGETOPTDEF s_aOptions[] =
88 {
89 { "--ber", 'b', RTGETOPT_REQ_NOTHING },
90 { "--cer", 'c', RTGETOPT_REQ_NOTHING },
91 { "--der", 'd', RTGETOPT_REQ_NOTHING },
92 { "--exe", 'e', RTGETOPT_REQ_STRING },
93 { "--output", 'o', RTGETOPT_REQ_STRING },
94 };
95
96 const char *pszExe = NULL;
97 const char *pszOut = NULL;
98 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
99 uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
100
101 RTGETOPTSTATE GetState;
102 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
103 AssertRCReturn(rc, RTEXITCODE_FAILURE);
104 RTGETOPTUNION ValueUnion;
105 int ch;
106 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
107 {
108 switch (ch)
109 {
110 case 'e': pszExe = ValueUnion.psz; break;
111 case 'o': pszOut = ValueUnion.psz; break;
112 case 'b': fCursorFlags = 0; break;
113 case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
114 case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
115 case 'V': return HandleVersion(cArgs, papszArgs);
116 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
117
118 case VINF_GETOPT_NOT_OPTION:
119 if (!pszExe)
120 pszExe = ValueUnion.psz;
121 else if (!pszOut)
122 pszOut = ValueUnion.psz;
123 else
124 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
125 break;
126
127 default:
128 return RTGetOptPrintError(ch, &ValueUnion);
129 }
130 }
131 if (!pszExe)
132 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
133 if (!pszOut)
134 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
135 if (RTPathExists(pszOut))
136 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
137
138 /*
139 * Do it.
140 */
141
142 /* Open the executable image and query the PKCS7 info. */
143 RTLDRMOD hLdrMod;
144 rc = RTLdrOpen(pszExe, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod);
145 if (RT_FAILURE(rc))
146 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszExe, rc);
147
148 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
149#ifdef DEBUG
150 size_t cbBuf = 64;
151#else
152 size_t cbBuf = _512K;
153#endif
154 void *pvBuf = RTMemAlloc(cbBuf);
155 size_t cbRet = 0;
156 rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet);
157 if (rc == VERR_BUFFER_OVERFLOW && cbRet < _4M && cbRet > 0)
158 {
159 RTMemFree(pvBuf);
160 cbBuf = cbRet;
161 pvBuf = RTMemAlloc(cbBuf);
162 rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet);
163 }
164 if (RT_SUCCESS(rc))
165 {
166 static RTERRINFOSTATIC s_StaticErrInfo;
167 RTErrInfoInitStatic(&s_StaticErrInfo);
168
169 /*
170 * Decode the output.
171 */
172 RTASN1CURSORPRIMARY PrimaryCursor;
173 RTAsn1CursorInitPrimary(&PrimaryCursor, pvBuf, (uint32_t)cbRet, &s_StaticErrInfo.Core,
174 &g_RTAsn1DefaultAllocator, fCursorFlags, "exe");
175 RTCRPKCS7CONTENTINFO Pkcs7Ci;
176 rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &Pkcs7Ci, "pkcs7");
177 if (RT_SUCCESS(rc))
178 {
179 if (RTCrPkcs7ContentInfo_IsSignedData(&Pkcs7Ci))
180 {
181 PCRTCRPKCS7SIGNEDDATA pSd = Pkcs7Ci.u.pSignedData;
182 if (pSd->SignerInfos.cItems == 1)
183 {
184 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSd->SignerInfos.paItems[0].IssuerAndSerialNumber;
185 PCRTCRX509CERTIFICATE pCert;
186 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSd->Certificates,
187 &pISN->Name, &pISN->SerialNumber);
188 if (pCert)
189 {
190 /*
191 * Write it out.
192 */
193 RTFILE hFile;
194 rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE);
195 if (RT_SUCCESS(rc))
196 {
197 uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
198 rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
199 cbCert, NULL);
200 if (RT_SUCCESS(rc))
201 {
202 rc = RTFileClose(hFile);
203 if (RT_SUCCESS(rc))
204 {
205 hFile = NIL_RTFILE;
206 rcExit = RTEXITCODE_SUCCESS;
207 RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut);
208 }
209 else
210 RTMsgError("RTFileClose failed: %Rrc", rc);
211 }
212 else
213 RTMsgError("RTFileWrite failed: %Rrc", rc);
214 RTFileClose(hFile);
215 }
216 else
217 RTMsgError("Error opening '%s': %Rrc", pszOut, rc);
218 }
219 else
220 RTMsgError("Certificate not found.");
221 }
222 else
223 RTMsgError("SignerInfo count: %u", pSd->SignerInfos.cItems);
224 }
225 else
226 RTMsgError("No PKCS7 content: ContentType=%s", Pkcs7Ci.ContentType.szObjId);
227 RTAsn1VtDelete(&Pkcs7Ci.SeqCore.Asn1Core);
228 }
229 else
230 RTMsgError("RTPkcs7ContentInfoDecodeAsn1 failed: %Rrc - %s", rc, s_StaticErrInfo.szMsg);
231 }
232 else
233 RTMsgError("RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc", pszExe, rc);
234 RTMemFree(pvBuf);
235 rc = RTLdrClose(hLdrMod);
236 if (RT_FAILURE(rc))
237 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc);
238 return rcExit;
239}
240
241#ifndef IPRT_IN_BUILD_TOOL
242
243/*
244 * The 'verify-exe' command.
245 */
246static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
247{
248 RT_NOREF_PV(enmLevel);
249 RTStrmPrintf(pStrm,
250 "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n"
251 " [--type <win|osx>] <exe1> [exe2 [..]]\n");
252 return RTEXITCODE_SUCCESS;
253}
254
255typedef struct VERIFYEXESTATE
256{
257 RTCRSTORE hRootStore;
258 RTCRSTORE hKernelRootStore;
259 RTCRSTORE hAdditionalStore;
260 bool fKernel;
261 int cVerbose;
262 enum { kSignType_Windows, kSignType_OSX } enmSignType;
263 uint64_t uTimestamp;
264 RTLDRARCH enmLdrArch;
265} VERIFYEXESTATE;
266
267#ifdef VBOX
268/** Certificate store load set.
269 * Declared outside HandleVerifyExe because of braindead gcc visibility crap. */
270struct STSTORESET
271{
272 RTCRSTORE hStore;
273 PCSUPTAENTRY paTAs;
274 unsigned cTAs;
275};
276#endif
277
278/**
279 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
280 * Standard code signing. Use this for Microsoft SPC.}
281 */
282static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
283 void *pvUser, PRTERRINFO pErrInfo)
284{
285 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
286 uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0;
287
288 /*
289 * Dump all the paths.
290 */
291 if (pState->cVerbose > 0)
292 {
293 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
294 {
295 RTPrintf("---\n");
296 RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
297 *pErrInfo->pszMsg = '\0';
298 }
299 RTPrintf("---\n");
300 }
301
302 /*
303 * Test signing certificates normally doesn't have all the necessary
304 * features required below. So, treat them as special cases.
305 */
306 if ( hCertPaths == NIL_RTCRX509CERTPATHS
307 && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
308 {
309 RTMsgInfo("Test signed.\n");
310 return VINF_SUCCESS;
311 }
312
313 if (hCertPaths == NIL_RTCRX509CERTPATHS)
314 RTMsgInfo("Signed by trusted certificate.\n");
315
316 /*
317 * Standard code signing capabilites required.
318 */
319 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
320 if ( RT_SUCCESS(rc)
321 && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
322 {
323 /*
324 * If kernel signing, a valid certificate path must be anchored by the
325 * microsoft kernel signing root certificate. The only alternative is
326 * test signing.
327 */
328 if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS)
329 {
330 uint32_t cFound = 0;
331 uint32_t cValid = 0;
332 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
333 {
334 bool fTrusted;
335 PCRTCRX509NAME pSubject;
336 PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
337 int rcVerify;
338 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
339 NULL, NULL /*pCertCtx*/, &rcVerify);
340 AssertRCBreak(rc);
341
342 if (RT_SUCCESS(rcVerify))
343 {
344 Assert(fTrusted);
345 cValid++;
346
347 /* Search the kernel signing root store for a matching anchor. */
348 RTCRSTORECERTSEARCH Search;
349 rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search);
350 AssertRCBreak(rc);
351 PCRTCRCERTCTX pCertCtx;
352 while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL)
353 {
354 PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo;
355 if (pCertCtx->pCert)
356 pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
357 else if (pCertCtx->pTaInfo)
358 pPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
359 else
360 pPubKeyInfo = NULL;
361 if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0)
362 cFound++;
363 RTCrCertCtxRelease(pCertCtx);
364 }
365
366 int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2);
367 }
368 }
369 if (RT_SUCCESS(rc) && cFound == 0)
370 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
371 if (RT_SUCCESS(rc) && cValid != 2)
372 RTMsgWarning("%u valid paths, expected 2", cValid);
373 }
374 }
375
376 return rc;
377}
378
379
380/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
381static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
382 void const *pvSignature, size_t cbSignature,
383 PRTERRINFO pErrInfo, void *pvUser)
384{
385 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
386 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(cbSignature);
387
388 switch (enmSignature)
389 {
390 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
391 {
392 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
393
394 RTTIMESPEC ValidationTime;
395 RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp);
396
397 /*
398 * Dump the signed data if so requested.
399 */
400 if (pState->cVerbose)
401 RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
402
403
404 /*
405 * Do the actual verification. Will have to modify this so it takes
406 * the authenticode policies into account.
407 */
408 return RTCrPkcs7VerifySignedData(pContentInfo,
409 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
410 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
411 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT,
412 pState->hAdditionalStore, pState->hRootStore, &ValidationTime,
413 VerifyExecCertVerifyCallback, pState, pErrInfo);
414 }
415
416 default:
417 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature);
418 }
419}
420
421/** Worker for HandleVerifyExe. */
422static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
423{
424 /*
425 * Open the executable image and verify it.
426 */
427 RTLDRMOD hLdrMod;
428 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod);
429 if (RT_FAILURE(rc))
430 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc);
431
432
433 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pState->uTimestamp, sizeof(pState->uTimestamp));
434 if (RT_SUCCESS(rc))
435 {
436 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
437 if (RT_SUCCESS(rc))
438 RTMsgInfo("'%s' is valid.\n", pszFilename);
439 else if (rc == VERR_CR_X509_CPV_NOT_VALID_AT_TIME)
440 {
441 RTTIMESPEC Now;
442 pState->uTimestamp = RTTimeSpecGetSeconds(RTTimeNow(&Now));
443 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
444 if (RT_SUCCESS(rc))
445 RTMsgInfo("'%s' is valid now, but not at link time.\n", pszFilename);
446 }
447 if (RT_FAILURE(rc))
448 RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg);
449 }
450 else
451 RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pszFilename, rc);
452
453 int rc2 = RTLdrClose(hLdrMod);
454 if (RT_FAILURE(rc2))
455 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
456 if (RT_FAILURE(rc))
457 return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
458
459 return RTEXITCODE_SUCCESS;
460}
461
462
463static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
464{
465 RTERRINFOSTATIC StaticErrInfo;
466
467 /* Note! This code does not try to clean up the crypto stores on failure.
468 This is intentional as the code is only expected to be used in a
469 one-command-per-process environment where we do exit() upon
470 returning from this function. */
471
472 /*
473 * Parse arguments.
474 */
475 static const RTGETOPTDEF s_aOptions[] =
476 {
477 { "--kernel", 'k', RTGETOPT_REQ_NOTHING },
478 { "--root", 'r', RTGETOPT_REQ_STRING },
479 { "--additional", 'a', RTGETOPT_REQ_STRING },
480 { "--add", 'a', RTGETOPT_REQ_STRING },
481 { "--type", 't', RTGETOPT_REQ_STRING },
482 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
483 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
484 };
485
486 VERIFYEXESTATE State =
487 {
488 NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false,
489 VERIFYEXESTATE::kSignType_Windows, 0, RTLDRARCH_WHATEVER
490 };
491 int rc = RTCrStoreCreateInMem(&State.hRootStore, 0);
492 if (RT_SUCCESS(rc))
493 rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0);
494 if (RT_SUCCESS(rc))
495 rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0);
496 if (RT_FAILURE(rc))
497 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
498
499 RTGETOPTSTATE GetState;
500 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
501 AssertRCReturn(rc, RTEXITCODE_FAILURE);
502 RTGETOPTUNION ValueUnion;
503 int ch;
504 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
505 {
506 switch (ch)
507 {
508 case 'r': case 'a':
509 rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore,
510 RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR,
511 ValueUnion.psz, RTErrInfoInitStatic(&StaticErrInfo));
512 if (RT_FAILURE(rc))
513 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s",
514 ValueUnion.psz, rc, StaticErrInfo.szMsg);
515 if (RTErrInfoIsSet(&StaticErrInfo.Core))
516 RTMsgWarning("Warnings loading certificate '%s': %s", ValueUnion.psz, StaticErrInfo.szMsg);
517 break;
518
519 case 't':
520 if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
521 State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
522 else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
523 State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
524 else
525 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
526 break;
527
528 case 'k': State.fKernel = true; break;
529 case 'v': State.cVerbose++; break;
530 case 'q': State.cVerbose = 0; break;
531 case 'V': return HandleVersion(cArgs, papszArgs);
532 case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
533 default: return RTGetOptPrintError(ch, &ValueUnion);
534 }
535 }
536 if (ch != VINF_GETOPT_NOT_OPTION)
537 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
538
539 /*
540 * Populate the certificate stores according to the signing type.
541 */
542#ifdef VBOX
543 unsigned cSets = 0;
544 struct STSTORESET aSets[6];
545#endif
546
547 switch (State.enmSignType)
548 {
549 case VERIFYEXESTATE::kSignType_Windows:
550#ifdef VBOX
551 aSets[cSets].hStore = State.hRootStore;
552 aSets[cSets].paTAs = g_aSUPTimestampTAs;
553 aSets[cSets].cTAs = g_cSUPTimestampTAs;
554 cSets++;
555 aSets[cSets].hStore = State.hRootStore;
556 aSets[cSets].paTAs = g_aSUPSpcRootTAs;
557 aSets[cSets].cTAs = g_cSUPSpcRootTAs;
558 cSets++;
559 aSets[cSets].hStore = State.hRootStore;
560 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
561 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
562 cSets++;
563 aSets[cSets].hStore = State.hKernelRootStore;
564 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
565 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
566 cSets++;
567#endif
568 break;
569
570 case VERIFYEXESTATE::kSignType_OSX:
571 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented.");
572 }
573
574#ifdef VBOX
575 for (unsigned i = 0; i < cSets; i++)
576 for (unsigned j = 0; j < aSets[i].cTAs; j++)
577 {
578 rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
579 aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
580 if (RT_FAILURE(rc))
581 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
582 i, j, StaticErrInfo.szMsg);
583 }
584#endif
585
586 /*
587 * Do it.
588 */
589 RTEXITCODE rcExit;
590 for (;;)
591 {
592 rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo);
593 if (rcExit != RTEXITCODE_SUCCESS)
594 break;
595
596 /*
597 * Next file
598 */
599 ch = RTGetOpt(&GetState, &ValueUnion);
600 if (ch == 0)
601 break;
602 if (ch != VINF_GETOPT_NOT_OPTION)
603 {
604 rcExit = RTGetOptPrintError(ch, &ValueUnion);
605 break;
606 }
607 }
608
609 /*
610 * Clean up.
611 */
612 uint32_t cRefs;
613 cRefs = RTCrStoreRelease(State.hRootStore); Assert(cRefs == 0);
614 cRefs = RTCrStoreRelease(State.hKernelRootStore); Assert(cRefs == 0);
615 cRefs = RTCrStoreRelease(State.hAdditionalStore); Assert(cRefs == 0);
616
617 return rcExit;
618}
619
620#endif /* !IPRT_IN_BUILD_TOOL */
621
622/*
623 * The 'make-tainfo' command.
624 */
625static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
626{
627 RT_NOREF_PV(enmLevel);
628 RTStrmPrintf(pStrm,
629 "make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
630 return RTEXITCODE_SUCCESS;
631}
632
633
634typedef struct MAKETAINFOSTATE
635{
636 int cVerbose;
637 const char *pszCert;
638 const char *pszOutput;
639} MAKETAINFOSTATE;
640
641
642/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
643static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
644{
645 RT_NOREF_PV(pErrInfo);
646 return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
647}
648
649
650static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
651{
652 /*
653 * Parse arguments.
654 */
655 static const RTGETOPTDEF s_aOptions[] =
656 {
657 { "--cert", 'c', RTGETOPT_REQ_STRING },
658 { "--output", 'o', RTGETOPT_REQ_STRING },
659 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
660 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
661 };
662
663 MAKETAINFOSTATE State = { 0, NULL, NULL };
664
665 RTGETOPTSTATE GetState;
666 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
667 AssertRCReturn(rc, RTEXITCODE_FAILURE);
668 RTGETOPTUNION ValueUnion;
669 int ch;
670 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
671 {
672 switch (ch)
673 {
674 case 'c':
675 if (State.pszCert)
676 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
677 State.pszCert = ValueUnion.psz;
678 break;
679
680 case 'o':
681 case VINF_GETOPT_NOT_OPTION:
682 if (State.pszOutput)
683 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
684 State.pszOutput = ValueUnion.psz;
685 break;
686
687 case 'v': State.cVerbose++; break;
688 case 'q': State.cVerbose = 0; break;
689 case 'V': return HandleVersion(cArgs, papszArgs);
690 case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
691 default: return RTGetOptPrintError(ch, &ValueUnion);
692 }
693 }
694 if (!State.pszCert)
695 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
696 if (!State.pszOutput)
697 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
698
699 /*
700 * Read the certificate.
701 */
702 RTERRINFOSTATIC StaticErrInfo;
703 RTCRX509CERTIFICATE Certificate;
704 rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
705 RTErrInfoInitStatic(&StaticErrInfo));
706 if (RT_FAILURE(rc))
707 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
708 State.pszCert, rc, StaticErrInfo.szMsg);
709 /*
710 * Construct the trust anchor information.
711 */
712 RTCRTAFTRUSTANCHORINFO TrustAnchor;
713 rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
714 if (RT_SUCCESS(rc))
715 {
716 /* Public key. */
717 Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
718 RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
719 rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
720 &g_RTAsn1DefaultAllocator);
721 if (RT_FAILURE(rc))
722 RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
723 RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
724
725 /* Key Identifier. */
726 PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
727 if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
728 pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
729 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
730 && RTCrX509Certificate_IsSelfSigned(&Certificate)
731 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
732 pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
733 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
734 && RTCrX509Certificate_IsSelfSigned(&Certificate)
735 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
736 pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
737 if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
738 {
739 Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
740 RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
741 rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
742 if (RT_FAILURE(rc))
743 RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
744 RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
745 }
746 else
747 RTMsgWarning("No key identifier found or has zero length.");
748
749 /* Subject */
750 if (RT_SUCCESS(rc))
751 {
752 Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
753 rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
754 if (RT_SUCCESS(rc))
755 {
756 Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
757 RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
758 rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
759 &g_RTAsn1DefaultAllocator);
760 if (RT_SUCCESS(rc))
761 {
762 RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
763 rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
764 if (RT_FAILURE(rc))
765 RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
766 }
767 else
768 RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
769 }
770 else
771 RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
772 }
773
774 /* Check that what we've constructed makes some sense. */
775 if (RT_SUCCESS(rc))
776 {
777 rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
778 if (RT_FAILURE(rc))
779 RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
780 }
781
782 if (RT_SUCCESS(rc))
783 {
784 /*
785 * Encode it and write it to the output file.
786 */
787 uint32_t cbEncoded;
788 rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
789 RTErrInfoInitStatic(&StaticErrInfo));
790 if (RT_SUCCESS(rc))
791 {
792 if (State.cVerbose >= 1)
793 RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
794
795 PRTSTREAM pStrm;
796 rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
797 if (RT_SUCCESS(rc))
798 {
799 rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
800 handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
801 if (RT_SUCCESS(rc))
802 {
803 rc = RTStrmClose(pStrm);
804 if (RT_SUCCESS(rc))
805 RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
806 else
807 RTMsgError("RTStrmClose failed: %Rrc", rc);
808 }
809 else
810 {
811 RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
812 RTStrmClose(pStrm);
813 }
814 }
815 else
816 RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
817 }
818 else
819 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
820 }
821
822 RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
823 }
824 else
825 RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
826
827 RTCrX509Certificate_Delete(&Certificate);
828 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
829}
830
831
832
833/*
834 * The 'version' command.
835 */
836static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
837{
838 RT_NOREF_PV(enmLevel);
839 RTStrmPrintf(pStrm, "version\n");
840 return RTEXITCODE_SUCCESS;
841}
842
843static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
844{
845 RT_NOREF_PV(cArgs); RT_NOREF_PV(papszArgs);
846#ifndef IN_BLD_PROG /* RTBldCfgVersion or RTBldCfgRevision in build time IPRT lib. */
847 RTPrintf("%s\n", RTBldCfgVersion());
848 return RTEXITCODE_SUCCESS;
849#else
850 return RTEXITCODE_FAILURE;
851#endif
852}
853
854
855
856/**
857 * Command mapping.
858 */
859static struct
860{
861 /** The command. */
862 const char *pszCmd;
863 /**
864 * Handle the command.
865 * @returns Program exit code.
866 * @param cArgs Number of arguments.
867 * @param papszArgs The argument vector, starting with the command name.
868 */
869 RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
870 /**
871 * Produce help.
872 * @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
873 * @param pStrm Where to send help text.
874 * @param enmLevel The level of the help information.
875 */
876 RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
877}
878/** Mapping commands to handler and helper functions. */
879const g_aCommands[] =
880{
881 { "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
882#ifndef IPRT_IN_BUILD_TOOL
883 { "verify-exe", HandleVerifyExe, HelpVerifyExe },
884#endif
885 { "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
886 { "help", HandleHelp, HelpHelp },
887 { "--help", HandleHelp, NULL },
888 { "-h", HandleHelp, NULL },
889 { "version", HandleVersion, HelpVersion },
890 { "--version", HandleVersion, NULL },
891 { "-V", HandleVersion, NULL },
892};
893
894
895/*
896 * The 'help' command.
897 */
898static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
899{
900 RT_NOREF_PV(enmLevel);
901 RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
902 return RTEXITCODE_SUCCESS;
903}
904
905static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
906{
907 RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
908 uint32_t cShowed = 0;
909 for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
910 {
911 if (g_aCommands[iCmd].pfnHelp)
912 {
913 bool fShow = false;
914 if (cArgs <= 1)
915 fShow = true;
916 else
917 {
918 for (int iArg = 1; iArg < cArgs; iArg++)
919 if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
920 {
921 fShow = true;
922 break;
923 }
924 }
925 if (fShow)
926 {
927 g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel);
928 cShowed++;
929 }
930 }
931 }
932 return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
933}
934
935
936
937int main(int argc, char **argv)
938{
939 int rc = RTR3InitExe(argc, &argv, 0);
940 if (RT_FAILURE(rc))
941 return RTMsgInitFailure(rc);
942
943 /*
944 * Parse global arguments.
945 */
946 int iArg = 1;
947 /* none presently. */
948
949 /*
950 * Command dispatcher.
951 */
952 if (iArg < argc)
953 {
954 const char *pszCmd = argv[iArg];
955 uint32_t i = RT_ELEMENTS(g_aCommands);
956 while (i-- > 0)
957 if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
958 return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
959 RTMsgError("Unknown command '%s'.", pszCmd);
960 }
961 else
962 RTMsgError("No command given. (try --help)");
963
964 return RTEXITCODE_SYNTAX;
965}
966
967
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette