VirtualBox

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

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

*: Made RT_UOFFSETOF, RT_OFFSETOF, RT_UOFFSETOF_ADD and RT_OFFSETOF_ADD work like builtin_offsetof() and require compile time resolvable requests, adding RT_UOFFSETOF_DYN for the dynamic questions that can only be answered at runtime.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 105.5 KB
Line 
1/* $Id: RTSignTool.cpp 73097 2018-07-12 21:06:33Z 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
632 /*
633 * Decode it.
634 */
635 rc = SignToolPkcs7_Decode(pThis, false /*fCatalog*/);
636 if (RT_SUCCESS(rc))
637 return RTEXITCODE_SUCCESS;
638 }
639 else
640 RTMsgError("RTLdrQueryPropEx/RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc\n", pszFilename, rc);
641 }
642 else if (RT_SUCCESS(rc))
643 RTMsgInfo("'%s': not signed\n", pszFilename);
644 else
645 RTMsgError("RTLdrQueryProp/RTLDRPROP_IS_SIGNED failed on '%s': %Rrc\n", pszFilename, rc);
646 }
647 else
648 RTMsgError("Error opening executable image '%s': %Rrc", pszFilename, rc);
649
650 SignToolPkcs7Exe_Delete(pThis);
651 return RTEXITCODE_FAILURE;
652}
653
654
655/**
656 * Calculates the checksum of an executable.
657 *
658 * @returns Success indicator (errors are reported)
659 * @param pThis The exe file to checksum.
660 * @param hFile The file handle.
661 * @param puCheckSum Where to return the checksum.
662 */
663static bool SignToolPkcs7Exe_CalcPeCheckSum(PSIGNTOOLPKCS7EXE pThis, RTFILE hFile, uint32_t *puCheckSum)
664{
665#ifdef RT_OS_WINDOWS
666 /*
667 * Try use IMAGEHLP!MapFileAndCheckSumW first.
668 */
669 PRTUTF16 pwszPath;
670 int rc = RTStrToUtf16(pThis->pszFilename, &pwszPath);
671 if (RT_SUCCESS(rc))
672 {
673 decltype(MapFileAndCheckSumW) *pfnMapFileAndCheckSumW;
674 pfnMapFileAndCheckSumW = (decltype(MapFileAndCheckSumW) *)RTLdrGetSystemSymbol("IMAGEHLP.DLL", "MapFileAndCheckSumW");
675 if (pfnMapFileAndCheckSumW)
676 {
677 DWORD uHeaderSum = UINT32_MAX;
678 DWORD uCheckSum = UINT32_MAX;
679 DWORD dwRc = pfnMapFileAndCheckSumW(pwszPath, &uHeaderSum, &uCheckSum);
680 if (dwRc == CHECKSUM_SUCCESS)
681 {
682 *puCheckSum = uCheckSum;
683 return true;
684 }
685 }
686 }
687#endif
688
689 RT_NOREF(pThis, hFile, puCheckSum);
690 RTMsgError("Implement check sum calcuation fallback!");
691 return false;
692}
693
694
695/**
696 * Writes the signature to the file.
697 *
698 * This has the side-effect of closing the hLdrMod member. So, it can only be
699 * called once!
700 *
701 * Caller must have called SignToolPkcs7_Encode() prior to this function.
702 *
703 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
704 * message on failure.
705 * @param pThis The file which to write.
706 * @param cVerbosity The verbosity.
707 */
708static RTEXITCODE SignToolPkcs7Exe_WriteSignatureToFile(PSIGNTOOLPKCS7EXE pThis, unsigned cVerbosity)
709{
710 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
711
712 /*
713 * Get the file header offset and arch before closing the destination handle.
714 */
715 uint32_t offNtHdrs;
716 int rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_FILE_OFF_HEADER, &offNtHdrs, sizeof(offNtHdrs));
717 if (RT_SUCCESS(rc))
718 {
719 RTLDRARCH enmLdrArch = RTLdrGetArch(pThis->hLdrMod);
720 if (enmLdrArch != RTLDRARCH_INVALID)
721 {
722 RTLdrClose(pThis->hLdrMod);
723 pThis->hLdrMod = NIL_RTLDRMOD;
724 unsigned cbNtHdrs = 0;
725 switch (enmLdrArch)
726 {
727 case RTLDRARCH_AMD64:
728 cbNtHdrs = sizeof(IMAGE_NT_HEADERS64);
729 break;
730 case RTLDRARCH_X86_32:
731 cbNtHdrs = sizeof(IMAGE_NT_HEADERS32);
732 break;
733 default:
734 RTMsgError("Unknown image arch: %d", enmLdrArch);
735 }
736 if (cbNtHdrs > 0)
737 {
738 if (cVerbosity > 0)
739 RTMsgInfo("offNtHdrs=%#x cbNtHdrs=%u\n", offNtHdrs, cbNtHdrs);
740
741 /*
742 * Open the executable file for writing.
743 */
744 RTFILE hFile;
745 rc = RTFileOpen(&hFile, pThis->pszFilename, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
746 if (RT_SUCCESS(rc))
747 {
748 /* Read the file header and locate the security directory entry. */
749 union
750 {
751 IMAGE_NT_HEADERS32 NtHdrs32;
752 IMAGE_NT_HEADERS64 NtHdrs64;
753 } uBuf;
754 PIMAGE_DATA_DIRECTORY pSecDir = cbNtHdrs == sizeof(IMAGE_NT_HEADERS64)
755 ? &uBuf.NtHdrs64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]
756 : &uBuf.NtHdrs32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
757
758 rc = RTFileReadAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
759 if ( RT_SUCCESS(rc)
760 && uBuf.NtHdrs32.Signature == IMAGE_NT_SIGNATURE)
761 {
762 /*
763 * Drop any old signature by truncating the file.
764 */
765 if ( pSecDir->Size > 8
766 && pSecDir->VirtualAddress > offNtHdrs + sizeof(IMAGE_NT_HEADERS32))
767 {
768 rc = RTFileSetSize(hFile, pSecDir->VirtualAddress);
769 if (RT_FAILURE(rc))
770 RTMsgError("Error truncating file to %#x bytes: %Rrc", pSecDir->VirtualAddress, rc);
771 }
772 else
773 rc = RTMsgErrorRc(VERR_BAD_EXE_FORMAT, "Bad security directory entry: VA=%#x Size=%#x",
774 pSecDir->VirtualAddress, pSecDir->Size);
775 if (RT_SUCCESS(rc))
776 {
777 /*
778 * Sector align the signature portion.
779 */
780 uint32_t const cbWinCert = RT_UOFFSETOF(WIN_CERTIFICATE, bCertificate);
781 uint64_t offCur = 0;
782 rc = RTFileGetSize(hFile, &offCur);
783 if ( RT_SUCCESS(rc)
784 && offCur < _2G)
785 {
786 if (offCur & 0x1ff)
787 {
788 uint32_t cbNeeded = 0x200 - ((uint32_t)offCur & 0x1ff);
789 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbNeeded, NULL);
790 if (RT_SUCCESS(rc))
791 offCur += cbNeeded;
792 }
793 if (RT_SUCCESS(rc))
794 {
795 /*
796 * Write the header followed by the signature data.
797 */
798 uint32_t const cbZeroPad = (uint32_t)(RT_ALIGN_Z(pThis->cbNewBuf, 8) - pThis->cbNewBuf);
799 pSecDir->VirtualAddress = (uint32_t)offCur;
800 pSecDir->Size = cbWinCert + (uint32_t)pThis->cbNewBuf + cbZeroPad;
801 if (cVerbosity >= 2)
802 RTMsgInfo("Writing %u (%#x) bytes of signature at %#x (%u).\n",
803 pSecDir->Size, pSecDir->Size, pSecDir->VirtualAddress, pSecDir->VirtualAddress);
804
805 WIN_CERTIFICATE WinCert;
806 WinCert.dwLength = pSecDir->Size;
807 WinCert.wRevision = WIN_CERT_REVISION_2_0;
808 WinCert.wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
809
810 rc = RTFileWriteAt(hFile, offCur, &WinCert, cbWinCert, NULL);
811 if (RT_SUCCESS(rc))
812 {
813 offCur += cbWinCert;
814 rc = RTFileWriteAt(hFile, offCur, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
815 }
816 if (RT_SUCCESS(rc) && cbZeroPad)
817 {
818 offCur += pThis->cbNewBuf;
819 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbZeroPad, NULL);
820 }
821 if (RT_SUCCESS(rc))
822 {
823 /*
824 * Reset the checksum (sec dir updated already) and rewrite the header.
825 */
826 uBuf.NtHdrs32.OptionalHeader.CheckSum = 0;
827 offCur = offNtHdrs;
828 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
829 if (RT_SUCCESS(rc))
830 rc = RTFileFlush(hFile);
831 if (RT_SUCCESS(rc))
832 {
833 /*
834 * Calc checksum and write out the header again.
835 */
836 uint32_t uCheckSum = UINT32_MAX;
837 if (SignToolPkcs7Exe_CalcPeCheckSum(pThis, hFile, &uCheckSum))
838 {
839 uBuf.NtHdrs32.OptionalHeader.CheckSum = uCheckSum;
840 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
841 if (RT_SUCCESS(rc))
842 rc = RTFileFlush(hFile);
843 if (RT_SUCCESS(rc))
844 {
845 rc = RTFileClose(hFile);
846 if (RT_SUCCESS(rc))
847 return RTEXITCODE_SUCCESS;
848 RTMsgError("RTFileClose failed: %Rrc\n", rc);
849 return RTEXITCODE_FAILURE;
850 }
851 }
852 }
853 }
854 }
855 if (RT_FAILURE(rc))
856 RTMsgError("Write error at %#RX64: %Rrc", offCur, rc);
857 }
858 else if (RT_SUCCESS(rc))
859 RTMsgError("File to big: %'RU64 bytes", offCur);
860 else
861 RTMsgError("RTFileGetSize failed: %Rrc", rc);
862 }
863 }
864 else if (RT_SUCCESS(rc))
865 RTMsgError("Not NT executable header!");
866 else
867 RTMsgError("Error reading NT headers (%#x bytes) at %#x: %Rrc", cbNtHdrs, offNtHdrs, rc);
868 RTFileClose(hFile);
869 }
870 else
871 RTMsgError("Failed to open '%s' for writing: %Rrc", pThis->pszFilename, rc);
872 }
873 }
874 else
875 RTMsgError("RTLdrGetArch failed!");
876 }
877 else
878 RTMsgError("RTLdrQueryProp/RTLDRPROP_FILE_OFF_HEADER failed: %Rrc", rc);
879 return RTEXITCODE_FAILURE;
880}
881
882
883
884/*
885 * The 'extract-exe-signer-cert' command.
886 */
887static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
888{
889 RT_NOREF_PV(enmLevel);
890 RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--signature-index|-i <num>] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
891 return RTEXITCODE_SUCCESS;
892}
893
894static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
895{
896 /*
897 * Parse arguments.
898 */
899 static const RTGETOPTDEF s_aOptions[] =
900 {
901 { "--ber", 'b', RTGETOPT_REQ_NOTHING },
902 { "--cer", 'c', RTGETOPT_REQ_NOTHING },
903 { "--der", 'd', RTGETOPT_REQ_NOTHING },
904 { "--exe", 'e', RTGETOPT_REQ_STRING },
905 { "--output", 'o', RTGETOPT_REQ_STRING },
906 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
907 };
908
909 const char *pszExe = NULL;
910 const char *pszOut = NULL;
911 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
912 unsigned cVerbosity = 0;
913 uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
914 uint32_t iSignature = 0;
915
916 RTGETOPTSTATE GetState;
917 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
918 AssertRCReturn(rc, RTEXITCODE_FAILURE);
919 RTGETOPTUNION ValueUnion;
920 int ch;
921 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
922 {
923 switch (ch)
924 {
925 case 'e': pszExe = ValueUnion.psz; break;
926 case 'o': pszOut = ValueUnion.psz; break;
927 case 'b': fCursorFlags = 0; break;
928 case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
929 case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
930 case 'i': iSignature = ValueUnion.u32; break;
931 case 'V': return HandleVersion(cArgs, papszArgs);
932 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
933
934 case VINF_GETOPT_NOT_OPTION:
935 if (!pszExe)
936 pszExe = ValueUnion.psz;
937 else if (!pszOut)
938 pszOut = ValueUnion.psz;
939 else
940 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
941 break;
942
943 default:
944 return RTGetOptPrintError(ch, &ValueUnion);
945 }
946 }
947 if (!pszExe)
948 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
949 if (!pszOut)
950 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
951 if (RTPathExists(pszOut))
952 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
953
954 /*
955 * Do it.
956 */
957 /* Read & decode the PKCS#7 signature. */
958 SIGNTOOLPKCS7EXE This;
959 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
960 if (rcExit == RTEXITCODE_SUCCESS)
961 {
962 /* Find the signing certificate (ASSUMING that the certificate used is shipped in the set of certificates). */
963 PRTCRPKCS7SIGNEDDATA pSignedData;
964 PCRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(&This, iSignature, &pSignedData);
965 rcExit = RTEXITCODE_FAILURE;
966 if (pSignerInfo)
967 {
968 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSignedData->SignerInfos.papItems[0]->IssuerAndSerialNumber;
969 PCRTCRX509CERTIFICATE pCert;
970 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
971 &pISN->Name, &pISN->SerialNumber);
972 if (pCert)
973 {
974 /*
975 * Write it out.
976 */
977 RTFILE hFile;
978 rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE);
979 if (RT_SUCCESS(rc))
980 {
981 uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
982 rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
983 cbCert, NULL);
984 if (RT_SUCCESS(rc))
985 {
986 rc = RTFileClose(hFile);
987 if (RT_SUCCESS(rc))
988 {
989 hFile = NIL_RTFILE;
990 rcExit = RTEXITCODE_SUCCESS;
991 RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut);
992 }
993 else
994 RTMsgError("RTFileClose failed: %Rrc", rc);
995 }
996 else
997 RTMsgError("RTFileWrite failed: %Rrc", rc);
998 RTFileClose(hFile);
999 }
1000 else
1001 RTMsgError("Error opening '%s' for writing: %Rrc", pszOut, rc);
1002 }
1003 else
1004 RTMsgError("Certificate not found.");
1005 }
1006 else
1007 RTMsgError("Could not locate signature #%u!", iSignature);
1008
1009 /* Delete the signature data. */
1010 SignToolPkcs7Exe_Delete(&This);
1011 }
1012 return rcExit;
1013}
1014
1015
1016/*
1017 * The 'add-nested-exe-signature' command.
1018 */
1019static RTEXITCODE HelpAddNestedExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1020{
1021 RT_NOREF_PV(enmLevel);
1022 RTStrmPrintf(pStrm, "add-nested-exe-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-exe> <source-exe>\n");
1023 if (enmLevel == RTSIGNTOOLHELP_FULL)
1024 RTStrmPrintf(pStrm,
1025 "\n"
1026 "The --debug option allows the source-exe to be omitted in order to test the\n"
1027 "encoding and PE file modification.\n"
1028 "\n"
1029 "The --prepend option puts the nested signature first rather than appending it\n"
1030 "to the end of of the nested signature set. Windows reads nested signatures in\n"
1031 "reverse order, so --prepend will logically putting it last.\n"
1032 );
1033 return RTEXITCODE_SUCCESS;
1034}
1035
1036
1037static RTEXITCODE HandleAddNestedExeSignature(int cArgs, char **papszArgs)
1038{
1039 /*
1040 * Parse arguments.
1041 */
1042 static const RTGETOPTDEF s_aOptions[] =
1043 {
1044 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
1045 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1046 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
1047 };
1048
1049 const char *pszDst = NULL;
1050 const char *pszSrc = NULL;
1051 unsigned cVerbosity = 0;
1052 bool fDebug = false;
1053 bool fPrepend = false;
1054
1055 RTGETOPTSTATE GetState;
1056 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1057 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1058 RTGETOPTUNION ValueUnion;
1059 int ch;
1060 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1061 {
1062 switch (ch)
1063 {
1064 case 'v': cVerbosity++; break;
1065 case 'd': fDebug = pszSrc == NULL; break;
1066 case 'p': fPrepend = true; break;
1067 case 'V': return HandleVersion(cArgs, papszArgs);
1068 case 'h': return HelpAddNestedExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
1069
1070 case VINF_GETOPT_NOT_OPTION:
1071 if (!pszDst)
1072 pszDst = ValueUnion.psz;
1073 else if (!pszSrc)
1074 {
1075 pszSrc = ValueUnion.psz;
1076 fDebug = false;
1077 }
1078 else
1079 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
1080 break;
1081
1082 default:
1083 return RTGetOptPrintError(ch, &ValueUnion);
1084 }
1085 }
1086 if (!pszDst)
1087 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination executable given.");
1088 if (!pszSrc && !fDebug)
1089 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source executable file given.");
1090
1091 /*
1092 * Do it.
1093 */
1094 /* Read & decode the source PKCS#7 signature. */
1095 SIGNTOOLPKCS7EXE Src;
1096 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7Exe_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
1097 if (rcExit == RTEXITCODE_SUCCESS)
1098 {
1099 /* Ditto for the destination PKCS#7 signature. */
1100 SIGNTOOLPKCS7EXE Dst;
1101 rcExit = SignToolPkcs7Exe_InitFromFile(&Dst, pszDst, cVerbosity);
1102 if (rcExit == RTEXITCODE_SUCCESS)
1103 {
1104 /* Do the signature manipulation. */
1105 if (pszSrc)
1106 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
1107 if (rcExit == RTEXITCODE_SUCCESS)
1108 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
1109
1110 /* Update the destination executable file. */
1111 if (rcExit == RTEXITCODE_SUCCESS)
1112 rcExit = SignToolPkcs7Exe_WriteSignatureToFile(&Dst, cVerbosity);
1113
1114 SignToolPkcs7Exe_Delete(&Dst);
1115 }
1116 if (pszSrc)
1117 SignToolPkcs7Exe_Delete(&Src);
1118 }
1119
1120 return rcExit;
1121}
1122
1123
1124/*
1125 * The 'add-nested-cat-signature' command.
1126 */
1127static RTEXITCODE HelpAddNestedCatSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1128{
1129 RT_NOREF_PV(enmLevel);
1130 RTStrmPrintf(pStrm, "add-nested-cat-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-cat> <source-cat>\n");
1131 if (enmLevel == RTSIGNTOOLHELP_FULL)
1132 RTStrmPrintf(pStrm,
1133 "\n"
1134 "The --debug option allows the source-cat to be omitted in order to test the\n"
1135 "ASN.1 re-encoding of the destination catalog file.\n"
1136 "\n"
1137 "The --prepend option puts the nested signature first rather than appending it\n"
1138 "to the end of of the nested signature set. Windows reads nested signatures in\n"
1139 "reverse order, so --prepend will logically putting it last.\n"
1140 );
1141 return RTEXITCODE_SUCCESS;
1142}
1143
1144
1145static RTEXITCODE HandleAddNestedCatSignature(int cArgs, char **papszArgs)
1146{
1147 /*
1148 * Parse arguments.
1149 */
1150 static const RTGETOPTDEF s_aOptions[] =
1151 {
1152 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
1153 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1154 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
1155 };
1156
1157 const char *pszDst = NULL;
1158 const char *pszSrc = NULL;
1159 unsigned cVerbosity = 0;
1160 bool fDebug = false;
1161 bool fPrepend = false;
1162
1163 RTGETOPTSTATE GetState;
1164 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1165 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1166 RTGETOPTUNION ValueUnion;
1167 int ch;
1168 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1169 {
1170 switch (ch)
1171 {
1172 case 'v': cVerbosity++; break;
1173 case 'd': fDebug = pszSrc == NULL; break;
1174 case 'p': fPrepend = true; break;
1175 case 'V': return HandleVersion(cArgs, papszArgs);
1176 case 'h': return HelpAddNestedCatSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
1177
1178 case VINF_GETOPT_NOT_OPTION:
1179 if (!pszDst)
1180 pszDst = ValueUnion.psz;
1181 else if (!pszSrc)
1182 {
1183 pszSrc = ValueUnion.psz;
1184 fDebug = false;
1185 }
1186 else
1187 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
1188 break;
1189
1190 default:
1191 return RTGetOptPrintError(ch, &ValueUnion);
1192 }
1193 }
1194 if (!pszDst)
1195 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination catalog file given.");
1196 if (!pszSrc && !fDebug)
1197 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source catalog file given.");
1198
1199 /*
1200 * Do it.
1201 */
1202 /* Read & decode the source PKCS#7 signature. */
1203 SIGNTOOLPKCS7 Src;
1204 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
1205 if (rcExit == RTEXITCODE_SUCCESS)
1206 {
1207 /* Ditto for the destination PKCS#7 signature. */
1208 SIGNTOOLPKCS7EXE Dst;
1209 rcExit = SignToolPkcs7_InitFromFile(&Dst, pszDst, cVerbosity);
1210 if (rcExit == RTEXITCODE_SUCCESS)
1211 {
1212 /* Do the signature manipulation. */
1213 if (pszSrc)
1214 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
1215 if (rcExit == RTEXITCODE_SUCCESS)
1216 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
1217
1218 /* Update the destination executable file. */
1219 if (rcExit == RTEXITCODE_SUCCESS)
1220 rcExit = SignToolPkcs7_WriteSignatureToFile(&Dst, pszDst, cVerbosity);
1221
1222 SignToolPkcs7_Delete(&Dst);
1223 }
1224 if (pszSrc)
1225 SignToolPkcs7_Delete(&Src);
1226 }
1227
1228 return rcExit;
1229}
1230
1231#ifndef IPRT_IN_BUILD_TOOL
1232
1233/*
1234 * The 'verify-exe' command.
1235 */
1236static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
1237{
1238 RT_NOREF_PV(enmLevel);
1239 RTStrmPrintf(pStrm,
1240 "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n"
1241 " [--type <win|osx>] <exe1> [exe2 [..]]\n");
1242 return RTEXITCODE_SUCCESS;
1243}
1244
1245typedef struct VERIFYEXESTATE
1246{
1247 RTCRSTORE hRootStore;
1248 RTCRSTORE hKernelRootStore;
1249 RTCRSTORE hAdditionalStore;
1250 bool fKernel;
1251 int cVerbose;
1252 enum { kSignType_Windows, kSignType_OSX } enmSignType;
1253 uint64_t uTimestamp;
1254 RTLDRARCH enmLdrArch;
1255} VERIFYEXESTATE;
1256
1257# ifdef VBOX
1258/** Certificate store load set.
1259 * Declared outside HandleVerifyExe because of braindead gcc visibility crap. */
1260struct STSTORESET
1261{
1262 RTCRSTORE hStore;
1263 PCSUPTAENTRY paTAs;
1264 unsigned cTAs;
1265};
1266# endif
1267
1268/**
1269 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
1270 * Standard code signing. Use this for Microsoft SPC.}
1271 */
1272static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
1273 void *pvUser, PRTERRINFO pErrInfo)
1274{
1275 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
1276 uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0;
1277
1278 /*
1279 * Dump all the paths.
1280 */
1281 if (pState->cVerbose > 0)
1282 {
1283 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
1284 {
1285 RTPrintf("---\n");
1286 RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
1287 *pErrInfo->pszMsg = '\0';
1288 }
1289 RTPrintf("---\n");
1290 }
1291
1292 /*
1293 * Test signing certificates normally doesn't have all the necessary
1294 * features required below. So, treat them as special cases.
1295 */
1296 if ( hCertPaths == NIL_RTCRX509CERTPATHS
1297 && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
1298 {
1299 RTMsgInfo("Test signed.\n");
1300 return VINF_SUCCESS;
1301 }
1302
1303 if (hCertPaths == NIL_RTCRX509CERTPATHS)
1304 RTMsgInfo("Signed by trusted certificate.\n");
1305
1306 /*
1307 * Standard code signing capabilites required.
1308 */
1309 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
1310 if ( RT_SUCCESS(rc)
1311 && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
1312 {
1313 /*
1314 * If kernel signing, a valid certificate path must be anchored by the
1315 * microsoft kernel signing root certificate. The only alternative is
1316 * test signing.
1317 */
1318 if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS)
1319 {
1320 uint32_t cFound = 0;
1321 uint32_t cValid = 0;
1322 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
1323 {
1324 bool fTrusted;
1325 PCRTCRX509NAME pSubject;
1326 PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
1327 int rcVerify;
1328 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
1329 NULL, NULL /*pCertCtx*/, &rcVerify);
1330 AssertRCBreak(rc);
1331
1332 if (RT_SUCCESS(rcVerify))
1333 {
1334 Assert(fTrusted);
1335 cValid++;
1336
1337 /* Search the kernel signing root store for a matching anchor. */
1338 RTCRSTORECERTSEARCH Search;
1339 rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search);
1340 AssertRCBreak(rc);
1341 PCRTCRCERTCTX pCertCtx;
1342 while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL)
1343 {
1344 PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo;
1345 if (pCertCtx->pCert)
1346 pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
1347 else if (pCertCtx->pTaInfo)
1348 pPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
1349 else
1350 pPubKeyInfo = NULL;
1351 if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0)
1352 cFound++;
1353 RTCrCertCtxRelease(pCertCtx);
1354 }
1355
1356 int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2);
1357 }
1358 }
1359 if (RT_SUCCESS(rc) && cFound == 0)
1360 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
1361 if (RT_SUCCESS(rc) && cValid != 2)
1362 RTMsgWarning("%u valid paths, expected 2", cValid);
1363 }
1364 }
1365
1366 return rc;
1367}
1368
1369
1370/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
1371static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
1372 void const *pvSignature, size_t cbSignature,
1373 PRTERRINFO pErrInfo, void *pvUser)
1374{
1375 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
1376 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(cbSignature);
1377
1378 switch (enmSignature)
1379 {
1380 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
1381 {
1382 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
1383
1384 RTTIMESPEC ValidationTime;
1385 RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp);
1386
1387 /*
1388 * Dump the signed data if so requested.
1389 */
1390 if (pState->cVerbose)
1391 RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
1392
1393
1394 /*
1395 * Do the actual verification. Will have to modify this so it takes
1396 * the authenticode policies into account.
1397 */
1398 return RTCrPkcs7VerifySignedData(pContentInfo,
1399 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
1400 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
1401 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT,
1402 pState->hAdditionalStore, pState->hRootStore, &ValidationTime,
1403 VerifyExecCertVerifyCallback, pState, pErrInfo);
1404 }
1405
1406 default:
1407 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature);
1408 }
1409}
1410
1411/** Worker for HandleVerifyExe. */
1412static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
1413{
1414 /*
1415 * Open the executable image and verify it.
1416 */
1417 RTLDRMOD hLdrMod;
1418 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod);
1419 if (RT_FAILURE(rc))
1420 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc);
1421
1422
1423 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pState->uTimestamp, sizeof(pState->uTimestamp));
1424 if (RT_SUCCESS(rc))
1425 {
1426 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
1427 if (RT_SUCCESS(rc))
1428 RTMsgInfo("'%s' is valid.\n", pszFilename);
1429 else if (rc == VERR_CR_X509_CPV_NOT_VALID_AT_TIME)
1430 {
1431 RTTIMESPEC Now;
1432 pState->uTimestamp = RTTimeSpecGetSeconds(RTTimeNow(&Now));
1433 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
1434 if (RT_SUCCESS(rc))
1435 RTMsgInfo("'%s' is valid now, but not at link time.\n", pszFilename);
1436 }
1437 if (RT_FAILURE(rc))
1438 RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg);
1439 }
1440 else
1441 RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pszFilename, rc);
1442
1443 int rc2 = RTLdrClose(hLdrMod);
1444 if (RT_FAILURE(rc2))
1445 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
1446 if (RT_FAILURE(rc))
1447 return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
1448
1449 return RTEXITCODE_SUCCESS;
1450}
1451
1452
1453static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
1454{
1455 RTERRINFOSTATIC StaticErrInfo;
1456
1457 /* Note! This code does not try to clean up the crypto stores on failure.
1458 This is intentional as the code is only expected to be used in a
1459 one-command-per-process environment where we do exit() upon
1460 returning from this function. */
1461
1462 /*
1463 * Parse arguments.
1464 */
1465 static const RTGETOPTDEF s_aOptions[] =
1466 {
1467 { "--kernel", 'k', RTGETOPT_REQ_NOTHING },
1468 { "--root", 'r', RTGETOPT_REQ_STRING },
1469 { "--additional", 'a', RTGETOPT_REQ_STRING },
1470 { "--add", 'a', RTGETOPT_REQ_STRING },
1471 { "--type", 't', RTGETOPT_REQ_STRING },
1472 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1473 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
1474 };
1475
1476 VERIFYEXESTATE State =
1477 {
1478 NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false,
1479 VERIFYEXESTATE::kSignType_Windows, 0, RTLDRARCH_WHATEVER
1480 };
1481 int rc = RTCrStoreCreateInMem(&State.hRootStore, 0);
1482 if (RT_SUCCESS(rc))
1483 rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0);
1484 if (RT_SUCCESS(rc))
1485 rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0);
1486 if (RT_FAILURE(rc))
1487 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
1488
1489 RTGETOPTSTATE GetState;
1490 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1491 AssertRCReturn(rc, RTEXITCODE_FAILURE);
1492 RTGETOPTUNION ValueUnion;
1493 int ch;
1494 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
1495 {
1496 switch (ch)
1497 {
1498 case 'r': case 'a':
1499 rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore,
1500 RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR,
1501 ValueUnion.psz, RTErrInfoInitStatic(&StaticErrInfo));
1502 if (RT_FAILURE(rc))
1503 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s",
1504 ValueUnion.psz, rc, StaticErrInfo.szMsg);
1505 if (RTErrInfoIsSet(&StaticErrInfo.Core))
1506 RTMsgWarning("Warnings loading certificate '%s': %s", ValueUnion.psz, StaticErrInfo.szMsg);
1507 break;
1508
1509 case 't':
1510 if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
1511 State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
1512 else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
1513 State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
1514 else
1515 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
1516 break;
1517
1518 case 'k': State.fKernel = true; break;
1519 case 'v': State.cVerbose++; break;
1520 case 'q': State.cVerbose = 0; break;
1521 case 'V': return HandleVersion(cArgs, papszArgs);
1522 case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
1523 default: return RTGetOptPrintError(ch, &ValueUnion);
1524 }
1525 }
1526 if (ch != VINF_GETOPT_NOT_OPTION)
1527 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
1528
1529 /*
1530 * Populate the certificate stores according to the signing type.
1531 */
1532#ifdef VBOX
1533 unsigned cSets = 0;
1534 struct STSTORESET aSets[6];
1535#endif
1536
1537 switch (State.enmSignType)
1538 {
1539 case VERIFYEXESTATE::kSignType_Windows:
1540#ifdef VBOX
1541 aSets[cSets].hStore = State.hRootStore;
1542 aSets[cSets].paTAs = g_aSUPTimestampTAs;
1543 aSets[cSets].cTAs = g_cSUPTimestampTAs;
1544 cSets++;
1545 aSets[cSets].hStore = State.hRootStore;
1546 aSets[cSets].paTAs = g_aSUPSpcRootTAs;
1547 aSets[cSets].cTAs = g_cSUPSpcRootTAs;
1548 cSets++;
1549 aSets[cSets].hStore = State.hRootStore;
1550 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
1551 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
1552 cSets++;
1553 aSets[cSets].hStore = State.hKernelRootStore;
1554 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
1555 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
1556 cSets++;
1557#endif
1558 break;
1559
1560 case VERIFYEXESTATE::kSignType_OSX:
1561 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented.");
1562 }
1563
1564#ifdef VBOX
1565 for (unsigned i = 0; i < cSets; i++)
1566 for (unsigned j = 0; j < aSets[i].cTAs; j++)
1567 {
1568 rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
1569 aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
1570 if (RT_FAILURE(rc))
1571 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
1572 i, j, StaticErrInfo.szMsg);
1573 }
1574#endif
1575
1576 /*
1577 * Do it.
1578 */
1579 RTEXITCODE rcExit;
1580 for (;;)
1581 {
1582 rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo);
1583 if (rcExit != RTEXITCODE_SUCCESS)
1584 break;
1585
1586 /*
1587 * Next file
1588 */
1589 ch = RTGetOpt(&GetState, &ValueUnion);
1590 if (ch == 0)
1591 break;
1592 if (ch != VINF_GETOPT_NOT_OPTION)
1593 {
1594 rcExit = RTGetOptPrintError(ch, &ValueUnion);
1595 break;
1596 }
1597 }
1598
1599 /*
1600 * Clean up.
1601 */
1602 uint32_t cRefs;
1603 cRefs = RTCrStoreRelease(State.hRootStore); Assert(cRefs == 0);
1604 cRefs = RTCrStoreRelease(State.hKernelRootStore); Assert(cRefs == 0);
1605 cRefs = RTCrStoreRelease(State.hAdditionalStore); Assert(cRefs == 0);
1606
1607 return rcExit;
1608}
1609
1610#endif /* !IPRT_IN_BUILD_TOOL */
1611
1612/*
1613 * common code for show-exe and show-cat:
1614 */
1615
1616/**
1617 * Display an object ID.
1618 *
1619 * @returns IPRT status code.
1620 * @param pThis The show exe instance data.
1621 * @param pObjId The object ID to display.
1622 * @param pszLabel The field label (prefixed by szPrefix).
1623 * @param pszPost What to print after the ID (typically newline).
1624 */
1625static void HandleShowExeWorkerDisplayObjId(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszLabel, const char *pszPost)
1626{
1627 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
1628 if (RT_SUCCESS(rc))
1629 {
1630 if (pThis->cVerbosity > 1)
1631 RTPrintf("%s%s%s (%s)%s", pThis->szPrefix, pszLabel, pThis->szTmp, pObjId->szObjId, pszPost);
1632 else
1633 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pThis->szTmp, pszPost);
1634 }
1635 else
1636 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pObjId->szObjId, pszPost);
1637}
1638
1639
1640/**
1641 * Display an object ID, without prefix and label
1642 *
1643 * @returns IPRT status code.
1644 * @param pThis The show exe instance data.
1645 * @param pObjId The object ID to display.
1646 * @param pszPost What to print after the ID (typically newline).
1647 */
1648static void HandleShowExeWorkerDisplayObjIdSimple(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszPost)
1649{
1650 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
1651 if (RT_SUCCESS(rc))
1652 {
1653 if (pThis->cVerbosity > 1)
1654 RTPrintf("%s (%s)%s", pThis->szTmp, pObjId->szObjId, pszPost);
1655 else
1656 RTPrintf("%s%s", pThis->szTmp, pszPost);
1657 }
1658 else
1659 RTPrintf("%s%s", pObjId->szObjId, pszPost);
1660}
1661
1662
1663/**
1664 * Display a signer info attribute.
1665 *
1666 * @returns IPRT status code.
1667 * @param pThis The show exe instance data.
1668 * @param offPrefix The current prefix offset.
1669 * @param pAttr The attribute to display.
1670 */
1671static int HandleShowExeWorkerPkcs7DisplayAttrib(PSHOWEXEPKCS7 pThis, size_t offPrefix, PCRTCRPKCS7ATTRIBUTE pAttr)
1672{
1673 HandleShowExeWorkerDisplayObjId(pThis, &pAttr->Type, "", ":\n");
1674
1675 int rc = VINF_SUCCESS;
1676 switch (pAttr->enmType)
1677 {
1678 case RTCRPKCS7ATTRIBUTETYPE_UNKNOWN:
1679 if (pAttr->uValues.pCores->cItems <= 1)
1680 RTPrintf("%s %u bytes\n", pThis->szPrefix,pAttr->uValues.pCores->SetCore.Asn1Core.cb);
1681 else
1682 RTPrintf("%s %u bytes divided by %u items\n", pThis->szPrefix, pAttr->uValues.pCores->SetCore.Asn1Core.cb, pAttr->uValues.pCores->cItems);
1683 break;
1684
1685 /* Object IDs, use pObjIds. */
1686 case RTCRPKCS7ATTRIBUTETYPE_OBJ_IDS:
1687 if (pAttr->uValues.pObjIds->cItems != 1)
1688 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIds->cItems);
1689 for (unsigned i = 0; i < pAttr->uValues.pObjIds->cItems; i++)
1690 {
1691 if (pAttr->uValues.pObjIds->cItems == 1)
1692 RTPrintf("%s ", pThis->szPrefix);
1693 else
1694 RTPrintf("%s ObjId[%u]: ", pThis->szPrefix, i);
1695 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIds->papItems[i], "\n");
1696 }
1697 break;
1698
1699 /* Sequence of object IDs, use pObjIdSeqs. */
1700 case RTCRPKCS7ATTRIBUTETYPE_MS_STATEMENT_TYPE:
1701 if (pAttr->uValues.pObjIdSeqs->cItems != 1)
1702 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIdSeqs->cItems);
1703 for (unsigned i = 0; i < pAttr->uValues.pObjIdSeqs->cItems; i++)
1704 {
1705 uint32_t const cObjIds = pAttr->uValues.pObjIdSeqs->papItems[i]->cItems;
1706 for (unsigned j = 0; j < cObjIds; j++)
1707 {
1708 if (pAttr->uValues.pObjIdSeqs->cItems == 1)
1709 RTPrintf("%s ", pThis->szPrefix);
1710 else
1711 RTPrintf("%s ObjIdSeq[%u]: ", pThis->szPrefix, i);
1712 if (cObjIds != 1)
1713 RTPrintf(" ObjId[%u]: ", j);
1714 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIdSeqs->papItems[i]->papItems[i], "\n");
1715 }
1716 }
1717 break;
1718
1719 /* Octet strings, use pOctetStrings. */
1720 case RTCRPKCS7ATTRIBUTETYPE_OCTET_STRINGS:
1721 if (pAttr->uValues.pOctetStrings->cItems != 1)
1722 RTPrintf("%s%u octet strings:", pThis->szPrefix, pAttr->uValues.pOctetStrings->cItems);
1723 for (unsigned i = 0; i < pAttr->uValues.pOctetStrings->cItems; i++)
1724 {
1725 PCRTASN1OCTETSTRING pOctetString = pAttr->uValues.pOctetStrings->papItems[i];
1726 uint32_t cbContent = pOctetString->Asn1Core.cb;
1727 if (cbContent > 0 && (cbContent <= 128 || pThis->cVerbosity >= 2))
1728 {
1729 uint8_t const *pbContent = pOctetString->Asn1Core.uData.pu8;
1730 uint32_t off = 0;
1731 while (off < cbContent)
1732 {
1733 uint32_t cbNow = RT_MIN(cbContent - off, 16);
1734 if (pAttr->uValues.pOctetStrings->cItems == 1)
1735 RTPrintf("%s %#06x: %.*Rhxs\n", pThis->szPrefix, off, cbNow, &pbContent[off]);
1736 else
1737 RTPrintf("%s OctetString[%u]: %#06x: %.*Rhxs\n", pThis->szPrefix, i, off, cbNow, &pbContent[off]);
1738 off += cbNow;
1739 }
1740 }
1741 else
1742 RTPrintf("%s: OctetString[%u]: %u bytes\n", pThis->szPrefix, i, pOctetString->Asn1Core.cb);
1743 }
1744 break;
1745
1746 /* Counter signatures (PKCS \#9), use pCounterSignatures. */
1747 case RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES:
1748 RTPrintf("%sTODO: RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES! %u bytes\n",
1749 pThis->szPrefix, pAttr->uValues.pCounterSignatures->SetCore.Asn1Core.cb);
1750 break;
1751
1752 /* Signing time (PKCS \#9), use pSigningTime. */
1753 case RTCRPKCS7ATTRIBUTETYPE_SIGNING_TIME:
1754 RTPrintf("%sTODO: RTCRPKCS7ATTRIBUTETYPE_SIGNING_TIME! %u bytes\n",
1755 pThis->szPrefix, pAttr->uValues.pSigningTime->SetCore.Asn1Core.cb);
1756 break;
1757
1758 /* Microsoft timestamp info (RFC-3161) signed data, use pContentInfo. */
1759 case RTCRPKCS7ATTRIBUTETYPE_MS_TIMESTAMP:
1760 case RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE:
1761 if (pAttr->uValues.pContentInfos->cItems > 1)
1762 RTPrintf("%s%u nested signatures, %u bytes in total\n", pThis->szPrefix,
1763 pAttr->uValues.pContentInfos->cItems, pAttr->uValues.pContentInfos->SetCore.Asn1Core.cb);
1764 for (unsigned i = 0; i < pAttr->uValues.pContentInfos->cItems; i++)
1765 {
1766 size_t offPrefix2 = offPrefix;
1767 if (pAttr->uValues.pContentInfos->cItems > 1)
1768 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig[%u]: ", i);
1769 else
1770 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " ");
1771 // offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig: ", i);
1772 PCRTCRPKCS7CONTENTINFO pContentInfo = pAttr->uValues.pContentInfos->papItems[i];
1773 int rc2;
1774 if (RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
1775 rc2 = HandleShowExeWorkerPkcs7Display(pThis, pContentInfo->u.pSignedData, offPrefix2, pContentInfo);
1776 else
1777 rc2 = RTMsgErrorRc(VERR_ASN1_UNEXPECTED_OBJ_ID, "%sPKCS#7 content in nested signature is not 'signedData': %s",
1778 pThis->szPrefix, pContentInfo->ContentType.szObjId);
1779 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1780 rc = rc2;
1781 }
1782 break;
1783
1784 case RTCRPKCS7ATTRIBUTETYPE_INVALID:
1785 RTPrintf("%sINVALID!\n", pThis->szPrefix);
1786 break;
1787 case RTCRPKCS7ATTRIBUTETYPE_NOT_PRESENT:
1788 RTPrintf("%sNOT PRESENT!\n", pThis->szPrefix);
1789 break;
1790 default:
1791 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pAttr->enmType);
1792 break;
1793 }
1794 return rc;
1795}
1796
1797
1798/**
1799 * Displays a Microsoft SPC indirect data structure.
1800 *
1801 * @returns IPRT status code.
1802 * @param pThis The show exe instance data.
1803 * @param offPrefix The current prefix offset.
1804 * @param pIndData The indirect data to display.
1805 */
1806static int HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(PSHOWEXEPKCS7 pThis, size_t offPrefix,
1807 PCRTCRSPCINDIRECTDATACONTENT pIndData)
1808{
1809 /*
1810 * The image hash.
1811 */
1812 RTDIGESTTYPE const enmDigestType = RTCrX509AlgorithmIdentifier_QueryDigestType(&pIndData->DigestInfo.DigestAlgorithm);
1813 const char *pszDigestType = RTCrDigestTypeToName(enmDigestType);
1814 RTPrintf("%s Digest Type: %s", pThis->szPrefix, pszDigestType);
1815 if (pThis->cVerbosity > 1)
1816 RTPrintf(" (%s)\n", pIndData->DigestInfo.DigestAlgorithm.Algorithm.szObjId);
1817 else
1818 RTPrintf("\n");
1819 RTPrintf("%s Digest: %.*Rhxs\n",
1820 pThis->szPrefix, pIndData->DigestInfo.Digest.Asn1Core.cb, pIndData->DigestInfo.Digest.Asn1Core.uData.pu8);
1821
1822 /*
1823 * The data/file/url.
1824 */
1825 switch (pIndData->Data.enmType)
1826 {
1827 case RTCRSPCAAOVTYPE_PE_IMAGE_DATA:
1828 {
1829 RTPrintf("%s Data Type: PE Image Data\n", pThis->szPrefix);
1830 PRTCRSPCPEIMAGEDATA pPeImage = pIndData->Data.uValue.pPeImage;
1831 /** @todo display "Flags". */
1832
1833 switch (pPeImage->T0.File.enmChoice)
1834 {
1835 case RTCRSPCLINKCHOICE_MONIKER:
1836 {
1837 PRTCRSPCSERIALIZEDOBJECT pMoniker = pPeImage->T0.File.u.pMoniker;
1838 if (RTCrSpcSerializedObject_IsPresent(pMoniker))
1839 {
1840 if (RTUuidCompareStr(pMoniker->Uuid.Asn1Core.uData.pUuid, RTCRSPCSERIALIZEDOBJECT_UUID_STR) == 0)
1841 {
1842 RTPrintf("%s Moniker: SpcSerializedObject (%RTuuid)\n",
1843 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
1844
1845 PCRTCRSPCSERIALIZEDOBJECTATTRIBUTES pData = pMoniker->u.pData;
1846 if (pData)
1847 for (uint32_t i = 0; i < pData->cItems; i++)
1848 {
1849 RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix,
1850 "MonikerAttrib[%u]: ", i);
1851
1852 switch (pData->papItems[i]->enmType)
1853 {
1854 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V2:
1855 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1:
1856 {
1857 PCRTCRSPCSERIALIZEDPAGEHASHES pPgHashes = pData->papItems[i]->u.pPageHashes;
1858 uint32_t const cbHash = pData->papItems[i]->enmType
1859 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1
1860 ? 160/8 /*SHA-1*/ : 256/8 /*SHA-256*/;
1861 uint32_t const cPages = pPgHashes->RawData.Asn1Core.cb / (cbHash + sizeof(uint32_t));
1862
1863 RTPrintf("%sPage Hashes version %u - %u pages (%u bytes total)\n", pThis->szPrefix,
1864 pData->papItems[i]->enmType
1865 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1 ? 1 : 2,
1866 cPages, pPgHashes->RawData.Asn1Core.cb);
1867 if (pThis->cVerbosity > 0)
1868 {
1869 PCRTCRSPCPEIMAGEPAGEHASHES pPg = pPgHashes->pData;
1870 for (unsigned iPg = 0; iPg < cPages; iPg++)
1871 {
1872 uint32_t offHash = 0;
1873 do
1874 {
1875 if (offHash == 0)
1876 RTPrintf("%.*s Page#%04u/%#08x: ",
1877 offPrefix, pThis->szPrefix, iPg, pPg->Generic.offFile);
1878 else
1879 RTPrintf("%.*s ", offPrefix, pThis->szPrefix);
1880 uint32_t cbLeft = cbHash - offHash;
1881 if (cbLeft > 24)
1882 cbLeft = 16;
1883 RTPrintf("%.*Rhxs\n", cbLeft, &pPg->Generic.abHash[offHash]);
1884 offHash += cbLeft;
1885 } while (offHash < cbHash);
1886 pPg = (PCRTCRSPCPEIMAGEPAGEHASHES)&pPg->Generic.abHash[cbHash];
1887 }
1888
1889 if (pThis->cVerbosity > 3)
1890 RTPrintf("%.*Rhxd\n",
1891 pPgHashes->RawData.Asn1Core.cb,
1892 pPgHashes->RawData.Asn1Core.uData.pu8);
1893 }
1894 break;
1895 }
1896
1897 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_UNKNOWN:
1898 HandleShowExeWorkerDisplayObjIdSimple(pThis, &pData->papItems[i]->Type, "\n");
1899 break;
1900 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_NOT_PRESENT:
1901 RTPrintf("%sNot present!\n", pThis->szPrefix);
1902 break;
1903 default:
1904 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pData->papItems[i]->enmType);
1905 break;
1906 }
1907 pThis->szPrefix[offPrefix] = '\0';
1908 }
1909 else
1910 RTPrintf("%s pData is NULL!\n", pThis->szPrefix);
1911 }
1912 else
1913 RTPrintf("%s Moniker: Unknown UUID: %RTuuid\n",
1914 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
1915 }
1916 else
1917 RTPrintf("%s Moniker: not present\n", pThis->szPrefix);
1918 break;
1919 }
1920
1921 case RTCRSPCLINKCHOICE_URL:
1922 {
1923 const char *pszUrl = NULL;
1924 int rc = pPeImage->T0.File.u.pUrl
1925 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pUrl, &pszUrl, NULL)
1926 : VERR_NOT_FOUND;
1927 if (RT_SUCCESS(rc))
1928 RTPrintf("%s URL: '%s'\n", pThis->szPrefix, pszUrl);
1929 else
1930 RTPrintf("%s URL: rc=%Rrc\n", pThis->szPrefix, rc);
1931 break;
1932 }
1933
1934 case RTCRSPCLINKCHOICE_FILE:
1935 {
1936 const char *pszFile = NULL;
1937 int rc = pPeImage->T0.File.u.pT2 && pPeImage->T0.File.u.pT2->File.u.pAscii
1938 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pT2->File.u.pAscii, &pszFile, NULL)
1939 : VERR_NOT_FOUND;
1940 if (RT_SUCCESS(rc))
1941 RTPrintf("%s File: '%s'\n", pThis->szPrefix, pszFile);
1942 else
1943 RTPrintf("%s File: rc=%Rrc\n", pThis->szPrefix, rc);
1944 break;
1945 }
1946
1947 case RTCRSPCLINKCHOICE_NOT_PRESENT:
1948 RTPrintf("%s File not present!\n", pThis->szPrefix);
1949 break;
1950 default:
1951 RTPrintf("%s enmChoice=%d!\n", pThis->szPrefix, pPeImage->T0.File.enmChoice);
1952 break;
1953 }
1954 break;
1955 }
1956
1957 case RTCRSPCAAOVTYPE_UNKNOWN:
1958 HandleShowExeWorkerDisplayObjId(pThis, &pIndData->Data.Type, " Data Type: ", "\n");
1959 break;
1960 case RTCRSPCAAOVTYPE_NOT_PRESENT:
1961 RTPrintf("%s Data Type: Not present!\n", pThis->szPrefix);
1962 break;
1963 default:
1964 RTPrintf("%s Data Type: enmType=%d!\n", pThis->szPrefix, pIndData->Data.enmType);
1965 break;
1966 }
1967
1968 return VINF_SUCCESS;
1969}
1970
1971
1972/**
1973 * Display an PKCS#7 signed data instance.
1974 *
1975 * @returns IPRT status code.
1976 * @param pThis The show exe instance data.
1977 * @param pSignedData The signed data to display.
1978 * @param offPrefix The current prefix offset.
1979 * @param pContentInfo The content info structure (for the size).
1980 */
1981static int HandleShowExeWorkerPkcs7Display(PSHOWEXEPKCS7 pThis, PRTCRPKCS7SIGNEDDATA pSignedData, size_t offPrefix,
1982 PCRTCRPKCS7CONTENTINFO pContentInfo)
1983{
1984 pThis->szPrefix[offPrefix] = '\0';
1985 RTPrintf("%sPKCS#7 signature: %u (%#x) bytes\n", pThis->szPrefix,
1986 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core),
1987 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core));
1988
1989 /*
1990 * Display list of signing algorithms.
1991 */
1992 RTPrintf("%sDigestAlgorithms: ", pThis->szPrefix);
1993 if (pSignedData->DigestAlgorithms.cItems == 0)
1994 RTPrintf("none");
1995 for (unsigned i = 0; i < pSignedData->DigestAlgorithms.cItems; i++)
1996 {
1997 PCRTCRX509ALGORITHMIDENTIFIER pAlgoId = pSignedData->DigestAlgorithms.papItems[i];
1998 const char *pszDigestType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_QueryDigestType(pAlgoId));
1999 if (!pszDigestType)
2000 pszDigestType = pAlgoId->Algorithm.szObjId;
2001 RTPrintf(i == 0 ? "%s" : ", %s", pszDigestType);
2002 if (pThis->cVerbosity > 1)
2003 RTPrintf(" (%s)", pAlgoId->Algorithm.szObjId);
2004 }
2005 RTPrintf("\n");
2006
2007 /*
2008 * Display the signed data content.
2009 */
2010 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCRSPCINDIRECTDATACONTENT_OID) == 0)
2011 {
2012 RTPrintf("%s ContentType: SpcIndirectDataContent (" RTCRSPCINDIRECTDATACONTENT_OID ")\n", pThis->szPrefix);
2013 size_t offPrefix2 = RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " SPC Ind Data: ");
2014 HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(pThis, offPrefix2 + offPrefix,
2015 pSignedData->ContentInfo.u.pIndirectDataContent);
2016 pThis->szPrefix[offPrefix] = '\0';
2017 }
2018 else
2019 HandleShowExeWorkerDisplayObjId(pThis, &pSignedData->ContentInfo.ContentType, " ContentType: ", " - not implemented.\n");
2020
2021 /*
2022 * Display certificates (Certificates).
2023 */
2024 if (pSignedData->Certificates.cItems > 0)
2025 {
2026 RTPrintf("%s Certificates: %u\n", pThis->szPrefix, pSignedData->Certificates.cItems);
2027 if (pThis->cVerbosity >= 2)
2028 {
2029 for (uint32_t i = 0; i < pSignedData->Certificates.cItems; i++)
2030 {
2031 if (i != 0)
2032 RTPrintf("\n");
2033 RTPrintf("%s Certificate #%u:\n", pThis->szPrefix, i);
2034 RTAsn1Dump(RTCrPkcs7Cert_GetAsn1Core(pSignedData->Certificates.papItems[i]), 0,
2035 ((uint32_t)offPrefix + 9) / 2, RTStrmDumpPrintfV, g_pStdOut);
2036 }
2037 }
2038 /** @todo display certificates properly. */
2039 }
2040
2041 if (pSignedData->Crls.cb > 0)
2042 RTPrintf("%s CRLs: %u bytes\n", pThis->szPrefix, pSignedData->Crls.cb);
2043
2044 /*
2045 * Show signatures (SignerInfos).
2046 */
2047 unsigned const cSigInfos = pSignedData->SignerInfos.cItems;
2048 if (cSigInfos != 1)
2049 RTPrintf("%s SignerInfos: %u signers\n", pThis->szPrefix, cSigInfos);
2050 else
2051 RTPrintf("%s SignerInfos:\n", pThis->szPrefix);
2052 for (unsigned i = 0; i < cSigInfos; i++)
2053 {
2054 PRTCRPKCS7SIGNERINFO pSigInfo = pSignedData->SignerInfos.papItems[i];
2055 size_t offPrefix2 = offPrefix;
2056 if (cSigInfos != 1)
2057 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "SignerInfo[%u]: ", i);
2058
2059 int rc = RTAsn1Integer_ToString(&pSigInfo->IssuerAndSerialNumber.SerialNumber,
2060 pThis->szTmp, sizeof(pThis->szTmp), 0 /*fFlags*/, NULL);
2061 if (RT_FAILURE(rc))
2062 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
2063 RTPrintf("%s Serial No: %s\n", pThis->szPrefix, pThis->szTmp);
2064
2065 rc = RTCrX509Name_FormatAsString(&pSigInfo->IssuerAndSerialNumber.Name, pThis->szTmp, sizeof(pThis->szTmp), NULL);
2066 if (RT_FAILURE(rc))
2067 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
2068 RTPrintf("%s Issuer: %s\n", pThis->szPrefix, pThis->szTmp);
2069
2070 const char *pszType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_QueryDigestType(&pSigInfo->DigestAlgorithm));
2071 if (!pszType)
2072 pszType = pSigInfo->DigestAlgorithm.Algorithm.szObjId;
2073 RTPrintf("%s Digest Algorithm: %s", pThis->szPrefix, pszType);
2074 if (pThis->cVerbosity > 1)
2075 RTPrintf(" (%s)\n", pSigInfo->DigestAlgorithm.Algorithm.szObjId);
2076 else
2077 RTPrintf("\n");
2078
2079 HandleShowExeWorkerDisplayObjId(pThis, &pSigInfo->DigestEncryptionAlgorithm.Algorithm,
2080 "Digest Encryption Algorithm: ", "\n");
2081
2082 if (pSigInfo->AuthenticatedAttributes.cItems == 0)
2083 RTPrintf("%s Authenticated Attributes: none\n", pThis->szPrefix);
2084 else
2085 {
2086 RTPrintf("%s Authenticated Attributes: %u item%s\n", pThis->szPrefix,
2087 pSigInfo->AuthenticatedAttributes.cItems, pSigInfo->AuthenticatedAttributes.cItems > 1 ? "s" : "");
2088 for (unsigned j = 0; j < pSigInfo->AuthenticatedAttributes.cItems; j++)
2089 {
2090 PRTCRPKCS7ATTRIBUTE pAttr = pSigInfo->AuthenticatedAttributes.papItems[j];
2091 size_t offPrefix3 = offPrefix2 + RTStrPrintf(&pThis->szPrefix[offPrefix2], sizeof(pThis->szPrefix) - offPrefix2,
2092 " AuthAttrib[%u]: ", j);
2093 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
2094 }
2095 pThis->szPrefix[offPrefix2] = '\0';
2096 }
2097
2098 if (pSigInfo->UnauthenticatedAttributes.cItems == 0)
2099 RTPrintf("%s Unauthenticated Attributes: none\n", pThis->szPrefix);
2100 else
2101 {
2102 RTPrintf("%s Unauthenticated Attributes: %u item%s\n", pThis->szPrefix,
2103 pSigInfo->UnauthenticatedAttributes.cItems, pSigInfo->UnauthenticatedAttributes.cItems > 1 ? "s" : "");
2104 for (unsigned j = 0; j < pSigInfo->UnauthenticatedAttributes.cItems; j++)
2105 {
2106 PRTCRPKCS7ATTRIBUTE pAttr = pSigInfo->UnauthenticatedAttributes.papItems[j];
2107 size_t offPrefix3 = offPrefix2 + RTStrPrintf(&pThis->szPrefix[offPrefix2], sizeof(pThis->szPrefix) - offPrefix2,
2108 " UnauthAttrib[%u]: ", j);
2109 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
2110 }
2111 pThis->szPrefix[offPrefix2] = '\0';
2112 }
2113
2114 /** @todo show the encrypted stuff (EncryptedDigest)? */
2115 }
2116 pThis->szPrefix[offPrefix] = '\0';
2117
2118 return VINF_SUCCESS;
2119}
2120
2121
2122/*
2123 * The 'show-exe' command.
2124 */
2125static RTEXITCODE HelpShowExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2126{
2127 RT_NOREF_PV(enmLevel);
2128 RTStrmPrintf(pStrm,
2129 "show-exe [--verbose|-v] [--quiet|-q] <exe1> [exe2 [..]]\n");
2130 return RTEXITCODE_SUCCESS;
2131}
2132
2133
2134static RTEXITCODE HandleShowExe(int cArgs, char **papszArgs)
2135{
2136 /*
2137 * Parse arguments.
2138 */
2139 static const RTGETOPTDEF s_aOptions[] =
2140 {
2141 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2142 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2143 };
2144
2145 unsigned cVerbosity = 0;
2146 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
2147
2148 RTGETOPTSTATE GetState;
2149 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2150 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2151 RTGETOPTUNION ValueUnion;
2152 int ch;
2153 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
2154 {
2155 switch (ch)
2156 {
2157 case 'v': cVerbosity++; break;
2158 case 'q': cVerbosity = 0; break;
2159 case 'V': return HandleVersion(cArgs, papszArgs);
2160 case 'h': return HelpShowExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
2161 default: return RTGetOptPrintError(ch, &ValueUnion);
2162 }
2163 }
2164 if (ch != VINF_GETOPT_NOT_OPTION)
2165 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
2166
2167 /*
2168 * Do it.
2169 */
2170 unsigned iFile = 0;
2171 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2172 do
2173 {
2174 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
2175
2176 SHOWEXEPKCS7 This;
2177 RT_ZERO(This);
2178 This.cVerbosity = cVerbosity;
2179
2180 RTEXITCODE rcExitThis = SignToolPkcs7Exe_InitFromFile(&This, ValueUnion.psz, cVerbosity, enmLdrArch);
2181 if (rcExitThis == RTEXITCODE_SUCCESS)
2182 {
2183 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
2184 if (RT_FAILURE(rc))
2185 rcExit = RTEXITCODE_FAILURE;
2186 SignToolPkcs7Exe_Delete(&This);
2187 }
2188 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
2189 rcExit = rcExitThis;
2190
2191 iFile++;
2192 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
2193 if (ch != 0)
2194 return RTGetOptPrintError(ch, &ValueUnion);
2195
2196 return rcExit;
2197}
2198
2199
2200/*
2201 * The 'show-cat' command.
2202 */
2203static RTEXITCODE HelpShowCat(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2204{
2205 RT_NOREF_PV(enmLevel);
2206 RTStrmPrintf(pStrm,
2207 "show-cat [--verbose|-v] [--quiet|-q] <cat1> [cat2 [..]]\n");
2208 return RTEXITCODE_SUCCESS;
2209}
2210
2211
2212static RTEXITCODE HandleShowCat(int cArgs, char **papszArgs)
2213{
2214 /*
2215 * Parse arguments.
2216 */
2217 static const RTGETOPTDEF s_aOptions[] =
2218 {
2219 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2220 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2221 };
2222
2223 unsigned cVerbosity = 0;
2224
2225 RTGETOPTSTATE GetState;
2226 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2227 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2228 RTGETOPTUNION ValueUnion;
2229 int ch;
2230 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
2231 {
2232 switch (ch)
2233 {
2234 case 'v': cVerbosity++; break;
2235 case 'q': cVerbosity = 0; break;
2236 case 'V': return HandleVersion(cArgs, papszArgs);
2237 case 'h': return HelpShowCat(g_pStdOut, RTSIGNTOOLHELP_FULL);
2238 default: return RTGetOptPrintError(ch, &ValueUnion);
2239 }
2240 }
2241 if (ch != VINF_GETOPT_NOT_OPTION)
2242 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
2243
2244 /*
2245 * Do it.
2246 */
2247 unsigned iFile = 0;
2248 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2249 do
2250 {
2251 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
2252
2253 SHOWEXEPKCS7 This;
2254 RT_ZERO(This);
2255 This.cVerbosity = cVerbosity;
2256
2257 RTEXITCODE rcExitThis = SignToolPkcs7_InitFromFile(&This, ValueUnion.psz, cVerbosity);
2258 if (rcExitThis == RTEXITCODE_SUCCESS)
2259 {
2260 This.hLdrMod = NIL_RTLDRMOD;
2261
2262 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
2263 if (RT_FAILURE(rc))
2264 rcExit = RTEXITCODE_FAILURE;
2265 SignToolPkcs7Exe_Delete(&This);
2266 }
2267 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
2268 rcExit = rcExitThis;
2269
2270 iFile++;
2271 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
2272 if (ch != 0)
2273 return RTGetOptPrintError(ch, &ValueUnion);
2274
2275 return rcExit;
2276}
2277
2278
2279/*
2280 * The 'make-tainfo' command.
2281 */
2282static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2283{
2284 RT_NOREF_PV(enmLevel);
2285 RTStrmPrintf(pStrm,
2286 "make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
2287 return RTEXITCODE_SUCCESS;
2288}
2289
2290
2291typedef struct MAKETAINFOSTATE
2292{
2293 int cVerbose;
2294 const char *pszCert;
2295 const char *pszOutput;
2296} MAKETAINFOSTATE;
2297
2298
2299/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
2300static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
2301{
2302 RT_NOREF_PV(pErrInfo);
2303 return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
2304}
2305
2306
2307static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
2308{
2309 /*
2310 * Parse arguments.
2311 */
2312 static const RTGETOPTDEF s_aOptions[] =
2313 {
2314 { "--cert", 'c', RTGETOPT_REQ_STRING },
2315 { "--output", 'o', RTGETOPT_REQ_STRING },
2316 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
2317 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
2318 };
2319
2320 MAKETAINFOSTATE State = { 0, NULL, NULL };
2321
2322 RTGETOPTSTATE GetState;
2323 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2324 AssertRCReturn(rc, RTEXITCODE_FAILURE);
2325 RTGETOPTUNION ValueUnion;
2326 int ch;
2327 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2328 {
2329 switch (ch)
2330 {
2331 case 'c':
2332 if (State.pszCert)
2333 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
2334 State.pszCert = ValueUnion.psz;
2335 break;
2336
2337 case 'o':
2338 case VINF_GETOPT_NOT_OPTION:
2339 if (State.pszOutput)
2340 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
2341 State.pszOutput = ValueUnion.psz;
2342 break;
2343
2344 case 'v': State.cVerbose++; break;
2345 case 'q': State.cVerbose = 0; break;
2346 case 'V': return HandleVersion(cArgs, papszArgs);
2347 case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
2348 default: return RTGetOptPrintError(ch, &ValueUnion);
2349 }
2350 }
2351 if (!State.pszCert)
2352 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
2353 if (!State.pszOutput)
2354 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
2355
2356 /*
2357 * Read the certificate.
2358 */
2359 RTERRINFOSTATIC StaticErrInfo;
2360 RTCRX509CERTIFICATE Certificate;
2361 rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
2362 RTErrInfoInitStatic(&StaticErrInfo));
2363 if (RT_FAILURE(rc))
2364 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
2365 State.pszCert, rc, StaticErrInfo.szMsg);
2366 /*
2367 * Construct the trust anchor information.
2368 */
2369 RTCRTAFTRUSTANCHORINFO TrustAnchor;
2370 rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
2371 if (RT_SUCCESS(rc))
2372 {
2373 /* Public key. */
2374 Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
2375 RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
2376 rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
2377 &g_RTAsn1DefaultAllocator);
2378 if (RT_FAILURE(rc))
2379 RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
2380 RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
2381
2382 /* Key Identifier. */
2383 PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
2384 if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
2385 pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
2386 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
2387 && RTCrX509Certificate_IsSelfSigned(&Certificate)
2388 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
2389 pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
2390 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
2391 && RTCrX509Certificate_IsSelfSigned(&Certificate)
2392 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
2393 pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
2394 if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
2395 {
2396 Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
2397 RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
2398 rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
2399 if (RT_FAILURE(rc))
2400 RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
2401 RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
2402 }
2403 else
2404 RTMsgWarning("No key identifier found or has zero length.");
2405
2406 /* Subject */
2407 if (RT_SUCCESS(rc))
2408 {
2409 Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
2410 rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
2411 if (RT_SUCCESS(rc))
2412 {
2413 Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
2414 RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
2415 rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
2416 &g_RTAsn1DefaultAllocator);
2417 if (RT_SUCCESS(rc))
2418 {
2419 RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
2420 rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
2421 if (RT_FAILURE(rc))
2422 RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
2423 }
2424 else
2425 RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
2426 }
2427 else
2428 RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
2429 }
2430
2431 /* Check that what we've constructed makes some sense. */
2432 if (RT_SUCCESS(rc))
2433 {
2434 rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
2435 if (RT_FAILURE(rc))
2436 RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2437 }
2438
2439 if (RT_SUCCESS(rc))
2440 {
2441 /*
2442 * Encode it and write it to the output file.
2443 */
2444 uint32_t cbEncoded;
2445 rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
2446 RTErrInfoInitStatic(&StaticErrInfo));
2447 if (RT_SUCCESS(rc))
2448 {
2449 if (State.cVerbose >= 1)
2450 RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
2451
2452 PRTSTREAM pStrm;
2453 rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
2454 if (RT_SUCCESS(rc))
2455 {
2456 rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
2457 handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
2458 if (RT_SUCCESS(rc))
2459 {
2460 rc = RTStrmClose(pStrm);
2461 if (RT_SUCCESS(rc))
2462 RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
2463 else
2464 RTMsgError("RTStrmClose failed: %Rrc", rc);
2465 }
2466 else
2467 {
2468 RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2469 RTStrmClose(pStrm);
2470 }
2471 }
2472 else
2473 RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
2474 }
2475 else
2476 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
2477 }
2478
2479 RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
2480 }
2481 else
2482 RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
2483
2484 RTCrX509Certificate_Delete(&Certificate);
2485 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2486}
2487
2488
2489
2490/*
2491 * The 'version' command.
2492 */
2493static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2494{
2495 RT_NOREF_PV(enmLevel);
2496 RTStrmPrintf(pStrm, "version\n");
2497 return RTEXITCODE_SUCCESS;
2498}
2499
2500static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
2501{
2502 RT_NOREF_PV(cArgs); RT_NOREF_PV(papszArgs);
2503#ifndef IN_BLD_PROG /* RTBldCfgVersion or RTBldCfgRevision in build time IPRT lib. */
2504 RTPrintf("%s\n", RTBldCfgVersion());
2505 return RTEXITCODE_SUCCESS;
2506#else
2507 return RTEXITCODE_FAILURE;
2508#endif
2509}
2510
2511
2512
2513/**
2514 * Command mapping.
2515 */
2516static struct
2517{
2518 /** The command. */
2519 const char *pszCmd;
2520 /**
2521 * Handle the command.
2522 * @returns Program exit code.
2523 * @param cArgs Number of arguments.
2524 * @param papszArgs The argument vector, starting with the command name.
2525 */
2526 RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
2527 /**
2528 * Produce help.
2529 * @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
2530 * @param pStrm Where to send help text.
2531 * @param enmLevel The level of the help information.
2532 */
2533 RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
2534}
2535/** Mapping commands to handler and helper functions. */
2536const g_aCommands[] =
2537{
2538 { "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
2539 { "add-nested-exe-signature", HandleAddNestedExeSignature, HelpAddNestedExeSignature },
2540 { "add-nested-cat-signature", HandleAddNestedCatSignature, HelpAddNestedCatSignature },
2541#ifndef IPRT_IN_BUILD_TOOL
2542 { "verify-exe", HandleVerifyExe, HelpVerifyExe },
2543#endif
2544 { "show-exe", HandleShowExe, HelpShowExe },
2545 { "show-cat", HandleShowCat, HelpShowCat },
2546 { "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
2547 { "help", HandleHelp, HelpHelp },
2548 { "--help", HandleHelp, NULL },
2549 { "-h", HandleHelp, NULL },
2550 { "version", HandleVersion, HelpVersion },
2551 { "--version", HandleVersion, NULL },
2552 { "-V", HandleVersion, NULL },
2553};
2554
2555
2556/*
2557 * The 'help' command.
2558 */
2559static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
2560{
2561 RT_NOREF_PV(enmLevel);
2562 RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
2563 return RTEXITCODE_SUCCESS;
2564}
2565
2566static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
2567{
2568 RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
2569 uint32_t cShowed = 0;
2570 for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
2571 {
2572 if (g_aCommands[iCmd].pfnHelp)
2573 {
2574 bool fShow = false;
2575 if (cArgs <= 1)
2576 fShow = true;
2577 else
2578 {
2579 for (int iArg = 1; iArg < cArgs; iArg++)
2580 if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
2581 {
2582 fShow = true;
2583 break;
2584 }
2585 }
2586 if (fShow)
2587 {
2588 g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel);
2589 cShowed++;
2590 }
2591 }
2592 }
2593 return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2594}
2595
2596
2597
2598int main(int argc, char **argv)
2599{
2600 int rc = RTR3InitExe(argc, &argv, 0);
2601 if (RT_FAILURE(rc))
2602 return RTMsgInitFailure(rc);
2603
2604 /*
2605 * Parse global arguments.
2606 */
2607 int iArg = 1;
2608 /* none presently. */
2609
2610 /*
2611 * Command dispatcher.
2612 */
2613 if (iArg < argc)
2614 {
2615 const char *pszCmd = argv[iArg];
2616 uint32_t i = RT_ELEMENTS(g_aCommands);
2617 while (i-- > 0)
2618 if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
2619 return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
2620 RTMsgError("Unknown command '%s'.", pszCmd);
2621 }
2622 else
2623 RTMsgError("No command given. (try --help)");
2624
2625 return RTEXITCODE_SYNTAX;
2626}
2627
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