VirtualBox

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

Last change on this file since 74672 was 74672, checked in by vboxsync, 6 years ago

IPRT/asn1: Hacked code into handling the necessary indefinite length stuff from apple. bugref:9232

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 105.6 KB
Line 
1/* $Id: RTSignTool.cpp 74672 2018-10-08 12:08:51Z vboxsync $ */
2/** @file
3 * IPRT - Signing Tool.
4 */
5
6/*
7 * Copyright (C) 2006-2017 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/uuid.h>
44#include <iprt/zero.h>
45#ifndef RT_OS_WINDOWS
46# include <iprt/formats/pecoff.h>
47#endif
48#include <iprt/crypto/digest.h>
49#include <iprt/crypto/x509.h>
50#include <iprt/crypto/pkcs7.h>
51#include <iprt/crypto/store.h>
52#include <iprt/crypto/spc.h>
53#ifdef VBOX
54# include <VBox/sup.h> /* Certificates */
55#endif
56#ifdef RT_OS_WINDOWS
57# include <iprt/win/windows.h>
58# include <ImageHlp.h>
59#endif
60
61
62/*********************************************************************************************************************************
63* Structures and Typedefs *
64*********************************************************************************************************************************/
65/** Help detail levels. */
66typedef enum RTSIGNTOOLHELP
67{
68 RTSIGNTOOLHELP_USAGE,
69 RTSIGNTOOLHELP_FULL
70} RTSIGNTOOLHELP;
71
72
73/**
74 * PKCS\#7 signature data.
75 */
76typedef struct SIGNTOOLPKCS7
77{
78 /** The raw signature. */
79 uint8_t *pbBuf;
80 /** Size of the raw signature. */
81 size_t cbBuf;
82 /** The filename. */
83 const char *pszFilename;
84 /** The outer content info wrapper. */
85 RTCRPKCS7CONTENTINFO ContentInfo;
86 /** Pointer to the decoded SignedData inside the ContentInfo member. */
87 PRTCRPKCS7SIGNEDDATA pSignedData;
88 /** Pointer to the indirect data content. */
89 PRTCRSPCINDIRECTDATACONTENT pIndData;
90
91 /** Newly encoded raw signature.
92 * @sa SignToolPkcs7_Encode() */
93 uint8_t *pbNewBuf;
94 /** Size of newly encoded raw signature. */
95 size_t cbNewBuf;
96
97} SIGNTOOLPKCS7;
98typedef SIGNTOOLPKCS7 *PSIGNTOOLPKCS7;
99
100
101/**
102 * PKCS\#7 signature data for executable.
103 */
104typedef struct SIGNTOOLPKCS7EXE : public SIGNTOOLPKCS7
105{
106 /** The module handle. */
107 RTLDRMOD hLdrMod;
108} SIGNTOOLPKCS7EXE;
109typedef SIGNTOOLPKCS7EXE *PSIGNTOOLPKCS7EXE;
110
111
112/**
113 * Data for the show exe (signature) command.
114 */
115typedef struct SHOWEXEPKCS7 : public SIGNTOOLPKCS7EXE
116{
117 /** The verbosity. */
118 unsigned cVerbosity;
119 /** The prefix buffer. */
120 char szPrefix[256];
121 /** Temporary buffer. */
122 char szTmp[4096];
123} SHOWEXEPKCS7;
124typedef SHOWEXEPKCS7 *PSHOWEXEPKCS7;
125
126
127/*********************************************************************************************************************************
128* Internal Functions *
129*********************************************************************************************************************************/
130static RTEXITCODE HandleHelp(int cArgs, char **papszArgs);
131static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
132static RTEXITCODE HandleVersion(int cArgs, char **papszArgs);
133static int HandleShowExeWorkerPkcs7Display(PSHOWEXEPKCS7 pThis, PRTCRPKCS7SIGNEDDATA pSignedData, size_t offPrefix,
134 PCRTCRPKCS7CONTENTINFO pContentInfo);
135
136
137/**
138 * Deletes the structure.
139 *
140 * @param pThis The structure to initialize.
141 */
142static void SignToolPkcs7_Delete(PSIGNTOOLPKCS7 pThis)
143{
144 RTCrPkcs7ContentInfo_Delete(&pThis->ContentInfo);
145 pThis->pIndData = NULL;
146 pThis->pSignedData = NULL;
147 pThis->pIndData = NULL;
148 RTMemFree(pThis->pbBuf);
149 pThis->pbBuf = NULL;
150 pThis->cbBuf = 0;
151 RTMemFree(pThis->pbNewBuf);
152 pThis->pbNewBuf = NULL;
153 pThis->cbNewBuf = 0;
154}
155
156
157/**
158 * Deletes the structure.
159 *
160 * @param pThis The structure to initialize.
161 */
162static void SignToolPkcs7Exe_Delete(PSIGNTOOLPKCS7EXE pThis)
163{
164 if (pThis->hLdrMod != NIL_RTLDRMOD)
165 {
166 int rc2 = RTLdrClose(pThis->hLdrMod);
167 if (RT_FAILURE(rc2))
168 RTMsgError("RTLdrClose failed: %Rrc\n", rc2);
169 pThis->hLdrMod = NIL_RTLDRMOD;
170 }
171 SignToolPkcs7_Delete(pThis);
172}
173
174
175/**
176 * Decodes the PKCS #7 blob pointed to by pThis->pbBuf.
177 *
178 * @returns IPRT status code (error message already shown on failure).
179 * @param pThis The PKCS\#7 signature to decode.
180 * @param fCatalog Set if catalog file, clear if executable.
181 */
182static int SignToolPkcs7_Decode(PSIGNTOOLPKCS7 pThis, bool fCatalog)
183{
184 RTERRINFOSTATIC ErrInfo;
185 RTASN1CURSORPRIMARY PrimaryCursor;
186 RTAsn1CursorInitPrimary(&PrimaryCursor, pThis->pbBuf, (uint32_t)pThis->cbBuf, RTErrInfoInitStatic(&ErrInfo),
187 &g_RTAsn1DefaultAllocator, 0, "WinCert");
188
189 int rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &pThis->ContentInfo, "CI");
190 if (RT_SUCCESS(rc))
191 {
192 if (RTCrPkcs7ContentInfo_IsSignedData(&pThis->ContentInfo))
193 {
194 pThis->pSignedData = pThis->ContentInfo.u.pSignedData;
195
196 /*
197 * Decode the authenticode bits.
198 */
199 if (!strcmp(pThis->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID))
200 {
201 pThis->pIndData = pThis->pSignedData->ContentInfo.u.pIndirectDataContent;
202 Assert(pThis->pIndData);
203
204 /*
205 * Check that things add up.
206 */
207 rc = RTCrPkcs7SignedData_CheckSanity(pThis->pSignedData,
208 RTCRPKCS7SIGNEDDATA_SANITY_F_AUTHENTICODE
209 | RTCRPKCS7SIGNEDDATA_SANITY_F_ONLY_KNOWN_HASH
210 | RTCRPKCS7SIGNEDDATA_SANITY_F_SIGNING_CERT_PRESENT,
211 RTErrInfoInitStatic(&ErrInfo), "SD");
212 if (RT_SUCCESS(rc))
213 {
214 rc = RTCrSpcIndirectDataContent_CheckSanityEx(pThis->pIndData,
215 pThis->pSignedData,
216 RTCRSPCINDIRECTDATACONTENT_SANITY_F_ONLY_KNOWN_HASH,
217 RTErrInfoInitStatic(&ErrInfo));
218 if (RT_FAILURE(rc))
219 RTMsgError("SPC indirect data content sanity check failed for '%s': %Rrc - %s\n",
220 pThis->pszFilename, rc, ErrInfo.szMsg);
221 }
222 else
223 RTMsgError("PKCS#7 sanity check failed for '%s': %Rrc - %s\n", pThis->pszFilename, rc, ErrInfo.szMsg);
224 }
225 else if (!fCatalog)
226 RTMsgError("Unexpected the signed content in '%s': %s (expected %s)", pThis->pszFilename,
227 pThis->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID);
228 }
229 else
230 rc = RTMsgErrorRc(VERR_CR_PKCS7_NOT_SIGNED_DATA,
231 "PKCS#7 content is inside '%s' is not 'signedData': %s\n",
232 pThis->pszFilename, pThis->ContentInfo.ContentType.szObjId);
233 }
234 else
235 RTMsgError("RTCrPkcs7ContentInfo_DecodeAsn1 failed on '%s': %Rrc - %s\n", pThis->pszFilename, rc, ErrInfo.szMsg);
236 return rc;
237}
238
239
240/**
241 * Reads and decodes PKCS\#7 signature from the given cat file.
242 *
243 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
244 * on failure.
245 * @param pThis The structure to initialize.
246 * @param pszFilename The catalog (or any other DER PKCS\#7) filename.
247 * @param cVerbosity The verbosity.
248 */
249static RTEXITCODE SignToolPkcs7_InitFromFile(PSIGNTOOLPKCS7 pThis, const char *pszFilename, unsigned cVerbosity)
250{
251 /*
252 * Init the return structure.
253 */
254 RT_ZERO(*pThis);
255 pThis->pszFilename = pszFilename;
256
257 /*
258 * Lazy bird uses RTFileReadAll and duplicates the allocation.
259 */
260 void *pvFile;
261 int rc = RTFileReadAll(pszFilename, &pvFile, &pThis->cbBuf);
262 if (RT_SUCCESS(rc))
263 {
264 pThis->pbBuf = (uint8_t *)RTMemDup(pvFile, pThis->cbBuf);
265 RTFileReadAllFree(pvFile, pThis->cbBuf);
266 if (pThis->pbBuf)
267 {
268 if (cVerbosity > 2)
269 RTPrintf("PKCS#7 signature: %u bytes\n", pThis->cbBuf);
270
271 /*
272 * Decode it.
273 */
274 rc = SignToolPkcs7_Decode(pThis, true /*fCatalog*/);
275 if (RT_SUCCESS(rc))
276 return RTEXITCODE_SUCCESS;
277 }
278 else
279 RTMsgError("Out of memory!");
280 }
281 else
282 RTMsgError("Error reading '%s' into memory: %Rrc", pszFilename, rc);
283
284 SignToolPkcs7_Delete(pThis);
285 return RTEXITCODE_FAILURE;
286}
287
288
289/**
290 * Encodes the signature into the SIGNTOOLPKCS7::pbNewBuf and
291 * SIGNTOOLPKCS7::cbNewBuf members.
292 *
293 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
294 * on failure.
295 * @param pThis The signature to encode.
296 * @param cVerbosity The verbosity.
297 */
298static RTEXITCODE SignToolPkcs7_Encode(PSIGNTOOLPKCS7 pThis, unsigned cVerbosity)
299{
300 RTERRINFOSTATIC StaticErrInfo;
301 PRTASN1CORE pRoot = RTCrPkcs7ContentInfo_GetAsn1Core(&pThis->ContentInfo);
302 uint32_t cbEncoded;
303 int rc = RTAsn1EncodePrepare(pRoot, RTASN1ENCODE_F_DER, &cbEncoded, RTErrInfoInitStatic(&StaticErrInfo));
304 if (RT_SUCCESS(rc))
305 {
306 if (cVerbosity >= 4)
307 RTAsn1Dump(pRoot, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
308
309 RTMemFree(pThis->pbNewBuf);
310 pThis->cbNewBuf = cbEncoded;
311 pThis->pbNewBuf = (uint8_t *)RTMemAllocZ(cbEncoded);
312 if (pThis->pbNewBuf)
313 {
314 rc = RTAsn1EncodeToBuffer(pRoot, RTASN1ENCODE_F_DER, pThis->pbNewBuf, pThis->cbNewBuf,
315 RTErrInfoInitStatic(&StaticErrInfo));
316 if (RT_SUCCESS(rc))
317 {
318 if (cVerbosity > 1)
319 RTMsgInfo("Encoded signature to %u bytes", cbEncoded);
320 return RTEXITCODE_SUCCESS;
321 }
322 RTMsgError("RTAsn1EncodeToBuffer failed: %Rrc", rc);
323
324 RTMemFree(pThis->pbNewBuf);
325 pThis->pbNewBuf = NULL;
326 }
327 else
328 RTMsgError("Failed to allocate %u bytes!", cbEncoded);
329 }
330 else
331 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
332 return RTEXITCODE_FAILURE;
333}
334
335
336/**
337 * Adds the @a pSrc signature as a nested signature.
338 *
339 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
340 * on failure.
341 * @param pThis The signature to modify.
342 * @param pSrc The signature to add as nested.
343 * @param cVerbosity The verbosity.
344 * @param fPrepend Whether to prepend (true) or append (false) the
345 * source signature to the nested attribute.
346 */
347static RTEXITCODE SignToolPkcs7_AddNestedSignature(PSIGNTOOLPKCS7 pThis, PSIGNTOOLPKCS7 pSrc,
348 unsigned cVerbosity, bool fPrepend)
349{
350 PRTCRPKCS7SIGNERINFO pSignerInfo = pThis->pSignedData->SignerInfos.papItems[0];
351 int rc;
352
353 /*
354 * Deal with UnauthenticatedAttributes being absent before trying to append to the array.
355 */
356 if (pSignerInfo->UnauthenticatedAttributes.cItems == 0)
357 {
358 /* HACK ALERT! Invent ASN.1 setters/whatever for members to replace this mess. */
359
360 if (pSignerInfo->AuthenticatedAttributes.cItems == 0)
361 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No authenticated or unauthenticated attributes! Sorry, no can do.");
362
363 Assert(pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.uTag == 0);
364 rc = RTAsn1SetCore_Init(&pSignerInfo->UnauthenticatedAttributes.SetCore,
365 pSignerInfo->AuthenticatedAttributes.SetCore.Asn1Core.pOps);
366 if (RT_FAILURE(rc))
367 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTAsn1SetCore_Init failed: %Rrc", rc);
368 pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.uTag = 1;
369 pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.fClass = ASN1_TAGCLASS_CONTEXT | ASN1_TAGFLAG_CONSTRUCTED;
370 RTAsn1MemInitArrayAllocation(&pSignerInfo->UnauthenticatedAttributes.Allocation,
371 pSignerInfo->AuthenticatedAttributes.Allocation.pAllocator,
372 sizeof(**pSignerInfo->UnauthenticatedAttributes.papItems));
373 }
374
375 /*
376 * Find or add an unauthenticated attribute for nested signatures.
377 */
378 rc = VERR_NOT_FOUND;
379 PRTCRPKCS7ATTRIBUTE pAttr = NULL;
380 int32_t iPos = pSignerInfo->UnauthenticatedAttributes.cItems;
381 while (iPos-- > 0)
382 if (pSignerInfo->UnauthenticatedAttributes.papItems[iPos]->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE)
383 {
384 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
385 rc = VINF_SUCCESS;
386 break;
387 }
388 if (iPos < 0)
389 {
390 iPos = RTCrPkcs7Attributes_Append(&pSignerInfo->UnauthenticatedAttributes);
391 if (iPos >= 0)
392 {
393 if (cVerbosity >= 3)
394 RTMsgInfo("Adding UnauthenticatedAttribute #%u...", iPos);
395 Assert((uint32_t)iPos < pSignerInfo->UnauthenticatedAttributes.cItems);
396
397 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
398 rc = RTAsn1ObjId_InitFromString(&pAttr->Type, RTCR_PKCS9_ID_MS_NESTED_SIGNATURE, pAttr->Allocation.pAllocator);
399 if (RT_SUCCESS(rc))
400 {
401 /** @todo Generalize the Type + enmType DYN stuff and generate setters. */
402 Assert(pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_NOT_PRESENT);
403 Assert(pAttr->uValues.pContentInfos == NULL);
404 pAttr->enmType = RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE;
405 rc = RTAsn1MemAllocZ(&pAttr->Allocation, (void **)&pAttr->uValues.pContentInfos,
406 sizeof(*pAttr->uValues.pContentInfos));
407 if (RT_SUCCESS(rc))
408 {
409 rc = RTCrPkcs7SetOfContentInfos_Init(pAttr->uValues.pContentInfos, pAttr->Allocation.pAllocator);
410 if (!RT_SUCCESS(rc))
411 RTMsgError("RTCrPkcs7ContentInfos_Init failed: %Rrc", rc);
412 }
413 else
414 RTMsgError("RTAsn1MemAllocZ failed: %Rrc", rc);
415 }
416 else
417 RTMsgError("RTAsn1ObjId_InitFromString failed: %Rrc", rc);
418 }
419 else
420 RTMsgError("RTCrPkcs7Attributes_Append failed: %Rrc", iPos);
421 }
422 else if (cVerbosity >= 2)
423 RTMsgInfo("Found UnauthenticatedAttribute #%u...", iPos);
424 if (RT_SUCCESS(rc))
425 {
426 /*
427 * Append/prepend the signature.
428 */
429 uint32_t iActualPos = UINT32_MAX;
430 iPos = fPrepend ? 0 : pAttr->uValues.pContentInfos->cItems;
431 rc = RTCrPkcs7SetOfContentInfos_InsertEx(pAttr->uValues.pContentInfos, iPos, &pSrc->ContentInfo,
432 pAttr->Allocation.pAllocator, &iActualPos);
433 if (RT_SUCCESS(rc))
434 {
435 if (cVerbosity > 0)
436 RTMsgInfo("Added nested signature (#%u)", iActualPos);
437 if (cVerbosity >= 3)
438 {
439 RTMsgInfo("SingerInfo dump after change:");
440 RTAsn1Dump(RTCrPkcs7SignerInfo_GetAsn1Core(pSignerInfo), 0, 2, RTStrmDumpPrintfV, g_pStdOut);
441 }
442 return RTEXITCODE_SUCCESS;
443 }
444
445 RTMsgError("RTCrPkcs7ContentInfos_InsertEx failed: %Rrc", rc);
446 }
447 return RTEXITCODE_FAILURE;
448}
449
450
451/**
452 * Writes the signature to the file.
453 *
454 * Caller must have called SignToolPkcs7_Encode() prior to this function.
455 *
456 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
457 * message on failure.
458 * @param pThis The file which to write.
459 * @param cVerbosity The verbosity.
460 */
461static RTEXITCODE SignToolPkcs7_WriteSignatureToFile(PSIGNTOOLPKCS7 pThis, const char *pszFilename, unsigned cVerbosity)
462{
463 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
464
465 /*
466 * Open+truncate file, write new signature, close. Simple.
467 */
468 RTFILE hFile;
469 int rc = RTFileOpen(&hFile, pszFilename, RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE | RTFILE_O_DENY_WRITE);
470 if (RT_SUCCESS(rc))
471 {
472 rc = RTFileWrite(hFile, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
473 if (RT_SUCCESS(rc))
474 {
475 rc = RTFileClose(hFile);
476 if (RT_SUCCESS(rc))
477 {
478 if (cVerbosity > 0)
479 RTMsgInfo("Wrote %u bytes to %s", pThis->cbNewBuf, pszFilename);
480 return RTEXITCODE_SUCCESS;
481 }
482
483 RTMsgError("RTFileClose failed on %s: %Rrc", pszFilename, rc);
484 }
485 else
486 RTMsgError("Write error on %s: %Rrc", pszFilename, rc);
487 }
488 else
489 RTMsgError("Failed to open %s for writing: %Rrc", pszFilename, rc);
490 return RTEXITCODE_FAILURE;
491}
492
493
494
495/**
496 * Worker for recursively searching for MS nested signatures and signer infos.
497 *
498 * @returns Pointer to the signer info corresponding to @a iSignature. NULL if
499 * not found.
500 * @param pSignedData The signature to search.
501 * @param piNextSignature Pointer to the variable keeping track of the next
502 * signature number.
503 * @param iReqSignature The request signature number.
504 * @param ppSignedData Where to return the signature data structure.
505 */
506static PRTCRPKCS7SIGNERINFO SignToolPkcs7_FindNestedSignatureByIndexWorker(PRTCRPKCS7SIGNEDDATA pSignedData,
507 uint32_t *piNextSignature,
508 uint32_t iReqSignature,
509 PRTCRPKCS7SIGNEDDATA *ppSignedData)
510{
511 for (uint32_t iSignerInfo = 0; iSignerInfo < pSignedData->SignerInfos.cItems; iSignerInfo++)
512 {
513 /* Match?*/
514 PRTCRPKCS7SIGNERINFO pSignerInfo = pSignedData->SignerInfos.papItems[iSignerInfo];
515 if (*piNextSignature == iReqSignature)
516 {
517 *ppSignedData = pSignedData;
518 return pSignerInfo;
519 }
520 *piNextSignature += 1;
521
522 /* Look for nested signatures. */
523 for (uint32_t iAttrib = 0; iAttrib < pSignerInfo->UnauthenticatedAttributes.cItems; iAttrib++)
524 if (pSignerInfo->UnauthenticatedAttributes.papItems[iAttrib]->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE)
525 {
526 PRTCRPKCS7SETOFCONTENTINFOS pCntInfos;
527 pCntInfos = pSignerInfo->UnauthenticatedAttributes.papItems[iAttrib]->uValues.pContentInfos;
528 for (uint32_t iCntInfo = 0; iCntInfo < pCntInfos->cItems; iCntInfo++)
529 {
530 PRTCRPKCS7CONTENTINFO pCntInfo = pCntInfos->papItems[iCntInfo];
531 if (RTCrPkcs7ContentInfo_IsSignedData(pCntInfo))
532 {
533 PRTCRPKCS7SIGNERINFO pRet;
534 pRet = SignToolPkcs7_FindNestedSignatureByIndexWorker(pCntInfo->u.pSignedData, piNextSignature,
535 iReqSignature, ppSignedData);
536 if (pRet)
537 return pRet;
538 }
539 }
540 }
541 }
542 return NULL;
543}
544
545
546/**
547 * Locates the given nested signature.
548 *
549 * @returns Pointer to the signer info corresponding to @a iSignature. NULL if
550 * not found.
551 * @param pThis The PKCS\#7 structure to search.
552 * @param iReqSignature The requested signature number.
553 * @param ppSignedData Where to return the pointer to the signed data that
554 * the returned signer info belongs to.
555 *
556 * @todo Move into SPC or PKCS\#7.
557 */
558static PRTCRPKCS7SIGNERINFO SignToolPkcs7_FindNestedSignatureByIndex(PSIGNTOOLPKCS7 pThis, uint32_t iReqSignature,
559 PRTCRPKCS7SIGNEDDATA *ppSignedData)
560{
561 uint32_t iNextSignature = 0;
562 return SignToolPkcs7_FindNestedSignatureByIndexWorker(pThis->pSignedData, &iNextSignature, iReqSignature, ppSignedData);
563}
564
565
566
567/**
568 * Reads and decodes PKCS\#7 signature from the given executable.
569 *
570 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
571 * on failure.
572 * @param pThis The structure to initialize.
573 * @param pszFilename The executable filename.
574 * @param cVerbosity The verbosity.
575 * @param enmLdrArch For FAT binaries.
576 */
577static RTEXITCODE SignToolPkcs7Exe_InitFromFile(PSIGNTOOLPKCS7EXE pThis, const char *pszFilename,
578 unsigned cVerbosity, RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER)
579{
580 /*
581 * Init the return structure.
582 */
583 RT_ZERO(*pThis);
584 pThis->hLdrMod = NIL_RTLDRMOD;
585 pThis->pszFilename = pszFilename;
586
587 /*
588 * Open the image and check if it's signed.
589 */
590 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, enmLdrArch, &pThis->hLdrMod);
591 if (RT_SUCCESS(rc))
592 {
593 bool fIsSigned = false;
594 rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_IS_SIGNED, &fIsSigned, sizeof(fIsSigned));
595 if (RT_SUCCESS(rc) && fIsSigned)
596 {
597 /*
598 * Query the PKCS#7 data (assuming M$ style signing) and hand it to a worker.
599 */
600 size_t cbActual = 0;
601#ifdef DEBUG
602 size_t cbBuf = 64;
603#else
604 size_t cbBuf = _512K;
605#endif
606 void *pvBuf = RTMemAllocZ(cbBuf);
607 if (pvBuf)
608 {
609 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbActual);
610 if (rc == VERR_BUFFER_OVERFLOW)
611 {
612 RTMemFree(pvBuf);
613 cbBuf = cbActual;
614 pvBuf = RTMemAllocZ(cbActual);
615 if (pvBuf)
616 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/,
617 pvBuf, cbBuf, &cbActual);
618 else
619 rc = VERR_NO_MEMORY;
620 }
621 }
622 else
623 rc = VERR_NO_MEMORY;
624
625 pThis->pbBuf = (uint8_t *)pvBuf;
626 pThis->cbBuf = cbActual;
627 if (RT_SUCCESS(rc))
628 {
629 if (cVerbosity > 2)
630 RTPrintf("PKCS#7 signature: %u bytes\n", cbActual);
631 if (cVerbosity > 3)
632 RTPrintf("%.*Rhxd\n", cbActual, pvBuf);
633
634 /*
635 * Decode it.
636 */
637 rc = SignToolPkcs7_Decode(pThis, false /*fCatalog*/);
638 if (RT_SUCCESS(rc))
639 return RTEXITCODE_SUCCESS;
640 }
641 else
642 RTMsgError("RTLdrQueryPropEx/RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc\n", pszFilename, rc);
643 }
644 else if (RT_SUCCESS(rc))
645 RTMsgInfo("'%s': not signed\n", pszFilename);
646 else
647 RTMsgError("RTLdrQueryProp/RTLDRPROP_IS_SIGNED failed on '%s': %Rrc\n", pszFilename, rc);
648 }
649 else
650 RTMsgError("Error opening executable image '%s': %Rrc", pszFilename, rc);
651
652 SignToolPkcs7Exe_Delete(pThis);
653 return RTEXITCODE_FAILURE;
654}
655
656
657/**
658 * Calculates the checksum of an executable.
659 *
660 * @returns Success indicator (errors are reported)
661 * @param pThis The exe file to checksum.
662 * @param hFile The file handle.
663 * @param puCheckSum Where to return the checksum.
664 */
665static bool SignToolPkcs7Exe_CalcPeCheckSum(PSIGNTOOLPKCS7EXE pThis, RTFILE hFile, uint32_t *puCheckSum)
666{
667#ifdef RT_OS_WINDOWS
668 /*
669 * Try use IMAGEHLP!MapFileAndCheckSumW first.
670 */
671 PRTUTF16 pwszPath;
672 int rc = RTStrToUtf16(pThis->pszFilename, &pwszPath);
673 if (RT_SUCCESS(rc))
674 {
675 decltype(MapFileAndCheckSumW) *pfnMapFileAndCheckSumW;
676 pfnMapFileAndCheckSumW = (decltype(MapFileAndCheckSumW) *)RTLdrGetSystemSymbol("IMAGEHLP.DLL", "MapFileAndCheckSumW");
677 if (pfnMapFileAndCheckSumW)
678 {
679 DWORD uHeaderSum = UINT32_MAX;
680 DWORD uCheckSum = UINT32_MAX;
681 DWORD dwRc = pfnMapFileAndCheckSumW(pwszPath, &uHeaderSum, &uCheckSum);
682 if (dwRc == CHECKSUM_SUCCESS)
683 {
684 *puCheckSum = uCheckSum;
685 return true;
686 }
687 }
688 }
689#endif
690
691 RT_NOREF(pThis, hFile, puCheckSum);
692 RTMsgError("Implement check sum calcuation fallback!");
693 return false;
694}
695
696
697/**
698 * Writes the signature to the file.
699 *
700 * This has the side-effect of closing the hLdrMod member. So, it can only be
701 * called once!
702 *
703 * Caller must have called SignToolPkcs7_Encode() prior to this function.
704 *
705 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
706 * message on failure.
707 * @param pThis The file which to write.
708 * @param cVerbosity The verbosity.
709 */
710static RTEXITCODE SignToolPkcs7Exe_WriteSignatureToFile(PSIGNTOOLPKCS7EXE pThis, unsigned cVerbosity)
711{
712 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
713
714 /*
715 * Get the file header offset and arch before closing the destination handle.
716 */
717 uint32_t offNtHdrs;
718 int rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_FILE_OFF_HEADER, &offNtHdrs, sizeof(offNtHdrs));
719 if (RT_SUCCESS(rc))
720 {
721 RTLDRARCH enmLdrArch = RTLdrGetArch(pThis->hLdrMod);
722 if (enmLdrArch != RTLDRARCH_INVALID)
723 {
724 RTLdrClose(pThis->hLdrMod);
725 pThis->hLdrMod = NIL_RTLDRMOD;
726 unsigned cbNtHdrs = 0;
727 switch (enmLdrArch)
728 {
729 case RTLDRARCH_AMD64:
730 cbNtHdrs = sizeof(IMAGE_NT_HEADERS64);
731 break;
732 case RTLDRARCH_X86_32:
733 cbNtHdrs = sizeof(IMAGE_NT_HEADERS32);
734 break;
735 default:
736 RTMsgError("Unknown image arch: %d", enmLdrArch);
737 }
738 if (cbNtHdrs > 0)
739 {
740 if (cVerbosity > 0)
741 RTMsgInfo("offNtHdrs=%#x cbNtHdrs=%u\n", offNtHdrs, cbNtHdrs);
742
743 /*
744 * Open the executable file for writing.
745 */
746 RTFILE hFile;
747 rc = RTFileOpen(&hFile, pThis->pszFilename, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
748 if (RT_SUCCESS(rc))
749 {
750 /* Read the file header and locate the security directory entry. */
751 union
752 {
753 IMAGE_NT_HEADERS32 NtHdrs32;
754 IMAGE_NT_HEADERS64 NtHdrs64;
755 } uBuf;
756 PIMAGE_DATA_DIRECTORY pSecDir = cbNtHdrs == sizeof(IMAGE_NT_HEADERS64)
757 ? &uBuf.NtHdrs64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]
758 : &uBuf.NtHdrs32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
759
760 rc = RTFileReadAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
761 if ( RT_SUCCESS(rc)
762 && uBuf.NtHdrs32.Signature == IMAGE_NT_SIGNATURE)
763 {
764 /*
765 * Drop any old signature by truncating the file.
766 */
767 if ( pSecDir->Size > 8
768 && pSecDir->VirtualAddress > offNtHdrs + sizeof(IMAGE_NT_HEADERS32))
769 {
770 rc = RTFileSetSize(hFile, pSecDir->VirtualAddress);
771 if (RT_FAILURE(rc))
772 RTMsgError("Error truncating file to %#x bytes: %Rrc", pSecDir->VirtualAddress, rc);
773 }
774 else
775 rc = RTMsgErrorRc(VERR_BAD_EXE_FORMAT, "Bad security directory entry: VA=%#x Size=%#x",
776 pSecDir->VirtualAddress, pSecDir->Size);
777 if (RT_SUCCESS(rc))
778 {
779 /*
780 * Sector align the signature portion.
781 */
782 uint32_t const cbWinCert = RT_UOFFSETOF(WIN_CERTIFICATE, bCertificate);
783 uint64_t offCur = 0;
784 rc = RTFileGetSize(hFile, &offCur);
785 if ( RT_SUCCESS(rc)
786 && offCur < _2G)
787 {
788 if (offCur & 0x1ff)
789 {
790 uint32_t cbNeeded = 0x200 - ((uint32_t)offCur & 0x1ff);
791 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbNeeded, NULL);
792 if (RT_SUCCESS(rc))
793 offCur += cbNeeded;
794 }
795 if (RT_SUCCESS(rc))
796 {
797 /*
798 * Write the header followed by the signature data.
799 */
800 uint32_t const cbZeroPad = (uint32_t)(RT_ALIGN_Z(pThis->cbNewBuf, 8) - pThis->cbNewBuf);
801 pSecDir->VirtualAddress = (uint32_t)offCur;
802 pSecDir->Size = cbWinCert + (uint32_t)pThis->cbNewBuf + cbZeroPad;
803 if (cVerbosity >= 2)
804 RTMsgInfo("Writing %u (%#x) bytes of signature at %#x (%u).\n",
805 pSecDir->Size, pSecDir->Size, pSecDir->VirtualAddress, pSecDir->VirtualAddress);
806
807 WIN_CERTIFICATE WinCert;
808 WinCert.dwLength = pSecDir->Size;
809 WinCert.wRevision = WIN_CERT_REVISION_2_0;
810 WinCert.wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
811
812 rc = RTFileWriteAt(hFile, offCur, &WinCert, cbWinCert, NULL);
813 if (RT_SUCCESS(rc))
814 {
815 offCur += cbWinCert;
816 rc = RTFileWriteAt(hFile, offCur, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
817 }
818 if (RT_SUCCESS(rc) && cbZeroPad)
819 {
820 offCur += pThis->cbNewBuf;
821 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbZeroPad, NULL);
822 }
823 if (RT_SUCCESS(rc))
824 {
825 /*
826 * Reset the checksum (sec dir updated already) and rewrite the header.
827 */
828 uBuf.NtHdrs32.OptionalHeader.CheckSum = 0;
829 offCur = offNtHdrs;
830 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
831 if (RT_SUCCESS(rc))
832 rc = RTFileFlush(hFile);
833 if (RT_SUCCESS(rc))
834 {
835 /*
836 * Calc checksum and write out the header again.
837 */
838 uint32_t uCheckSum = UINT32_MAX;
839 if (SignToolPkcs7Exe_CalcPeCheckSum(pThis, hFile, &uCheckSum))
840 {
841 uBuf.NtHdrs32.OptionalHeader.CheckSum = uCheckSum;
842 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
843 if (RT_SUCCESS(rc))
844 rc = RTFileFlush(hFile);
845 if (RT_SUCCESS(rc))
846 {
847 rc = RTFileClose(hFile);
848 if (RT_SUCCESS(rc))
849 return RTEXITCODE_SUCCESS;
850 RTMsgError("RTFileClose failed: %Rrc\n", rc);
851 return RTEXITCODE_FAILURE;
852 }
853 }
854 }
855 }
856 }
857 if (RT_FAILURE(rc))
858 RTMsgError("Write error at %#RX64: %Rrc", offCur, rc);
859 }
860 else if (RT_SUCCESS(rc))
861 RTMsgError("File to big: %'RU64 bytes", offCur);
862 else
863 RTMsgError("RTFileGetSize failed: %Rrc", rc);
864 }
865 }
866 else if (RT_SUCCESS(rc))
867 RTMsgError("Not NT executable header!");
868 else
869 RTMsgError("Error reading NT headers (%#x bytes) at %#x: %Rrc", cbNtHdrs, offNtHdrs, rc);
870 RTFileClose(hFile);
871 }
872 else
873 RTMsgError("Failed to open '%s' for writing: %Rrc", pThis->pszFilename, rc);
874 }
875 }
876 else
877 RTMsgError("RTLdrGetArch failed!");
878 }
879 else
880 RTMsgError("RTLdrQueryProp/RTLDRPROP_FILE_OFF_HEADER failed: %Rrc", rc);
881 return RTEXITCODE_FAILURE;
882}
883
884
885
886/*
887 * The 'extract-exe-signer-cert' command.
888 */
889static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
890{
891 RT_NOREF_PV(enmLevel);
892 RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--signature-index|-i <num>] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
893 return RTEXITCODE_SUCCESS;
894}
895
896static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
897{
898 /*
899 * Parse arguments.
900 */
901 static const RTGETOPTDEF s_aOptions[] =
902 {
903 { "--ber", 'b', RTGETOPT_REQ_NOTHING },
904 { "--cer", 'c', RTGETOPT_REQ_NOTHING },
905 { "--der", 'd', RTGETOPT_REQ_NOTHING },
906 { "--exe", 'e', RTGETOPT_REQ_STRING },
907 { "--output", 'o', RTGETOPT_REQ_STRING },
908 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
909 };
910
911 const char *pszExe = NULL;
912 const char *pszOut = NULL;
913 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
914 unsigned cVerbosity = 0;
915 uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
916 uint32_t iSignature = 0;
917
918 RTGETOPTSTATE GetState;
919 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
920 AssertRCReturn(rc, RTEXITCODE_FAILURE);
921 RTGETOPTUNION ValueUnion;
922 int ch;
923 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
924 {
925 switch (ch)
926 {
927 case 'e': pszExe = ValueUnion.psz; break;
928 case 'o': pszOut = ValueUnion.psz; break;
929 case 'b': fCursorFlags = 0; break;
930 case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
931 case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
932 case 'i': iSignature = ValueUnion.u32; break;
933 case 'V': return HandleVersion(cArgs, papszArgs);
934 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
935
936 case VINF_GETOPT_NOT_OPTION:
937 if (!pszExe)
938 pszExe = ValueUnion.psz;
939 else if (!pszOut)
940 pszOut = ValueUnion.psz;
941 else
942 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
943 break;
944
945 default:
946 return RTGetOptPrintError(ch, &ValueUnion);
947 }
948 }
949 if (!pszExe)
950 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
951 if (!pszOut)
952 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
953 if (RTPathExists(pszOut))
954 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
955
956 /*
957 * Do it.
958 */
959 /* Read & decode the PKCS#7 signature. */
960 SIGNTOOLPKCS7EXE This;
961 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
962 if (rcExit == RTEXITCODE_SUCCESS)
963 {
964 /* Find the signing certificate (ASSUMING that the certificate used is shipped in the set of certificates). */
965 PRTCRPKCS7SIGNEDDATA pSignedData;
966 PCRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(&This, iSignature, &pSignedData);
967 rcExit = RTEXITCODE_FAILURE;
968 if (pSignerInfo)
969 {
970 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSignedData->SignerInfos.papItems[0]->IssuerAndSerialNumber;
971 PCRTCRX509CERTIFICATE pCert;
972 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
973 &pISN->Name, &pISN->SerialNumber);
974 if (pCert)
975 {
976 /*
977 * Write it out.
978 */
979 RTFILE hFile;
980 rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE);
981 if (RT_SUCCESS(rc))
982 {
983 uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
984 rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
985 cbCert, NULL);
986 if (RT_SUCCESS(rc))
987 {
988 rc = RTFileClose(hFile);
989 if (RT_SUCCESS(rc))
990 {
991 hFile = NIL_RTFILE;
992 rcExit = RTEXITCODE_SUCCESS;
993 RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut);
994 }
995 else
996 RTMsgError("RTFileClose failed: %Rrc", rc);
997 }
998 else
999 RTMsgError("RTFileWrite failed: %Rrc", rc);
1000 RTFileClose(hFile);
1001 }
1002 else
1003 RTMsgError("Error opening '%s' for writing: %Rrc", pszOut, rc);
1004 }
1005 else
1006 RTMsgError("Certificate not found.");
1007 }
1008 else
1009 RTMsgError("Could not locate signature #%u!", iSignature);
1010
1011 /* Delete the signature data. */
1012 SignToolPkcs7Exe_Delete(&This);
1013 }
1014 return rcExit;
1015}
1016
1017
1018/*
1019 * The 'add-nested-exe-signature' command.
1020 */
1021static RTEXITCODE HelpAddNestedExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1022{
1023 RT_NOREF_PV(enmLevel);
1024 RTStrmPrintf(pStrm, "add-nested-exe-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-exe> <source-exe>\n");
1025 if (enmLevel == RTSIGNTOOLHELP_FULL)
1026 RTStrmPrintf(pStrm,
1027 "\n"
1028 "The --debug option allows the source-exe to be omitted in order to test the\n"
1029 "encoding and PE file modification.\n"
1030 "\n"
1031 "The --prepend option puts the nested signature first rather than appending it\n"
1032 "to the end of of the nested signature set. Windows reads nested signatures in\n"
1033 "reverse order, so --prepend will logically putting it last.\n"
1034 );
1035 return RTEXITCODE_SUCCESS;
1036}
1037
1038
1039static RTEXITCODE HandleAddNestedExeSignature(int cArgs, char **papszArgs)
1040{
1041 /*
1042 * Parse arguments.
1043 */
1044 static const RTGETOPTDEF s_aOptions[] =
1045 {
1046 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
1047 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1048 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
1049 };
1050
1051 const char *pszDst = NULL;
1052 const char *pszSrc = NULL;
1053 unsigned cVerbosity = 0;
1054 bool fDebug = false;
1055 bool fPrepend = false;
1056
1057 RTGETOPTSTATE GetState;
1058 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1059 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1060 RTGETOPTUNION ValueUnion;
1061 int ch;
1062 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1063 {
1064 switch (ch)
1065 {
1066 case 'v': cVerbosity++; break;
1067 case 'd': fDebug = pszSrc == NULL; break;
1068 case 'p': fPrepend = true; break;
1069 case 'V': return HandleVersion(cArgs, papszArgs);
1070 case 'h': return HelpAddNestedExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
1071
1072 case VINF_GETOPT_NOT_OPTION:
1073 if (!pszDst)
1074 pszDst = ValueUnion.psz;
1075 else if (!pszSrc)
1076 {
1077 pszSrc = ValueUnion.psz;
1078 fDebug = false;
1079 }
1080 else
1081 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
1082 break;
1083
1084 default:
1085 return RTGetOptPrintError(ch, &ValueUnion);
1086 }
1087 }
1088 if (!pszDst)
1089 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination executable given.");
1090 if (!pszSrc && !fDebug)
1091 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source executable file given.");
1092
1093 /*
1094 * Do it.
1095 */
1096 /* Read & decode the source PKCS#7 signature. */
1097 SIGNTOOLPKCS7EXE Src;
1098 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7Exe_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
1099 if (rcExit == RTEXITCODE_SUCCESS)
1100 {
1101 /* Ditto for the destination PKCS#7 signature. */
1102 SIGNTOOLPKCS7EXE Dst;
1103 rcExit = SignToolPkcs7Exe_InitFromFile(&Dst, pszDst, cVerbosity);
1104 if (rcExit == RTEXITCODE_SUCCESS)
1105 {
1106 /* Do the signature manipulation. */
1107 if (pszSrc)
1108 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
1109 if (rcExit == RTEXITCODE_SUCCESS)
1110 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
1111
1112 /* Update the destination executable file. */
1113 if (rcExit == RTEXITCODE_SUCCESS)
1114 rcExit = SignToolPkcs7Exe_WriteSignatureToFile(&Dst, cVerbosity);
1115
1116 SignToolPkcs7Exe_Delete(&Dst);
1117 }
1118 if (pszSrc)
1119 SignToolPkcs7Exe_Delete(&Src);
1120 }
1121
1122 return rcExit;
1123}
1124
1125
1126/*
1127 * The 'add-nested-cat-signature' command.
1128 */
1129static RTEXITCODE HelpAddNestedCatSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1130{
1131 RT_NOREF_PV(enmLevel);
1132 RTStrmPrintf(pStrm, "add-nested-cat-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-cat> <source-cat>\n");
1133 if (enmLevel == RTSIGNTOOLHELP_FULL)
1134 RTStrmPrintf(pStrm,
1135 "\n"
1136 "The --debug option allows the source-cat to be omitted in order to test the\n"
1137 "ASN.1 re-encoding of the destination catalog file.\n"
1138 "\n"
1139 "The --prepend option puts the nested signature first rather than appending it\n"
1140 "to the end of of the nested signature set. Windows reads nested signatures in\n"
1141 "reverse order, so --prepend will logically putting it last.\n"
1142 );
1143 return RTEXITCODE_SUCCESS;
1144}
1145
1146
1147static RTEXITCODE HandleAddNestedCatSignature(int cArgs, char **papszArgs)
1148{
1149 /*
1150 * Parse arguments.
1151 */
1152 static const RTGETOPTDEF s_aOptions[] =
1153 {
1154 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
1155 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1156 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
1157 };
1158
1159 const char *pszDst = NULL;
1160 const char *pszSrc = NULL;
1161 unsigned cVerbosity = 0;
1162 bool fDebug = false;
1163 bool fPrepend = false;
1164
1165 RTGETOPTSTATE GetState;
1166 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1167 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1168 RTGETOPTUNION ValueUnion;
1169 int ch;
1170 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1171 {
1172 switch (ch)
1173 {
1174 case 'v': cVerbosity++; break;
1175 case 'd': fDebug = pszSrc == NULL; break;
1176 case 'p': fPrepend = true; break;
1177 case 'V': return HandleVersion(cArgs, papszArgs);
1178 case 'h': return HelpAddNestedCatSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
1179
1180 case VINF_GETOPT_NOT_OPTION:
1181 if (!pszDst)
1182 pszDst = ValueUnion.psz;
1183 else if (!pszSrc)
1184 {
1185 pszSrc = ValueUnion.psz;
1186 fDebug = false;
1187 }
1188 else
1189 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
1190 break;
1191
1192 default:
1193 return RTGetOptPrintError(ch, &ValueUnion);
1194 }
1195 }
1196 if (!pszDst)
1197 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination catalog file given.");
1198 if (!pszSrc && !fDebug)
1199 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source catalog file given.");
1200
1201 /*
1202 * Do it.
1203 */
1204 /* Read & decode the source PKCS#7 signature. */
1205 SIGNTOOLPKCS7 Src;
1206 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
1207 if (rcExit == RTEXITCODE_SUCCESS)
1208 {
1209 /* Ditto for the destination PKCS#7 signature. */
1210 SIGNTOOLPKCS7EXE Dst;
1211 rcExit = SignToolPkcs7_InitFromFile(&Dst, pszDst, cVerbosity);
1212 if (rcExit == RTEXITCODE_SUCCESS)
1213 {
1214 /* Do the signature manipulation. */
1215 if (pszSrc)
1216 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
1217 if (rcExit == RTEXITCODE_SUCCESS)
1218 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
1219
1220 /* Update the destination executable file. */
1221 if (rcExit == RTEXITCODE_SUCCESS)
1222 rcExit = SignToolPkcs7_WriteSignatureToFile(&Dst, pszDst, cVerbosity);
1223
1224 SignToolPkcs7_Delete(&Dst);
1225 }
1226 if (pszSrc)
1227 SignToolPkcs7_Delete(&Src);
1228 }
1229
1230 return rcExit;
1231}
1232
1233#ifndef IPRT_IN_BUILD_TOOL
1234
1235/*
1236 * The 'verify-exe' command.
1237 */
1238static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1239{
1240 RT_NOREF_PV(enmLevel);
1241 RTStrmPrintf(pStrm,
1242 "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n"
1243 " [--type <win|osx>] <exe1> [exe2 [..]]\n");
1244 return RTEXITCODE_SUCCESS;
1245}
1246
1247typedef struct VERIFYEXESTATE
1248{
1249 RTCRSTORE hRootStore;
1250 RTCRSTORE hKernelRootStore;
1251 RTCRSTORE hAdditionalStore;
1252 bool fKernel;
1253 int cVerbose;
1254 enum { kSignType_Windows, kSignType_OSX } enmSignType;
1255 uint64_t uTimestamp;
1256 RTLDRARCH enmLdrArch;
1257} VERIFYEXESTATE;
1258
1259# ifdef VBOX
1260/** Certificate store load set.
1261 * Declared outside HandleVerifyExe because of braindead gcc visibility crap. */
1262struct STSTORESET
1263{
1264 RTCRSTORE hStore;
1265 PCSUPTAENTRY paTAs;
1266 unsigned cTAs;
1267};
1268# endif
1269
1270/**
1271 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
1272 * Standard code signing. Use this for Microsoft SPC.}
1273 */
1274static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
1275 void *pvUser, PRTERRINFO pErrInfo)
1276{
1277 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
1278 uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0;
1279
1280 /*
1281 * Dump all the paths.
1282 */
1283 if (pState->cVerbose > 0)
1284 {
1285 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
1286 {
1287 RTPrintf("---\n");
1288 RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
1289 *pErrInfo->pszMsg = '\0';
1290 }
1291 RTPrintf("---\n");
1292 }
1293
1294 /*
1295 * Test signing certificates normally doesn't have all the necessary
1296 * features required below. So, treat them as special cases.
1297 */
1298 if ( hCertPaths == NIL_RTCRX509CERTPATHS
1299 && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
1300 {
1301 RTMsgInfo("Test signed.\n");
1302 return VINF_SUCCESS;
1303 }
1304
1305 if (hCertPaths == NIL_RTCRX509CERTPATHS)
1306 RTMsgInfo("Signed by trusted certificate.\n");
1307
1308 /*
1309 * Standard code signing capabilites required.
1310 */
1311 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
1312 if ( RT_SUCCESS(rc)
1313 && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
1314 {
1315 /*
1316 * If kernel signing, a valid certificate path must be anchored by the
1317 * microsoft kernel signing root certificate. The only alternative is
1318 * test signing.
1319 */
1320 if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS)
1321 {
1322 uint32_t cFound = 0;
1323 uint32_t cValid = 0;
1324 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
1325 {
1326 bool fTrusted;
1327 PCRTCRX509NAME pSubject;
1328 PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
1329 int rcVerify;
1330 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
1331 NULL, NULL /*pCertCtx*/, &rcVerify);
1332 AssertRCBreak(rc);
1333
1334 if (RT_SUCCESS(rcVerify))
1335 {
1336 Assert(fTrusted);
1337 cValid++;
1338
1339 /* Search the kernel signing root store for a matching anchor. */
1340 RTCRSTORECERTSEARCH Search;
1341 rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search);
1342 AssertRCBreak(rc);
1343 PCRTCRCERTCTX pCertCtx;
1344 while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL)
1345 {
1346 PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo;
1347 if (pCertCtx->pCert)
1348 pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
1349 else if (pCertCtx->pTaInfo)
1350 pPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
1351 else
1352 pPubKeyInfo = NULL;
1353 if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0)
1354 cFound++;
1355 RTCrCertCtxRelease(pCertCtx);
1356 }
1357
1358 int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2);
1359 }
1360 }
1361 if (RT_SUCCESS(rc) && cFound == 0)
1362 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
1363 if (RT_SUCCESS(rc) && cValid != 2)
1364 RTMsgWarning("%u valid paths, expected 2", cValid);
1365 }
1366 }
1367
1368 return rc;
1369}
1370
1371
1372/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
1373static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
1374 void const *pvSignature, size_t cbSignature,
1375 PRTERRINFO pErrInfo, void *pvUser)
1376{
1377 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
1378 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(cbSignature);
1379
1380 switch (enmSignature)
1381 {
1382 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
1383 {
1384 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
1385
1386 RTTIMESPEC ValidationTime;
1387 RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp);
1388
1389 /*
1390 * Dump the signed data if so requested.
1391 */
1392 if (pState->cVerbose)
1393 RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
1394
1395
1396 /*
1397 * Do the actual verification. Will have to modify this so it takes
1398 * the authenticode policies into account.
1399 */
1400 return RTCrPkcs7VerifySignedData(pContentInfo,
1401 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
1402 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
1403 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT,
1404 pState->hAdditionalStore, pState->hRootStore, &ValidationTime,
1405 VerifyExecCertVerifyCallback, pState, pErrInfo);
1406 }
1407
1408 default:
1409 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature);
1410 }
1411}
1412
1413/** Worker for HandleVerifyExe. */
1414static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
1415{
1416 /*
1417 * Open the executable image and verify it.
1418 */
1419 RTLDRMOD hLdrMod;
1420 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod);
1421 if (RT_FAILURE(rc))
1422 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc);
1423
1424
1425 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pState->uTimestamp, sizeof(pState->uTimestamp));
1426 if (RT_SUCCESS(rc))
1427 {
1428 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
1429 if (RT_SUCCESS(rc))
1430 RTMsgInfo("'%s' is valid.\n", pszFilename);
1431 else if (rc == VERR_CR_X509_CPV_NOT_VALID_AT_TIME)
1432 {
1433 RTTIMESPEC Now;
1434 pState->uTimestamp = RTTimeSpecGetSeconds(RTTimeNow(&Now));
1435 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
1436 if (RT_SUCCESS(rc))
1437 RTMsgInfo("'%s' is valid now, but not at link time.\n", pszFilename);
1438 }
1439 if (RT_FAILURE(rc))
1440 RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg);
1441 }
1442 else
1443 RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pszFilename, rc);
1444
1445 int rc2 = RTLdrClose(hLdrMod);
1446 if (RT_FAILURE(rc2))
1447 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
1448 if (RT_FAILURE(rc))
1449 return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
1450
1451 return RTEXITCODE_SUCCESS;
1452}
1453
1454
1455static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
1456{
1457 RTERRINFOSTATIC StaticErrInfo;
1458
1459 /* Note! This code does not try to clean up the crypto stores on failure.
1460 This is intentional as the code is only expected to be used in a
1461 one-command-per-process environment where we do exit() upon
1462 returning from this function. */
1463
1464 /*
1465 * Parse arguments.
1466 */
1467 static const RTGETOPTDEF s_aOptions[] =
1468 {
1469 { "--kernel", 'k', RTGETOPT_REQ_NOTHING },
1470 { "--root", 'r', RTGETOPT_REQ_STRING },
1471 { "--additional", 'a', RTGETOPT_REQ_STRING },
1472 { "--add", 'a', RTGETOPT_REQ_STRING },
1473 { "--type", 't', RTGETOPT_REQ_STRING },
1474 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1475 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
1476 };
1477
1478 VERIFYEXESTATE State =
1479 {
1480 NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false,
1481 VERIFYEXESTATE::kSignType_Windows, 0, RTLDRARCH_WHATEVER
1482 };
1483 int rc = RTCrStoreCreateInMem(&State.hRootStore, 0);
1484 if (RT_SUCCESS(rc))
1485 rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0);
1486 if (RT_SUCCESS(rc))
1487 rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0);
1488 if (RT_FAILURE(rc))
1489 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
1490
1491 RTGETOPTSTATE GetState;
1492 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1493 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1494 RTGETOPTUNION ValueUnion;
1495 int ch;
1496 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
1497 {
1498 switch (ch)
1499 {
1500 case 'r': case 'a':
1501 rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore,
1502 RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR,
1503 ValueUnion.psz, RTErrInfoInitStatic(&StaticErrInfo));
1504 if (RT_FAILURE(rc))
1505 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s",
1506 ValueUnion.psz, rc, StaticErrInfo.szMsg);
1507 if (RTErrInfoIsSet(&StaticErrInfo.Core))
1508 RTMsgWarning("Warnings loading certificate '%s': %s", ValueUnion.psz, StaticErrInfo.szMsg);
1509 break;
1510
1511 case 't':
1512 if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
1513 State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
1514 else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
1515 State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
1516 else
1517 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
1518 break;
1519
1520 case 'k': State.fKernel = true; break;
1521 case 'v': State.cVerbose++; break;
1522 case 'q': State.cVerbose = 0; break;
1523 case 'V': return HandleVersion(cArgs, papszArgs);
1524 case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
1525 default: return RTGetOptPrintError(ch, &ValueUnion);
1526 }
1527 }
1528 if (ch != VINF_GETOPT_NOT_OPTION)
1529 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
1530
1531 /*
1532 * Populate the certificate stores according to the signing type.
1533 */
1534#ifdef VBOX
1535 unsigned cSets = 0;
1536 struct STSTORESET aSets[6];
1537#endif
1538
1539 switch (State.enmSignType)
1540 {
1541 case VERIFYEXESTATE::kSignType_Windows:
1542#ifdef VBOX
1543 aSets[cSets].hStore = State.hRootStore;
1544 aSets[cSets].paTAs = g_aSUPTimestampTAs;
1545 aSets[cSets].cTAs = g_cSUPTimestampTAs;
1546 cSets++;
1547 aSets[cSets].hStore = State.hRootStore;
1548 aSets[cSets].paTAs = g_aSUPSpcRootTAs;
1549 aSets[cSets].cTAs = g_cSUPSpcRootTAs;
1550 cSets++;
1551 aSets[cSets].hStore = State.hRootStore;
1552 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
1553 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
1554 cSets++;
1555 aSets[cSets].hStore = State.hKernelRootStore;
1556 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
1557 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
1558 cSets++;
1559#endif
1560 break;
1561
1562 case VERIFYEXESTATE::kSignType_OSX:
1563 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented.");
1564 }
1565
1566#ifdef VBOX
1567 for (unsigned i = 0; i < cSets; i++)
1568 for (unsigned j = 0; j < aSets[i].cTAs; j++)
1569 {
1570 rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
1571 aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
1572 if (RT_FAILURE(rc))
1573 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
1574 i, j, StaticErrInfo.szMsg);
1575 }
1576#endif
1577
1578 /*
1579 * Do it.
1580 */
1581 RTEXITCODE rcExit;
1582 for (;;)
1583 {
1584 rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo);
1585 if (rcExit != RTEXITCODE_SUCCESS)
1586 break;
1587
1588 /*
1589 * Next file
1590 */
1591 ch = RTGetOpt(&GetState, &ValueUnion);
1592 if (ch == 0)
1593 break;
1594 if (ch != VINF_GETOPT_NOT_OPTION)
1595 {
1596 rcExit = RTGetOptPrintError(ch, &ValueUnion);
1597 break;
1598 }
1599 }
1600
1601 /*
1602 * Clean up.
1603 */
1604 uint32_t cRefs;
1605 cRefs = RTCrStoreRelease(State.hRootStore); Assert(cRefs == 0);
1606 cRefs = RTCrStoreRelease(State.hKernelRootStore); Assert(cRefs == 0);
1607 cRefs = RTCrStoreRelease(State.hAdditionalStore); Assert(cRefs == 0);
1608
1609 return rcExit;
1610}
1611
1612#endif /* !IPRT_IN_BUILD_TOOL */
1613
1614/*
1615 * common code for show-exe and show-cat:
1616 */
1617
1618/**
1619 * Display an object ID.
1620 *
1621 * @returns IPRT status code.
1622 * @param pThis The show exe instance data.
1623 * @param pObjId The object ID to display.
1624 * @param pszLabel The field label (prefixed by szPrefix).
1625 * @param pszPost What to print after the ID (typically newline).
1626 */
1627static void HandleShowExeWorkerDisplayObjId(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszLabel, const char *pszPost)
1628{
1629 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
1630 if (RT_SUCCESS(rc))
1631 {
1632 if (pThis->cVerbosity > 1)
1633 RTPrintf("%s%s%s (%s)%s", pThis->szPrefix, pszLabel, pThis->szTmp, pObjId->szObjId, pszPost);
1634 else
1635 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pThis->szTmp, pszPost);
1636 }
1637 else
1638 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pObjId->szObjId, pszPost);
1639}
1640
1641
1642/**
1643 * Display an object ID, without prefix and label
1644 *
1645 * @returns IPRT status code.
1646 * @param pThis The show exe instance data.
1647 * @param pObjId The object ID to display.
1648 * @param pszPost What to print after the ID (typically newline).
1649 */
1650static void HandleShowExeWorkerDisplayObjIdSimple(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszPost)
1651{
1652 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
1653 if (RT_SUCCESS(rc))
1654 {
1655 if (pThis->cVerbosity > 1)
1656 RTPrintf("%s (%s)%s", pThis->szTmp, pObjId->szObjId, pszPost);
1657 else
1658 RTPrintf("%s%s", pThis->szTmp, pszPost);
1659 }
1660 else
1661 RTPrintf("%s%s", pObjId->szObjId, pszPost);
1662}
1663
1664
1665/**
1666 * Display a signer info attribute.
1667 *
1668 * @returns IPRT status code.
1669 * @param pThis The show exe instance data.
1670 * @param offPrefix The current prefix offset.
1671 * @param pAttr The attribute to display.
1672 */
1673static int HandleShowExeWorkerPkcs7DisplayAttrib(PSHOWEXEPKCS7 pThis, size_t offPrefix, PCRTCRPKCS7ATTRIBUTE pAttr)
1674{
1675 HandleShowExeWorkerDisplayObjId(pThis, &pAttr->Type, "", ":\n");
1676
1677 int rc = VINF_SUCCESS;
1678 switch (pAttr->enmType)
1679 {
1680 case RTCRPKCS7ATTRIBUTETYPE_UNKNOWN:
1681 if (pAttr->uValues.pCores->cItems <= 1)
1682 RTPrintf("%s %u bytes\n", pThis->szPrefix,pAttr->uValues.pCores->SetCore.Asn1Core.cb);
1683 else
1684 RTPrintf("%s %u bytes divided by %u items\n", pThis->szPrefix, pAttr->uValues.pCores->SetCore.Asn1Core.cb, pAttr->uValues.pCores->cItems);
1685 break;
1686
1687 /* Object IDs, use pObjIds. */
1688 case RTCRPKCS7ATTRIBUTETYPE_OBJ_IDS:
1689 if (pAttr->uValues.pObjIds->cItems != 1)
1690 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIds->cItems);
1691 for (unsigned i = 0; i < pAttr->uValues.pObjIds->cItems; i++)
1692 {
1693 if (pAttr->uValues.pObjIds->cItems == 1)
1694 RTPrintf("%s ", pThis->szPrefix);
1695 else
1696 RTPrintf("%s ObjId[%u]: ", pThis->szPrefix, i);
1697 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIds->papItems[i], "\n");
1698 }
1699 break;
1700
1701 /* Sequence of object IDs, use pObjIdSeqs. */
1702 case RTCRPKCS7ATTRIBUTETYPE_MS_STATEMENT_TYPE:
1703 if (pAttr->uValues.pObjIdSeqs->cItems != 1)
1704 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIdSeqs->cItems);
1705 for (unsigned i = 0; i < pAttr->uValues.pObjIdSeqs->cItems; i++)
1706 {
1707 uint32_t const cObjIds = pAttr->uValues.pObjIdSeqs->papItems[i]->cItems;
1708 for (unsigned j = 0; j < cObjIds; j++)
1709 {
1710 if (pAttr->uValues.pObjIdSeqs->cItems == 1)
1711 RTPrintf("%s ", pThis->szPrefix);
1712 else
1713 RTPrintf("%s ObjIdSeq[%u]: ", pThis->szPrefix, i);
1714 if (cObjIds != 1)
1715 RTPrintf(" ObjId[%u]: ", j);
1716 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIdSeqs->papItems[i]->papItems[i], "\n");
1717 }
1718 }
1719 break;
1720
1721 /* Octet strings, use pOctetStrings. */
1722 case RTCRPKCS7ATTRIBUTETYPE_OCTET_STRINGS:
1723 if (pAttr->uValues.pOctetStrings->cItems != 1)
1724 RTPrintf("%s%u octet strings:", pThis->szPrefix, pAttr->uValues.pOctetStrings->cItems);
1725 for (unsigned i = 0; i < pAttr->uValues.pOctetStrings->cItems; i++)
1726 {
1727 PCRTASN1OCTETSTRING pOctetString = pAttr->uValues.pOctetStrings->papItems[i];
1728 uint32_t cbContent = pOctetString->Asn1Core.cb;
1729 if (cbContent > 0 && (cbContent <= 128 || pThis->cVerbosity >= 2))
1730 {
1731 uint8_t const *pbContent = pOctetString->Asn1Core.uData.pu8;
1732 uint32_t off = 0;
1733 while (off < cbContent)
1734 {
1735 uint32_t cbNow = RT_MIN(cbContent - off, 16);
1736 if (pAttr->uValues.pOctetStrings->cItems == 1)
1737 RTPrintf("%s %#06x: %.*Rhxs\n", pThis->szPrefix, off, cbNow, &pbContent[off]);
1738 else
1739 RTPrintf("%s OctetString[%u]: %#06x: %.*Rhxs\n", pThis->szPrefix, i, off, cbNow, &pbContent[off]);
1740 off += cbNow;
1741 }
1742 }
1743 else
1744 RTPrintf("%s: OctetString[%u]: %u bytes\n", pThis->szPrefix, i, pOctetString->Asn1Core.cb);
1745 }
1746 break;
1747
1748 /* Counter signatures (PKCS \#9), use pCounterSignatures. */
1749 case RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES:
1750 RTPrintf("%sTODO: RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES! %u bytes\n",
1751 pThis->szPrefix, pAttr->uValues.pCounterSignatures->SetCore.Asn1Core.cb);
1752 break;
1753
1754 /* Signing time (PKCS \#9), use pSigningTime. */
1755 case RTCRPKCS7ATTRIBUTETYPE_SIGNING_TIME:
1756 RTPrintf("%sTODO: RTCRPKCS7ATTRIBUTETYPE_SIGNING_TIME! %u bytes\n",
1757 pThis->szPrefix, pAttr->uValues.pSigningTime->SetCore.Asn1Core.cb);
1758 break;
1759
1760 /* Microsoft timestamp info (RFC-3161) signed data, use pContentInfo. */
1761 case RTCRPKCS7ATTRIBUTETYPE_MS_TIMESTAMP:
1762 case RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE:
1763 if (pAttr->uValues.pContentInfos->cItems > 1)
1764 RTPrintf("%s%u nested signatures, %u bytes in total\n", pThis->szPrefix,
1765 pAttr->uValues.pContentInfos->cItems, pAttr->uValues.pContentInfos->SetCore.Asn1Core.cb);
1766 for (unsigned i = 0; i < pAttr->uValues.pContentInfos->cItems; i++)
1767 {
1768 size_t offPrefix2 = offPrefix;
1769 if (pAttr->uValues.pContentInfos->cItems > 1)
1770 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig[%u]: ", i);
1771 else
1772 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " ");
1773 // offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig: ", i);
1774 PCRTCRPKCS7CONTENTINFO pContentInfo = pAttr->uValues.pContentInfos->papItems[i];
1775 int rc2;
1776 if (RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
1777 rc2 = HandleShowExeWorkerPkcs7Display(pThis, pContentInfo->u.pSignedData, offPrefix2, pContentInfo);
1778 else
1779 rc2 = RTMsgErrorRc(VERR_ASN1_UNEXPECTED_OBJ_ID, "%sPKCS#7 content in nested signature is not 'signedData': %s",
1780 pThis->szPrefix, pContentInfo->ContentType.szObjId);
1781 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1782 rc = rc2;
1783 }
1784 break;
1785
1786 case RTCRPKCS7ATTRIBUTETYPE_INVALID:
1787 RTPrintf("%sINVALID!\n", pThis->szPrefix);
1788 break;
1789 case RTCRPKCS7ATTRIBUTETYPE_NOT_PRESENT:
1790 RTPrintf("%sNOT PRESENT!\n", pThis->szPrefix);
1791 break;
1792 default:
1793 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pAttr->enmType);
1794 break;
1795 }
1796 return rc;
1797}
1798
1799
1800/**
1801 * Displays a Microsoft SPC indirect data structure.
1802 *
1803 * @returns IPRT status code.
1804 * @param pThis The show exe instance data.
1805 * @param offPrefix The current prefix offset.
1806 * @param pIndData The indirect data to display.
1807 */
1808static int HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(PSHOWEXEPKCS7 pThis, size_t offPrefix,
1809 PCRTCRSPCINDIRECTDATACONTENT pIndData)
1810{
1811 /*
1812 * The image hash.
1813 */
1814 RTDIGESTTYPE const enmDigestType = RTCrX509AlgorithmIdentifier_QueryDigestType(&pIndData->DigestInfo.DigestAlgorithm);
1815 const char *pszDigestType = RTCrDigestTypeToName(enmDigestType);
1816 RTPrintf("%s Digest Type: %s", pThis->szPrefix, pszDigestType);
1817 if (pThis->cVerbosity > 1)
1818 RTPrintf(" (%s)\n", pIndData->DigestInfo.DigestAlgorithm.Algorithm.szObjId);
1819 else
1820 RTPrintf("\n");
1821 RTPrintf("%s Digest: %.*Rhxs\n",
1822 pThis->szPrefix, pIndData->DigestInfo.Digest.Asn1Core.cb, pIndData->DigestInfo.Digest.Asn1Core.uData.pu8);
1823
1824 /*
1825 * The data/file/url.
1826 */
1827 switch (pIndData->Data.enmType)
1828 {
1829 case RTCRSPCAAOVTYPE_PE_IMAGE_DATA:
1830 {
1831 RTPrintf("%s Data Type: PE Image Data\n", pThis->szPrefix);
1832 PRTCRSPCPEIMAGEDATA pPeImage = pIndData->Data.uValue.pPeImage;
1833 /** @todo display "Flags". */
1834
1835 switch (pPeImage->T0.File.enmChoice)
1836 {
1837 case RTCRSPCLINKCHOICE_MONIKER:
1838 {
1839 PRTCRSPCSERIALIZEDOBJECT pMoniker = pPeImage->T0.File.u.pMoniker;
1840 if (RTCrSpcSerializedObject_IsPresent(pMoniker))
1841 {
1842 if (RTUuidCompareStr(pMoniker->Uuid.Asn1Core.uData.pUuid, RTCRSPCSERIALIZEDOBJECT_UUID_STR) == 0)
1843 {
1844 RTPrintf("%s Moniker: SpcSerializedObject (%RTuuid)\n",
1845 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
1846
1847 PCRTCRSPCSERIALIZEDOBJECTATTRIBUTES pData = pMoniker->u.pData;
1848 if (pData)
1849 for (uint32_t i = 0; i < pData->cItems; i++)
1850 {
1851 RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix,
1852 "MonikerAttrib[%u]: ", i);
1853
1854 switch (pData->papItems[i]->enmType)
1855 {
1856 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V2:
1857 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1:
1858 {
1859 PCRTCRSPCSERIALIZEDPAGEHASHES pPgHashes = pData->papItems[i]->u.pPageHashes;
1860 uint32_t const cbHash = pData->papItems[i]->enmType
1861 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1
1862 ? 160/8 /*SHA-1*/ : 256/8 /*SHA-256*/;
1863 uint32_t const cPages = pPgHashes->RawData.Asn1Core.cb / (cbHash + sizeof(uint32_t));
1864
1865 RTPrintf("%sPage Hashes version %u - %u pages (%u bytes total)\n", pThis->szPrefix,
1866 pData->papItems[i]->enmType
1867 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1 ? 1 : 2,
1868 cPages, pPgHashes->RawData.Asn1Core.cb);
1869 if (pThis->cVerbosity > 0)
1870 {
1871 PCRTCRSPCPEIMAGEPAGEHASHES pPg = pPgHashes->pData;
1872 for (unsigned iPg = 0; iPg < cPages; iPg++)
1873 {
1874 uint32_t offHash = 0;
1875 do
1876 {
1877 if (offHash == 0)
1878 RTPrintf("%.*s Page#%04u/%#08x: ",
1879 offPrefix, pThis->szPrefix, iPg, pPg->Generic.offFile);
1880 else
1881 RTPrintf("%.*s ", offPrefix, pThis->szPrefix);
1882 uint32_t cbLeft = cbHash - offHash;
1883 if (cbLeft > 24)
1884 cbLeft = 16;
1885 RTPrintf("%.*Rhxs\n", cbLeft, &pPg->Generic.abHash[offHash]);
1886 offHash += cbLeft;
1887 } while (offHash < cbHash);
1888 pPg = (PCRTCRSPCPEIMAGEPAGEHASHES)&pPg->Generic.abHash[cbHash];
1889 }
1890
1891 if (pThis->cVerbosity > 3)
1892 RTPrintf("%.*Rhxd\n",
1893 pPgHashes->RawData.Asn1Core.cb,
1894 pPgHashes->RawData.Asn1Core.uData.pu8);
1895 }
1896 break;
1897 }
1898
1899 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_UNKNOWN:
1900 HandleShowExeWorkerDisplayObjIdSimple(pThis, &pData->papItems[i]->Type, "\n");
1901 break;
1902 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_NOT_PRESENT:
1903 RTPrintf("%sNot present!\n", pThis->szPrefix);
1904 break;
1905 default:
1906 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pData->papItems[i]->enmType);
1907 break;
1908 }
1909 pThis->szPrefix[offPrefix] = '\0';
1910 }
1911 else
1912 RTPrintf("%s pData is NULL!\n", pThis->szPrefix);
1913 }
1914 else
1915 RTPrintf("%s Moniker: Unknown UUID: %RTuuid\n",
1916 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
1917 }
1918 else
1919 RTPrintf("%s Moniker: not present\n", pThis->szPrefix);
1920 break;
1921 }
1922
1923 case RTCRSPCLINKCHOICE_URL:
1924 {
1925 const char *pszUrl = NULL;
1926 int rc = pPeImage->T0.File.u.pUrl
1927 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pUrl, &pszUrl, NULL)
1928 : VERR_NOT_FOUND;
1929 if (RT_SUCCESS(rc))
1930 RTPrintf("%s URL: '%s'\n", pThis->szPrefix, pszUrl);
1931 else
1932 RTPrintf("%s URL: rc=%Rrc\n", pThis->szPrefix, rc);
1933 break;
1934 }
1935
1936 case RTCRSPCLINKCHOICE_FILE:
1937 {
1938 const char *pszFile = NULL;
1939 int rc = pPeImage->T0.File.u.pT2 && pPeImage->T0.File.u.pT2->File.u.pAscii
1940 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pT2->File.u.pAscii, &pszFile, NULL)
1941 : VERR_NOT_FOUND;
1942 if (RT_SUCCESS(rc))
1943 RTPrintf("%s File: '%s'\n", pThis->szPrefix, pszFile);
1944 else
1945 RTPrintf("%s File: rc=%Rrc\n", pThis->szPrefix, rc);
1946 break;
1947 }
1948
1949 case RTCRSPCLINKCHOICE_NOT_PRESENT:
1950 RTPrintf("%s File not present!\n", pThis->szPrefix);
1951 break;
1952 default:
1953 RTPrintf("%s enmChoice=%d!\n", pThis->szPrefix, pPeImage->T0.File.enmChoice);
1954 break;
1955 }
1956 break;
1957 }
1958
1959 case RTCRSPCAAOVTYPE_UNKNOWN:
1960 HandleShowExeWorkerDisplayObjId(pThis, &pIndData->Data.Type, " Data Type: ", "\n");
1961 break;
1962 case RTCRSPCAAOVTYPE_NOT_PRESENT:
1963 RTPrintf("%s Data Type: Not present!\n", pThis->szPrefix);
1964 break;
1965 default:
1966 RTPrintf("%s Data Type: enmType=%d!\n", pThis->szPrefix, pIndData->Data.enmType);
1967 break;
1968 }
1969
1970 return VINF_SUCCESS;
1971}
1972
1973
1974/**
1975 * Display an PKCS#7 signed data instance.
1976 *
1977 * @returns IPRT status code.
1978 * @param pThis The show exe instance data.
1979 * @param pSignedData The signed data to display.
1980 * @param offPrefix The current prefix offset.
1981 * @param pContentInfo The content info structure (for the size).
1982 */
1983static int HandleShowExeWorkerPkcs7Display(PSHOWEXEPKCS7 pThis, PRTCRPKCS7SIGNEDDATA pSignedData, size_t offPrefix,
1984 PCRTCRPKCS7CONTENTINFO pContentInfo)
1985{
1986 pThis->szPrefix[offPrefix] = '\0';
1987 RTPrintf("%sPKCS#7 signature: %u (%#x) bytes\n", pThis->szPrefix,
1988 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core),
1989 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core));
1990
1991 /*
1992 * Display list of signing algorithms.
1993 */
1994 RTPrintf("%sDigestAlgorithms: ", pThis->szPrefix);
1995 if (pSignedData->DigestAlgorithms.cItems == 0)
1996 RTPrintf("none");
1997 for (unsigned i = 0; i < pSignedData->DigestAlgorithms.cItems; i++)
1998 {
1999 PCRTCRX509ALGORITHMIDENTIFIER pAlgoId = pSignedData->DigestAlgorithms.papItems[i];
2000 const char *pszDigestType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_QueryDigestType(pAlgoId));
2001 if (!pszDigestType)
2002 pszDigestType = pAlgoId->Algorithm.szObjId;
2003 RTPrintf(i == 0 ? "%s" : ", %s", pszDigestType);
2004 if (pThis->cVerbosity > 1)
2005 RTPrintf(" (%s)", pAlgoId->Algorithm.szObjId);
2006 }
2007 RTPrintf("\n");
2008
2009 /*
2010 * Display the signed data content.
2011 */
2012 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCRSPCINDIRECTDATACONTENT_OID) == 0)
2013 {
2014 RTPrintf("%s ContentType: SpcIndirectDataContent (" RTCRSPCINDIRECTDATACONTENT_OID ")\n", pThis->szPrefix);
2015 size_t offPrefix2 = RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " SPC Ind Data: ");
2016 HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(pThis, offPrefix2 + offPrefix,
2017 pSignedData->ContentInfo.u.pIndirectDataContent);
2018 pThis->szPrefix[offPrefix] = '\0';
2019 }
2020 else
2021 HandleShowExeWorkerDisplayObjId(pThis, &pSignedData->ContentInfo.ContentType, " ContentType: ", " - not implemented.\n");
2022
2023 /*
2024 * Display certificates (Certificates).
2025 */
2026 if (pSignedData->Certificates.cItems > 0)
2027 {
2028 RTPrintf("%s Certificates: %u\n", pThis->szPrefix, pSignedData->Certificates.cItems);
2029 if (pThis->cVerbosity >= 2)
2030 {
2031 for (uint32_t i = 0; i < pSignedData->Certificates.cItems; i++)
2032 {
2033 if (i != 0)
2034 RTPrintf("\n");
2035 RTPrintf("%s Certificate #%u:\n", pThis->szPrefix, i);
2036 RTAsn1Dump(RTCrPkcs7Cert_GetAsn1Core(pSignedData->Certificates.papItems[i]), 0,
2037 ((uint32_t)offPrefix + 9) / 2, RTStrmDumpPrintfV, g_pStdOut);
2038 }
2039 }
2040 /** @todo display certificates properly. */
2041 }
2042
2043 if (pSignedData->Crls.cb > 0)
2044 RTPrintf("%s CRLs: %u bytes\n", pThis->szPrefix, pSignedData->Crls.cb);
2045
2046 /*
2047 * Show signatures (SignerInfos).
2048 */
2049 unsigned const cSigInfos = pSignedData->SignerInfos.cItems;
2050 if (cSigInfos != 1)
2051 RTPrintf("%s SignerInfos: %u signers\n", pThis->szPrefix, cSigInfos);
2052 else
2053 RTPrintf("%s SignerInfos:\n", pThis->szPrefix);
2054 for (unsigned i = 0; i < cSigInfos; i++)
2055 {
2056 PRTCRPKCS7SIGNERINFO pSigInfo = pSignedData->SignerInfos.papItems[i];
2057 size_t offPrefix2 = offPrefix;
2058 if (cSigInfos != 1)
2059 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "SignerInfo[%u]: ", i);
2060
2061 int rc = RTAsn1Integer_ToString(&pSigInfo->IssuerAndSerialNumber.SerialNumber,
2062 pThis->szTmp, sizeof(pThis->szTmp), 0 /*fFlags*/, NULL);
2063 if (RT_FAILURE(rc))
2064 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
2065 RTPrintf("%s Serial No: %s\n", pThis->szPrefix, pThis->szTmp);
2066
2067 rc = RTCrX509Name_FormatAsString(&pSigInfo->IssuerAndSerialNumber.Name, pThis->szTmp, sizeof(pThis->szTmp), NULL);
2068 if (RT_FAILURE(rc))
2069 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
2070 RTPrintf("%s Issuer: %s\n", pThis->szPrefix, pThis->szTmp);
2071
2072 const char *pszType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_QueryDigestType(&pSigInfo->DigestAlgorithm));
2073 if (!pszType)
2074 pszType = pSigInfo->DigestAlgorithm.Algorithm.szObjId;
2075 RTPrintf("%s Digest Algorithm: %s", pThis->szPrefix, pszType);
2076 if (pThis->cVerbosity > 1)
2077 RTPrintf(" (%s)\n", pSigInfo->DigestAlgorithm.Algorithm.szObjId);
2078 else
2079 RTPrintf("\n");
2080
2081 HandleShowExeWorkerDisplayObjId(pThis, &pSigInfo->DigestEncryptionAlgorithm.Algorithm,
2082 "Digest Encryption Algorithm: ", "\n");
2083
2084 if (pSigInfo->AuthenticatedAttributes.cItems == 0)
2085 RTPrintf("%s Authenticated Attributes: none\n", pThis->szPrefix);
2086 else
2087 {
2088 RTPrintf("%s Authenticated Attributes: %u item%s\n", pThis->szPrefix,
2089 pSigInfo->AuthenticatedAttributes.cItems, pSigInfo->AuthenticatedAttributes.cItems > 1 ? "s" : "");
2090 for (unsigned j = 0; j < pSigInfo->AuthenticatedAttributes.cItems; j++)
2091 {
2092 PRTCRPKCS7ATTRIBUTE pAttr = pSigInfo->AuthenticatedAttributes.papItems[j];
2093 size_t offPrefix3 = offPrefix2 + RTStrPrintf(&pThis->szPrefix[offPrefix2], sizeof(pThis->szPrefix) - offPrefix2,
2094 " AuthAttrib[%u]: ", j);
2095 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
2096 }
2097 pThis->szPrefix[offPrefix2] = '\0';
2098 }
2099
2100 if (pSigInfo->UnauthenticatedAttributes.cItems == 0)
2101 RTPrintf("%s Unauthenticated Attributes: none\n", pThis->szPrefix);
2102 else
2103 {
2104 RTPrintf("%s Unauthenticated Attributes: %u item%s\n", pThis->szPrefix,
2105 pSigInfo->UnauthenticatedAttributes.cItems, pSigInfo->UnauthenticatedAttributes.cItems > 1 ? "s" : "");
2106 for (unsigned j = 0; j < pSigInfo->UnauthenticatedAttributes.cItems; j++)
2107 {
2108 PRTCRPKCS7ATTRIBUTE pAttr = pSigInfo->UnauthenticatedAttributes.papItems[j];
2109 size_t offPrefix3 = offPrefix2 + RTStrPrintf(&pThis->szPrefix[offPrefix2], sizeof(pThis->szPrefix) - offPrefix2,
2110 " UnauthAttrib[%u]: ", j);
2111 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
2112 }
2113 pThis->szPrefix[offPrefix2] = '\0';
2114 }
2115
2116 /** @todo show the encrypted stuff (EncryptedDigest)? */
2117 }
2118 pThis->szPrefix[offPrefix] = '\0';
2119
2120 return VINF_SUCCESS;
2121}
2122
2123
2124/*
2125 * The 'show-exe' command.
2126 */
2127static RTEXITCODE HelpShowExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2128{
2129 RT_NOREF_PV(enmLevel);
2130 RTStrmPrintf(pStrm,
2131 "show-exe [--verbose|-v] [--quiet|-q] <exe1> [exe2 [..]]\n");
2132 return RTEXITCODE_SUCCESS;
2133}
2134
2135
2136static RTEXITCODE HandleShowExe(int cArgs, char **papszArgs)
2137{
2138 /*
2139 * Parse arguments.
2140 */
2141 static const RTGETOPTDEF s_aOptions[] =
2142 {
2143 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2144 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2145 };
2146
2147 unsigned cVerbosity = 0;
2148 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
2149
2150 RTGETOPTSTATE GetState;
2151 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2152 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2153 RTGETOPTUNION ValueUnion;
2154 int ch;
2155 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
2156 {
2157 switch (ch)
2158 {
2159 case 'v': cVerbosity++; break;
2160 case 'q': cVerbosity = 0; break;
2161 case 'V': return HandleVersion(cArgs, papszArgs);
2162 case 'h': return HelpShowExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
2163 default: return RTGetOptPrintError(ch, &ValueUnion);
2164 }
2165 }
2166 if (ch != VINF_GETOPT_NOT_OPTION)
2167 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
2168
2169 /*
2170 * Do it.
2171 */
2172 unsigned iFile = 0;
2173 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2174 do
2175 {
2176 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
2177
2178 SHOWEXEPKCS7 This;
2179 RT_ZERO(This);
2180 This.cVerbosity = cVerbosity;
2181
2182 RTEXITCODE rcExitThis = SignToolPkcs7Exe_InitFromFile(&This, ValueUnion.psz, cVerbosity, enmLdrArch);
2183 if (rcExitThis == RTEXITCODE_SUCCESS)
2184 {
2185 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
2186 if (RT_FAILURE(rc))
2187 rcExit = RTEXITCODE_FAILURE;
2188 SignToolPkcs7Exe_Delete(&This);
2189 }
2190 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
2191 rcExit = rcExitThis;
2192
2193 iFile++;
2194 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
2195 if (ch != 0)
2196 return RTGetOptPrintError(ch, &ValueUnion);
2197
2198 return rcExit;
2199}
2200
2201
2202/*
2203 * The 'show-cat' command.
2204 */
2205static RTEXITCODE HelpShowCat(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2206{
2207 RT_NOREF_PV(enmLevel);
2208 RTStrmPrintf(pStrm,
2209 "show-cat [--verbose|-v] [--quiet|-q] <cat1> [cat2 [..]]\n");
2210 return RTEXITCODE_SUCCESS;
2211}
2212
2213
2214static RTEXITCODE HandleShowCat(int cArgs, char **papszArgs)
2215{
2216 /*
2217 * Parse arguments.
2218 */
2219 static const RTGETOPTDEF s_aOptions[] =
2220 {
2221 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2222 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2223 };
2224
2225 unsigned cVerbosity = 0;
2226
2227 RTGETOPTSTATE GetState;
2228 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2229 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2230 RTGETOPTUNION ValueUnion;
2231 int ch;
2232 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
2233 {
2234 switch (ch)
2235 {
2236 case 'v': cVerbosity++; break;
2237 case 'q': cVerbosity = 0; break;
2238 case 'V': return HandleVersion(cArgs, papszArgs);
2239 case 'h': return HelpShowCat(g_pStdOut, RTSIGNTOOLHELP_FULL);
2240 default: return RTGetOptPrintError(ch, &ValueUnion);
2241 }
2242 }
2243 if (ch != VINF_GETOPT_NOT_OPTION)
2244 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
2245
2246 /*
2247 * Do it.
2248 */
2249 unsigned iFile = 0;
2250 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2251 do
2252 {
2253 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
2254
2255 SHOWEXEPKCS7 This;
2256 RT_ZERO(This);
2257 This.cVerbosity = cVerbosity;
2258
2259 RTEXITCODE rcExitThis = SignToolPkcs7_InitFromFile(&This, ValueUnion.psz, cVerbosity);
2260 if (rcExitThis == RTEXITCODE_SUCCESS)
2261 {
2262 This.hLdrMod = NIL_RTLDRMOD;
2263
2264 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
2265 if (RT_FAILURE(rc))
2266 rcExit = RTEXITCODE_FAILURE;
2267 SignToolPkcs7Exe_Delete(&This);
2268 }
2269 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
2270 rcExit = rcExitThis;
2271
2272 iFile++;
2273 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
2274 if (ch != 0)
2275 return RTGetOptPrintError(ch, &ValueUnion);
2276
2277 return rcExit;
2278}
2279
2280
2281/*
2282 * The 'make-tainfo' command.
2283 */
2284static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2285{
2286 RT_NOREF_PV(enmLevel);
2287 RTStrmPrintf(pStrm,
2288 "make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
2289 return RTEXITCODE_SUCCESS;
2290}
2291
2292
2293typedef struct MAKETAINFOSTATE
2294{
2295 int cVerbose;
2296 const char *pszCert;
2297 const char *pszOutput;
2298} MAKETAINFOSTATE;
2299
2300
2301/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
2302static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
2303{
2304 RT_NOREF_PV(pErrInfo);
2305 return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
2306}
2307
2308
2309static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
2310{
2311 /*
2312 * Parse arguments.
2313 */
2314 static const RTGETOPTDEF s_aOptions[] =
2315 {
2316 { "--cert", 'c', RTGETOPT_REQ_STRING },
2317 { "--output", 'o', RTGETOPT_REQ_STRING },
2318 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2319 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2320 };
2321
2322 MAKETAINFOSTATE State = { 0, NULL, NULL };
2323
2324 RTGETOPTSTATE GetState;
2325 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2326 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2327 RTGETOPTUNION ValueUnion;
2328 int ch;
2329 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2330 {
2331 switch (ch)
2332 {
2333 case 'c':
2334 if (State.pszCert)
2335 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
2336 State.pszCert = ValueUnion.psz;
2337 break;
2338
2339 case 'o':
2340 case VINF_GETOPT_NOT_OPTION:
2341 if (State.pszOutput)
2342 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
2343 State.pszOutput = ValueUnion.psz;
2344 break;
2345
2346 case 'v': State.cVerbose++; break;
2347 case 'q': State.cVerbose = 0; break;
2348 case 'V': return HandleVersion(cArgs, papszArgs);
2349 case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
2350 default: return RTGetOptPrintError(ch, &ValueUnion);
2351 }
2352 }
2353 if (!State.pszCert)
2354 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
2355 if (!State.pszOutput)
2356 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
2357
2358 /*
2359 * Read the certificate.
2360 */
2361 RTERRINFOSTATIC StaticErrInfo;
2362 RTCRX509CERTIFICATE Certificate;
2363 rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
2364 RTErrInfoInitStatic(&StaticErrInfo));
2365 if (RT_FAILURE(rc))
2366 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
2367 State.pszCert, rc, StaticErrInfo.szMsg);
2368 /*
2369 * Construct the trust anchor information.
2370 */
2371 RTCRTAFTRUSTANCHORINFO TrustAnchor;
2372 rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
2373 if (RT_SUCCESS(rc))
2374 {
2375 /* Public key. */
2376 Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
2377 RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
2378 rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
2379 &g_RTAsn1DefaultAllocator);
2380 if (RT_FAILURE(rc))
2381 RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
2382 RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
2383
2384 /* Key Identifier. */
2385 PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
2386 if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
2387 pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
2388 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
2389 && RTCrX509Certificate_IsSelfSigned(&Certificate)
2390 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
2391 pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
2392 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
2393 && RTCrX509Certificate_IsSelfSigned(&Certificate)
2394 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
2395 pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
2396 if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
2397 {
2398 Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
2399 RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
2400 rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
2401 if (RT_FAILURE(rc))
2402 RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
2403 RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
2404 }
2405 else
2406 RTMsgWarning("No key identifier found or has zero length.");
2407
2408 /* Subject */
2409 if (RT_SUCCESS(rc))
2410 {
2411 Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
2412 rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
2413 if (RT_SUCCESS(rc))
2414 {
2415 Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
2416 RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
2417 rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
2418 &g_RTAsn1DefaultAllocator);
2419 if (RT_SUCCESS(rc))
2420 {
2421 RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
2422 rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
2423 if (RT_FAILURE(rc))
2424 RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
2425 }
2426 else
2427 RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
2428 }
2429 else
2430 RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
2431 }
2432
2433 /* Check that what we've constructed makes some sense. */
2434 if (RT_SUCCESS(rc))
2435 {
2436 rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
2437 if (RT_FAILURE(rc))
2438 RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2439 }
2440
2441 if (RT_SUCCESS(rc))
2442 {
2443 /*
2444 * Encode it and write it to the output file.
2445 */
2446 uint32_t cbEncoded;
2447 rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
2448 RTErrInfoInitStatic(&StaticErrInfo));
2449 if (RT_SUCCESS(rc))
2450 {
2451 if (State.cVerbose >= 1)
2452 RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
2453
2454 PRTSTREAM pStrm;
2455 rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
2456 if (RT_SUCCESS(rc))
2457 {
2458 rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
2459 handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
2460 if (RT_SUCCESS(rc))
2461 {
2462 rc = RTStrmClose(pStrm);
2463 if (RT_SUCCESS(rc))
2464 RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
2465 else
2466 RTMsgError("RTStrmClose failed: %Rrc", rc);
2467 }
2468 else
2469 {
2470 RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2471 RTStrmClose(pStrm);
2472 }
2473 }
2474 else
2475 RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
2476 }
2477 else
2478 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2479 }
2480
2481 RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
2482 }
2483 else
2484 RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
2485
2486 RTCrX509Certificate_Delete(&Certificate);
2487 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2488}
2489
2490
2491
2492/*
2493 * The 'version' command.
2494 */
2495static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2496{
2497 RT_NOREF_PV(enmLevel);
2498 RTStrmPrintf(pStrm, "version\n");
2499 return RTEXITCODE_SUCCESS;
2500}
2501
2502static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
2503{
2504 RT_NOREF_PV(cArgs); RT_NOREF_PV(papszArgs);
2505#ifndef IN_BLD_PROG /* RTBldCfgVersion or RTBldCfgRevision in build time IPRT lib. */
2506 RTPrintf("%s\n", RTBldCfgVersion());
2507 return RTEXITCODE_SUCCESS;
2508#else
2509 return RTEXITCODE_FAILURE;
2510#endif
2511}
2512
2513
2514
2515/**
2516 * Command mapping.
2517 */
2518static struct
2519{
2520 /** The command. */
2521 const char *pszCmd;
2522 /**
2523 * Handle the command.
2524 * @returns Program exit code.
2525 * @param cArgs Number of arguments.
2526 * @param papszArgs The argument vector, starting with the command name.
2527 */
2528 RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
2529 /**
2530 * Produce help.
2531 * @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
2532 * @param pStrm Where to send help text.
2533 * @param enmLevel The level of the help information.
2534 */
2535 RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
2536}
2537/** Mapping commands to handler and helper functions. */
2538const g_aCommands[] =
2539{
2540 { "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
2541 { "add-nested-exe-signature", HandleAddNestedExeSignature, HelpAddNestedExeSignature },
2542 { "add-nested-cat-signature", HandleAddNestedCatSignature, HelpAddNestedCatSignature },
2543#ifndef IPRT_IN_BUILD_TOOL
2544 { "verify-exe", HandleVerifyExe, HelpVerifyExe },
2545#endif
2546 { "show-exe", HandleShowExe, HelpShowExe },
2547 { "show-cat", HandleShowCat, HelpShowCat },
2548 { "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
2549 { "help", HandleHelp, HelpHelp },
2550 { "--help", HandleHelp, NULL },
2551 { "-h", HandleHelp, NULL },
2552 { "version", HandleVersion, HelpVersion },
2553 { "--version", HandleVersion, NULL },
2554 { "-V", HandleVersion, NULL },
2555};
2556
2557
2558/*
2559 * The 'help' command.
2560 */
2561static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2562{
2563 RT_NOREF_PV(enmLevel);
2564 RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
2565 return RTEXITCODE_SUCCESS;
2566}
2567
2568static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
2569{
2570 RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
2571 uint32_t cShowed = 0;
2572 for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
2573 {
2574 if (g_aCommands[iCmd].pfnHelp)
2575 {
2576 bool fShow = false;
2577 if (cArgs <= 1)
2578 fShow = true;
2579 else
2580 {
2581 for (int iArg = 1; iArg < cArgs; iArg++)
2582 if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
2583 {
2584 fShow = true;
2585 break;
2586 }
2587 }
2588 if (fShow)
2589 {
2590 g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel);
2591 cShowed++;
2592 }
2593 }
2594 }
2595 return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2596}
2597
2598
2599
2600int main(int argc, char **argv)
2601{
2602 int rc = RTR3InitExe(argc, &argv, 0);
2603 if (RT_FAILURE(rc))
2604 return RTMsgInitFailure(rc);
2605
2606 /*
2607 * Parse global arguments.
2608 */
2609 int iArg = 1;
2610 /* none presently. */
2611
2612 /*
2613 * Command dispatcher.
2614 */
2615 if (iArg < argc)
2616 {
2617 const char *pszCmd = argv[iArg];
2618 uint32_t i = RT_ELEMENTS(g_aCommands);
2619 while (i-- > 0)
2620 if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
2621 return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
2622 RTMsgError("Unknown command '%s'.", pszCmd);
2623 }
2624 else
2625 RTMsgError("No command given. (try --help)");
2626
2627 return RTEXITCODE_SYNTAX;
2628}
2629
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