RTSignTool.cpp revision 112958fbf92315189a6b038cbd3e8ef77e12f583
10139N/A/* $Id$ */
10139N/A/** @file
10139N/A * IPRT - Signing Tool.
12153N/A */
10139N/A
10139N/A/*
10139N/A * Copyright (C) 2006-2014 Oracle Corporation
10139N/A *
10139N/A * This file is part of VirtualBox Open Source Edition (OSE), as
10139N/A * available from http://www.virtualbox.org. This file is free software;
10139N/A * you can redistribute it and/or modify it under the terms of the GNU
10139N/A * General Public License (GPL) as published by the Free Software
13312N/A * Foundation, in version 2 as it comes in the "COPYING" file of the
10139N/A * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
10139N/A * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
10139N/A *
10139N/A * The contents of this file may alternatively be used under the terms
13312N/A * of the Common Development and Distribution License Version 1.0
12773N/A * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
12773N/A * VirtualBox OSE distribution, in which case the provisions of the
12773N/A * CDDL are applicable instead of those of the GPL.
11389N/A *
11248N/A * You may elect to license modified versions of this file under the
11963N/A * terms and conditions of either the GPL or the CDDL or both.
11412N/A */
13451N/A
12916N/A
13451N/A/*******************************************************************************
13451N/A* Header Files *
12916N/A*******************************************************************************/
10139N/A#include <iprt/assert.h>
10139N/A#include <iprt/buildconfig.h>
10139N/A#include <iprt/err.h>
10139N/A#include <iprt/getopt.h>
10139N/A#include <iprt/file.h>
10139N/A#include <iprt/initterm.h>
10139N/A#include <iprt/ldr.h>
10139N/A#include <iprt/message.h>
10139N/A#include <iprt/mem.h>
10139N/A#include <iprt/path.h>
10139N/A#include <iprt/stream.h>
10139N/A#include <iprt/string.h>
10139N/A#include <iprt/crypto/x509.h>
10139N/A#include <iprt/crypto/pkcs7.h>
10139N/A#include <iprt/crypto/store.h>
10139N/A#ifdef VBOX
10139N/A# include <VBox/sup.h> /* Certificates */
10139N/A#endif
10139N/A
10139N/A
10139N/A/*******************************************************************************
10139N/A* Structures and Typedefs *
10139N/A*******************************************************************************/
10139N/A/** Help detail levels. */
10139N/Atypedef enum RTSIGNTOOLHELP
10139N/A{
10139N/A RTSIGNTOOLHELP_USAGE,
10139N/A RTSIGNTOOLHELP_FULL
10139N/A} RTSIGNTOOLHELP;
10139N/A
10139N/A
10139N/A/*******************************************************************************
10139N/A* Internal Functions *
10139N/A*******************************************************************************/
10139N/Astatic RTEXITCODE HandleHelp(int cArgs, char **papszArgs);
10139N/Astatic RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
10139N/Astatic RTEXITCODE HandleVersion(int cArgs, char **papszArgs);
10139N/A
10139N/A
10139N/A
10139N/A
10139N/A/*
10139N/A * The 'extract-exe-signer-cert' command.
10139N/A */
10139N/Astatic RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
10139N/A{
10139N/A RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
10139N/A return RTEXITCODE_SUCCESS;
10139N/A}
10139N/A
11248N/Astatic RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
11412N/A{
13451N/A /*
13451N/A * Parse arguments.
13451N/A */
10139N/A static const RTGETOPTDEF s_aOptions[] =
10139N/A {
10139N/A { "--ber", 'b', RTGETOPT_REQ_NOTHING },
10139N/A { "--cer", 'c', RTGETOPT_REQ_NOTHING },
10139N/A { "--der", 'd', RTGETOPT_REQ_NOTHING },
10139N/A { "--exe", 'e', RTGETOPT_REQ_STRING },
10139N/A { "--output", 'o', RTGETOPT_REQ_STRING },
10139N/A };
10139N/A
10139N/A const char *pszExe = NULL;
10139N/A const char *pszOut = NULL;
10139N/A RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
10139N/A uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
10139N/A
10139N/A RTGETOPTSTATE GetState;
10139N/A int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
12773N/A AssertRCReturn(rc, RTEXITCODE_FAILURE);
12773N/A RTGETOPTUNION ValueUnion;
12773N/A int ch;
12773N/A while ((ch = RTGetOpt(&GetState, &ValueUnion)))
12773N/A {
10139N/A switch (ch)
10139N/A {
10139N/A case 'e': pszExe = ValueUnion.psz; break;
10139N/A case 'o': pszOut = ValueUnion.psz; break;
10139N/A case 'b': fCursorFlags = 0; break;
10139N/A case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
10139N/A case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
10139N/A case 'V': return HandleVersion(cArgs, papszArgs);
10139N/A case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
10139N/A
10139N/A case VINF_GETOPT_NOT_OPTION:
10139N/A if (!pszExe)
10139N/A pszExe = ValueUnion.psz;
10139N/A else if (!pszOut)
13059N/A pszOut = ValueUnion.psz;
10139N/A else
10139N/A return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
10139N/A break;
10139N/A
10139N/A default:
10139N/A return RTGetOptPrintError(ch, &ValueUnion);
10139N/A }
10139N/A }
10139N/A if (!pszExe)
12252N/A return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
12252N/A if (!pszOut)
12252N/A return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
12252N/A if (RTPathExists(pszOut))
12252N/A return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
12252N/A
12252N/A /*
12252N/A * Do it.
10139N/A */
10139N/A
10139N/A /* Open the executable image and query the PKCS7 info. */
10139N/A RTLDRMOD hLdrMod;
10139N/A rc = RTLdrOpen(pszExe, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod);
10139N/A if (RT_FAILURE(rc))
10139N/A return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszExe, rc);
10139N/A
10139N/A RTEXITCODE rcExit = RTEXITCODE_FAILURE;
10139N/A#ifdef DEBUG
10139N/A size_t cbBuf = 64;
10139N/A#else
10139N/A size_t cbBuf = _512K;
10139N/A#endif
10139N/A void *pvBuf = RTMemAlloc(cbBuf);
13312N/A size_t cbRet = 0;
13312N/A rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, pvBuf, cbBuf, &cbRet);
13312N/A if (rc == VERR_BUFFER_OVERFLOW && cbRet < _4M && cbRet > 0)
13312N/A {
13059N/A RTMemFree(pvBuf);
13059N/A cbBuf = cbRet;
13059N/A pvBuf = RTMemAlloc(cbBuf);
13059N/A rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, pvBuf, cbBuf, &cbRet);
12923N/A }
12916N/A if (RT_SUCCESS(rc))
12916N/A {
12916N/A static RTERRINFOSTATIC s_StaticErrInfo;
12813N/A RTErrInfoInitStatic(&s_StaticErrInfo);
12813N/A
12813N/A /*
12625N/A * Decode the output.
12625N/A */
12625N/A RTASN1CURSORPRIMARY PrimaryCursor;
12571N/A RTAsn1CursorInitPrimary(&PrimaryCursor, pvBuf, (uint32_t)cbRet, &s_StaticErrInfo.Core,
12571N/A &g_RTAsn1DefaultAllocator, fCursorFlags, "exe");
12571N/A RTCRPKCS7CONTENTINFO Pkcs7Ci;
12288N/A rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &Pkcs7Ci, "pkcs7");
12295N/A if (RT_SUCCESS(rc))
12288N/A {
12252N/A if (RTCrPkcs7ContentInfo_IsSignedData(&Pkcs7Ci))
12252N/A {
12252N/A PCRTCRPKCS7SIGNEDDATA pSd = Pkcs7Ci.u.pSignedData;
12252N/A if (pSd->SignerInfos.cItems == 1)
12153N/A {
12153N/A PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSd->SignerInfos.paItems[0].IssuerAndSerialNumber;
12024N/A PCRTCRX509CERTIFICATE pCert;
12024N/A pCert = RTCrX509Certificates_FindByIssuerAndSerialNumber(&pSd->Certificates,
12024N/A &pISN->Name, &pISN->SerialNumber);
12022N/A if (pCert)
12022N/A {
12022N/A /*
11412N/A * Write it out.
11412N/A */
11412N/A RTFILE hFile;
11240N/A rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE);
11240N/A if (RT_SUCCESS(rc))
11248N/A {
11240N/A uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
11069N/A rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
11069N/A cbCert, NULL);
11069N/A if (RT_SUCCESS(rc))
11069N/A {
10985N/A rc = RTFileClose(hFile);
10985N/A if (RT_SUCCESS(rc))
10985N/A {
10980N/A hFile = NIL_RTFILE;
10980N/A rcExit = RTEXITCODE_SUCCESS;
10980N/A RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut);
10980N/A }
10793N/A else
10793N/A RTMsgError("RTFileClose failed: %Rrc", rc);
10793N/A }
10473N/A else
10473N/A RTMsgError("RTFileWrite failed: %Rrc", rc);
10473N/A RTFileClose(hFile);
10473N/A }
10453N/A else
10453N/A RTMsgError("Error opening '%s': %Rrc", pszOut, rc);
10453N/A }
10280N/A else
10280N/A RTMsgError("Certificate not found.");
10280N/A }
10139N/A else
10139N/A RTMsgError("SignerInfo count: %u", pSd->SignerInfos.cItems);
10139N/A }
10139N/A else
10139N/A RTMsgError("No PKCS7 content: ContentType=%s", Pkcs7Ci.ContentType.szObjId);
10139N/A RTAsn1VtDelete(&Pkcs7Ci.SeqCore.Asn1Core);
10139N/A }
10139N/A else
10139N/A RTMsgError("RTPkcs7ContentInfoDecodeAsn1 failed: %Rrc - %s", rc, s_StaticErrInfo.szMsg);
10139N/A }
10139N/A else
10139N/A RTMsgError("RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc", pszExe, rc);
10139N/A RTMemFree(pvBuf);
10139N/A rc = RTLdrClose(hLdrMod);
10139N/A if (RT_FAILURE(rc))
10139N/A rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc);
10139N/A return rcExit;
10139N/A}
10139N/A
10139N/A#ifndef IPRT_IN_BUILD_TOOL
10139N/A
10139N/A/*
10139N/A * The 'verify-exe' command.
10139N/A */
10139N/Astatic RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
10139N/A{
10139N/A RTStrmPrintf(pStrm,
10139N/A "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n"
10139N/A " [--type <win|osx>] <exe1> [exe2 [..]]\n");
10139N/A return RTEXITCODE_SUCCESS;
10139N/A}
10139N/A
10139N/Atypedef struct VERIFYEXESTATE
10139N/A{
10139N/A RTCRSTORE hRootStore;
10139N/A RTCRSTORE hKernelRootStore;
10139N/A RTCRSTORE hAdditionalStore;
10139N/A bool fKernel;
10139N/A int cVerbose;
10139N/A enum { kSignType_Windows, kSignType_OSX } enmSignType;
10139N/A uint64_t uTimestamp;
10139N/A} VERIFYEXESTATE;
10139N/A
10139N/A
10139N/A/**
10139N/A * @callback_method_impl{RTCRPKCS7VERIFYCERTCALLBACK,
10139N/A * Standard code signing. Use this for Microsoft SPC.}
10139N/A */
10139N/Astatic DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths,
10139N/A void *pvUser, PRTERRINFO pErrInfo)
10139N/A{
10139N/A VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
10139N/A uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0;
10139N/A
10139N/A /*
10139N/A * Dump all the paths.
10139N/A */
10139N/A if (pState->cVerbose > 0)
10139N/A {
10139N/A for (uint32_t iPath = 0; iPath < cPaths; iPath++)
10139N/A {
10139N/A RTPrintf("---\n");
10139N/A RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
10139N/A *pErrInfo->pszMsg = '\0';
10139N/A }
10139N/A RTPrintf("---\n");
10139N/A }
10139N/A
10139N/A /*
10139N/A * Test signing certificates normally doesn't have all the necessary
10139N/A * features required below. So, treat them as special cases.
10139N/A */
10139N/A if ( hCertPaths == NIL_RTCRX509CERTPATHS
10139N/A && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
10139N/A {
10139N/A RTMsgInfo("Test signed.\n");
10139N/A return VINF_SUCCESS;
10139N/A }
10139N/A
10139N/A if (hCertPaths == NIL_RTCRX509CERTPATHS)
10139N/A RTMsgInfo("Signed by trusted certificate.\n");
10139N/A
10139N/A /*
10139N/A * Standard code signing capabilites required.
10139N/A */
10139N/A int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, NULL, pErrInfo);
10139N/A if (RT_SUCCESS(rc))
10139N/A {
10139N/A /*
10139N/A * If kernel signing, a valid certificate path must be anchored by the
10139N/A * microsoft kernel signing root certificate. The only alternative is
10139N/A * test signing.
10139N/A */
10139N/A if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS)
10139N/A {
10139N/A uint32_t cFound = 0;
10139N/A uint32_t cValid = 0;
10139N/A for (uint32_t iPath = 0; iPath < cPaths; iPath++)
10139N/A {
10139N/A bool fTrusted;
10139N/A PCRTCRX509NAME pSubject;
10139N/A PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
10139N/A int rcVerify;
10139N/A rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
10139N/A NULL, NULL /*pCertCtx*/, &rcVerify);
10139N/A AssertRCBreak(rc);
10139N/A
10139N/A if (RT_SUCCESS(rcVerify))
10139N/A {
10139N/A Assert(fTrusted);
10139N/A cValid++;
10139N/A
10139N/A /* Search the kernel signing root store for a matching anchor. */
10139N/A RTCRSTORECERTSEARCH Search;
10139N/A rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search);
10139N/A AssertRCBreak(rc);
10139N/A PCRTCRCERTCTX pCertCtx;
10139N/A while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL)
10139N/A {
10139N/A if (RTCrX509SubjectPublicKeyInfo_Compare(&pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo,
10139N/A pPublicKeyInfo) == 0)
10139N/A cFound++;
10139N/A RTCrCertCtxRelease(pCertCtx);
10139N/A }
10139N/A
10139N/A int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2);
10139N/A }
10139N/A }
10139N/A if (RT_SUCCESS(rc) && cFound == 0)
10139N/A rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
10139N/A if (RT_SUCCESS(rc) && cValid != 2)
10139N/A RTMsgWarning("%u valid paths, expected 2", cValid);
10139N/A }
10139N/A }
10139N/A
10139N/A return rc;
10139N/A}
10139N/A
10139N/A
10139N/A/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
10139N/Astatic DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
10139N/A void const *pvSignature, size_t cbSignature,
10139N/A PRTERRINFO pErrInfo, void *pvUser)
10139N/A{
10139N/A VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
10139N/A switch (enmSignature)
10139N/A {
10139N/A case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
10139N/A {
10139N/A PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
10139N/A
10139N/A RTTIMESPEC ValidationTime;
10139N/A RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp);
10139N/A
10139N/A /*
10139N/A * Dump the signed data if so requested.
10139N/A */
10139N/A if (pState->cVerbose)
RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
/*
* Do the actual verification. Will have to modify this so it takes
* the authenticode policies into account.
*/
return RTCrPkcs7VerifySignedData(pContentInfo, 0, pState->hAdditionalStore, pState->hRootStore, &ValidationTime,
VerifyExecCertVerifyCallback, pState, pErrInfo);
}
default:
return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature);
}
return VINF_SUCCESS;
}
static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
{
RTERRINFOSTATIC StaticErrInfo;
/* Note! This code does not try to clean up the crypto stores on failure.
This is intentional as the code is only expected to be used in a
one-command-per-process environment where we do exit() upon
returning from this function. */
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--kernel", 'k', RTGETOPT_REQ_NOTHING },
{ "--root", 'r', RTGETOPT_REQ_STRING },
{ "--additional", 'a', RTGETOPT_REQ_STRING },
{ "--add", 'a', RTGETOPT_REQ_STRING },
{ "--type", 't', RTGETOPT_REQ_STRING },
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING },
{ "--quiet", 'q', RTGETOPT_REQ_NOTHING },
};
RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
VERIFYEXESTATE State = { NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false, VERIFYEXESTATE::kSignType_Windows };
int rc = RTCrStoreCreateInMem(&State.hRootStore, 0);
if (RT_SUCCESS(rc))
rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0);
if (RT_SUCCESS(rc))
rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
RTGETOPTSTATE GetState;
rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
AssertRCReturn(rc, RTEXITCODE_FAILURE);
RTGETOPTUNION ValueUnion;
int ch;
while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
{
switch (ch)
{
case 'r': case 'a':
rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore, 0, ValueUnion.psz,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s",
ValueUnion.psz, rc, StaticErrInfo.szMsg);
break;
case 't':
if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
else
return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
break;
case 'k': State.fKernel = true; break;
case 'v': State.cVerbose++; break;
case 'q': State.cVerbose = 0; break;
case 'V': return HandleVersion(cArgs, papszArgs);
case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
default: return RTGetOptPrintError(ch, &ValueUnion);
}
}
if (ch != VINF_GETOPT_NOT_OPTION)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
/*
* Populate the certificate stores according to the signing type.
*/
#ifdef VBOX
unsigned cSets = 0;
struct STORESET { RTCRSTORE hStore; PCSUPTAENTRY paTAs; unsigned cTAs; } aSets[6];
#endif
switch (State.enmSignType)
{
case VERIFYEXESTATE::kSignType_Windows:
#ifdef VBOX
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPTimestampTAs;
aSets[cSets].cTAs = g_cSUPTimestampTAs;
cSets++;
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPSpcRootTAs;
aSets[cSets].cTAs = g_cSUPSpcRootTAs;
cSets++;
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
cSets++;
aSets[cSets].hStore = State.hKernelRootStore;
aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
cSets++;
#endif
break;
case VERIFYEXESTATE::kSignType_OSX:
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented.");
}
#ifdef VBOX
for (unsigned i = 0; i < cSets; i++)
for (unsigned j = 0; j < aSets[i].cTAs; j++)
{
rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
i, j, StaticErrInfo.szMsg);
}
#endif
/*
* Do it.
*/
for (;;)
{
/*
* Open the executable image and verify it.
*/
RTLDRMOD hLdrMod;
rc = RTLdrOpen(ValueUnion.psz, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", ValueUnion.psz, rc);
rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &State.uTimestamp, sizeof(State.uTimestamp));
if (RT_SUCCESS(rc))
{
rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, &State, RTErrInfoInitStatic(&StaticErrInfo));
if (RT_SUCCESS(rc))
RTMsgInfo("'%s' is valid.\n", ValueUnion.psz);
else
RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", ValueUnion.psz, rc, StaticErrInfo.szMsg);
}
else
RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", ValueUnion.psz, rc);
int rc2 = RTLdrClose(hLdrMod);
if (RT_FAILURE(rc2))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
if (RT_FAILURE(rc))
return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
/*
* Next file
*/
ch = RTGetOpt(&GetState, &ValueUnion);
if (ch == 0)
return RTEXITCODE_SUCCESS;
if (ch != VINF_GETOPT_NOT_OPTION)
return RTGetOptPrintError(ch, &ValueUnion);
}
}
#endif /* !IPRT_IN_BUILD_TOOL */
/*
* The 'make-tainfo' command.
*/
static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm,
"make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
return RTEXITCODE_SUCCESS;
}
typedef struct MAKETAINFOSTATE
{
int cVerbose;
const char *pszCert;
const char *pszOutput;
} MAKETAINFOSTATE;
/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
{
return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
}
static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
{
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--cert", 'c', RTGETOPT_REQ_STRING },
{ "--output", 'o', RTGETOPT_REQ_STRING },
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING },
{ "--quiet", 'q', RTGETOPT_REQ_NOTHING },
};
RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
MAKETAINFOSTATE State = { 0, NULL, NULL };
RTGETOPTSTATE GetState;
int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
AssertRCReturn(rc, RTEXITCODE_FAILURE);
RTGETOPTUNION ValueUnion;
int ch;
while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
{
switch (ch)
{
case 'c':
if (State.pszCert)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
State.pszCert = ValueUnion.psz;
break;
case 'o':
case VINF_GETOPT_NOT_OPTION:
if (State.pszOutput)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
State.pszOutput = ValueUnion.psz;
break;
case 'v': State.cVerbose++; break;
case 'q': State.cVerbose = 0; break;
case 'V': return HandleVersion(cArgs, papszArgs);
case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
default: return RTGetOptPrintError(ch, &ValueUnion);
}
}
if (!State.pszCert)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
if (!State.pszOutput)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
/*
* Read the certificate.
*/
RTERRINFOSTATIC StaticErrInfo;
RTCRX509CERTIFICATE Certificate;
rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
State.pszCert, rc, StaticErrInfo.szMsg);
/*
* Construct the trust anchor information.
*/
RTCRTAFTRUSTANCHORINFO TrustAnchor;
rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
/* Public key. */
Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
&g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
/* Key Identifier. */
PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
&& RTCrX509Certificate_IsSelfSigned(&Certificate)
&& RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
&& RTCrX509Certificate_IsSelfSigned(&Certificate)
&& RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
{
Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
}
else
RTMsgWarning("No key identifier found or has zero length.");
/* Subject */
if (RT_SUCCESS(rc))
{
Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
&g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
}
else
RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
}
else
RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
}
/* Check that what we've constructed makes some sense. */
if (RT_SUCCESS(rc))
{
rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
if (RT_FAILURE(rc))
RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
}
if (RT_SUCCESS(rc))
{
/*
* Encode it and write it to the output file.
*/
uint32_t cbEncoded;
rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_SUCCESS(rc))
{
if (State.cVerbose >= 1)
RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
PRTSTREAM pStrm;
rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
if (RT_SUCCESS(rc))
{
rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
if (RT_SUCCESS(rc))
{
rc = RTStrmClose(pStrm);
if (RT_SUCCESS(rc))
RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
else
RTMsgError("RTStrmClose failed: %Rrc");
}
else
{
RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
RTStrmClose(pStrm);
}
}
else
RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
}
else
RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
}
RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
}
else
RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
RTCrX509Certificate_Delete(&Certificate);
return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
/*
* The 'version' command.
*/
static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm, "version\n");
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
{
RTPrintf("%s\n", RTBldCfgVersion());
return RTEXITCODE_SUCCESS;
}
/**
* Command mapping.
*/
static struct
{
/** The command. */
const char *pszCmd;
/**
* Handle the command.
* @returns Program exit code.
* @param cArgs Number of arguments.
* @param papszArgs The argument vector, starting with the command name.
*/
RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
/**
* Produce help.
* @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
* @param pStrm Where to send help text.
* @param enmLevel The level of the help information.
*/
RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
}
/** Mapping commands to handler and helper functions. */
const g_aCommands[] =
{
{ "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
#ifndef IPRT_IN_BUILD_TOOL
{ "verify-exe", HandleVerifyExe, HelpVerifyExe },
#endif
{ "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
{ "help", HandleHelp, HelpHelp },
{ "--help", HandleHelp, NULL },
{ "-h", HandleHelp, NULL },
{ "version", HandleVersion, HelpVersion },
{ "--version", HandleVersion, NULL },
{ "-V", HandleVersion, NULL },
};
/*
* The 'help' command.
*/
static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
{
RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
uint32_t cShowed = 0;
for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
{
if (g_aCommands[iCmd].pfnHelp)
{
bool fShow;
if (cArgs <= 1)
fShow = true;
else
{
for (int iArg = 1; iArg < cArgs; iArg++)
if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
{
fShow = true;
break;
}
}
if (fShow)
{
g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel);
cShowed++;
}
}
}
return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
int main(int argc, char **argv)
{
int rc = RTR3InitExe(argc, &argv, 0);
if (RT_FAILURE(rc))
return RTMsgInitFailure(rc);
/*
* Parse global arguments.
*/
int iArg = 1;
/* none presently. */
/*
* Command dispatcher.
*/
if (iArg < argc)
{
const char *pszCmd = argv[iArg];
uint32_t i = RT_ELEMENTS(g_aCommands);
while (i-- > 0)
if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
RTMsgError("Unknown command '%s'.", pszCmd);
}
else
RTMsgError("No command given. (try --help)");
return RTEXITCODE_SYNTAX;
}