VirtualBox

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

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

(C) 2016

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