VirtualBox

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

Last change on this file since 107120 was 106602, checked in by vboxsync, 3 months ago

IPRT/ldrPE,RTSignTool: Recognize ARM64 images. jiraref:VBP-1171

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 306.9 KB
Line 
1/* $Id: RTSignTool.cpp 106602 2024-10-23 01:01:00Z vboxsync $ */
2/** @file
3 * IPRT - Signing Tool.
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#include <iprt/assert.h>
42#include <iprt/buildconfig.h>
43#include <iprt/ctype.h>
44#include <iprt/err.h>
45#include <iprt/getopt.h>
46#include <iprt/file.h>
47#include <iprt/initterm.h>
48#include <iprt/ldr.h>
49#include <iprt/message.h>
50#include <iprt/mem.h>
51#include <iprt/path.h>
52#include <iprt/stream.h>
53#include <iprt/string.h>
54#ifdef RT_OS_WINDOWS
55# include <iprt/utf16.h>
56#endif
57#include <iprt/uuid.h>
58#include <iprt/zero.h>
59#include <iprt/formats/asn1.h>
60#include <iprt/formats/mach-o.h>
61#ifndef RT_OS_WINDOWS
62# include <iprt/formats/pecoff.h>
63#else
64# define WIN_CERTIFICATE_ALIGNMENT UINT32_C(8) /* from pecoff.h */
65#endif
66#include <iprt/crypto/applecodesign.h>
67#include <iprt/crypto/digest.h>
68#include <iprt/crypto/key.h>
69#include <iprt/crypto/x509.h>
70#include <iprt/crypto/pkcs7.h>
71#include <iprt/crypto/store.h>
72#include <iprt/crypto/spc.h>
73#include <iprt/crypto/tsp.h>
74#include <iprt/cpp/ministring.h>
75#ifdef VBOX
76# include <VBox/sup.h> /* Certificates */
77#endif
78#ifdef RT_OS_WINDOWS
79# include <iprt/win/windows.h>
80# include <iprt/win/imagehlp.h>
81# include <wincrypt.h>
82# include <ncrypt.h>
83#endif
84#include "internal/ldr.h" /* for IMAGE_XX_SIGNATURE defines */
85
86
87/*********************************************************************************************************************************
88* Defined Constants And Macros *
89*********************************************************************************************************************************/
90#define OPT_OFF_CERT_FILE 0 /**< signtool /f file */
91#define OPT_OFF_CERT_SHA1 1 /**< signtool /sha1 thumbprint */
92#define OPT_OFF_CERT_SUBJECT 2 /**< signtool /n name */
93#define OPT_OFF_CERT_STORE 3 /**< signtool /s store */
94#define OPT_OFF_CERT_STORE_MACHINE 4 /**< signtool /sm */
95#define OPT_OFF_KEY_FILE 5 /**< no signtool equivalent, other than maybe /f. */
96#define OPT_OFF_KEY_PASSWORD 6 /**< signtool /p pass */
97#define OPT_OFF_KEY_PASSWORD_FILE 7 /**< no signtool equivalent. */
98#define OPT_OFF_KEY_NAME 8 /**< signtool /kc name */
99#define OPT_OFF_KEY_PROVIDER 9 /**< signtool /csp name (CSP = cryptographic service provider) */
100
101#define OPT_CERT_KEY_SWITCH_CASES(a_Instance, a_uBase, a_chOpt, a_ValueUnion, a_rcExit) \
102 case (a_uBase) + OPT_OFF_CERT_FILE: \
103 case (a_uBase) + OPT_OFF_CERT_SHA1: \
104 case (a_uBase) + OPT_OFF_CERT_SUBJECT: \
105 case (a_uBase) + OPT_OFF_CERT_STORE: \
106 case (a_uBase) + OPT_OFF_CERT_STORE_MACHINE: \
107 case (a_uBase) + OPT_OFF_KEY_FILE: \
108 case (a_uBase) + OPT_OFF_KEY_PASSWORD: \
109 case (a_uBase) + OPT_OFF_KEY_PASSWORD_FILE: \
110 case (a_uBase) + OPT_OFF_KEY_NAME: \
111 case (a_uBase) + OPT_OFF_KEY_PROVIDER: \
112 a_rcExit = a_Instance.handleOption((a_chOpt) - (a_uBase), &(a_ValueUnion)); \
113 break
114
115#define OPT_CERT_KEY_GETOPTDEF_ENTRIES(a_szPrefix, a_szSuffix, a_uBase) \
116 { a_szPrefix "cert-file" a_szSuffix, (a_uBase) + OPT_OFF_CERT_FILE, RTGETOPT_REQ_STRING }, \
117 { a_szPrefix "cert-sha1" a_szSuffix, (a_uBase) + OPT_OFF_CERT_SHA1, RTGETOPT_REQ_STRING }, \
118 { a_szPrefix "cert-subject" a_szSuffix, (a_uBase) + OPT_OFF_CERT_SUBJECT, RTGETOPT_REQ_STRING }, \
119 { a_szPrefix "cert-store" a_szSuffix, (a_uBase) + OPT_OFF_CERT_STORE, RTGETOPT_REQ_STRING }, \
120 { a_szPrefix "cert-machine-store" a_szSuffix, (a_uBase) + OPT_OFF_CERT_STORE_MACHINE, RTGETOPT_REQ_NOTHING }, \
121 { a_szPrefix "key-file" a_szSuffix, (a_uBase) + OPT_OFF_KEY_FILE, RTGETOPT_REQ_STRING }, \
122 { a_szPrefix "key-password" a_szSuffix, (a_uBase) + OPT_OFF_KEY_PASSWORD, RTGETOPT_REQ_STRING }, \
123 { a_szPrefix "key-password-file" a_szSuffix, (a_uBase) + OPT_OFF_KEY_PASSWORD_FILE, RTGETOPT_REQ_STRING }, \
124 { a_szPrefix "key-name" a_szSuffix, (a_uBase) + OPT_OFF_KEY_NAME, RTGETOPT_REQ_STRING }, \
125 { a_szPrefix "key-provider" a_szSuffix, (a_uBase) + OPT_OFF_KEY_PROVIDER, RTGETOPT_REQ_STRING }
126
127#define OPT_CERT_KEY_GETOPTDEF_COMPAT_ENTRIES(a_uBase) \
128 { "/f", (a_uBase) + OPT_OFF_CERT_FILE, RTGETOPT_REQ_STRING }, \
129 { "/sha1", (a_uBase) + OPT_OFF_CERT_SHA1, RTGETOPT_REQ_STRING }, \
130 { "/n", (a_uBase) + OPT_OFF_CERT_SUBJECT, RTGETOPT_REQ_STRING }, \
131 { "/s", (a_uBase) + OPT_OFF_CERT_STORE, RTGETOPT_REQ_STRING }, \
132 { "/sm", (a_uBase) + OPT_OFF_CERT_STORE_MACHINE, RTGETOPT_REQ_NOTHING }, \
133 { "/p", (a_uBase) + OPT_OFF_KEY_PASSWORD, RTGETOPT_REQ_STRING }, \
134 { "/kc", (a_uBase) + OPT_OFF_KEY_NAME, RTGETOPT_REQ_STRING }, \
135 { "/csp", (a_uBase) + OPT_OFF_KEY_PROVIDER, RTGETOPT_REQ_STRING }
136
137#define OPT_CERT_KEY_SYNOPSIS(a_szPrefix, a_szSuffix) \
138 "[" a_szPrefix "cert-file" a_szSuffix " <file.pem|file.crt>] " \
139 "[" a_szPrefix "cert-sha1" a_szSuffix " <fingerprint>] " \
140 "[" a_szPrefix "cert-subject" a_szSuffix " <part-name>] " \
141 "[" a_szPrefix "cert-store" a_szSuffix " <store>] " \
142 "[" a_szPrefix "cert-machine-store" a_szSuffix "] " \
143 "[" a_szPrefix "key-file" a_szSuffix " <file.pem|file.p12>] " \
144 "[" a_szPrefix "key-password" a_szSuffix " <password>] " \
145 "[" a_szPrefix "key-password-file" a_szSuffix " <file>|stdin] " \
146 "[" a_szPrefix "key-name" a_szSuffix " <name>] " \
147 "[" a_szPrefix "key-provider" a_szSuffix " <csp>] "
148
149#define OPT_HASH_PAGES 1200
150#define OPT_NO_HASH_PAGES 1201
151#define OPT_ADD_CERT 1202
152#define OPT_TIMESTAMP_TYPE 1203
153#define OPT_TIMESTAMP_TYPE_2 1204
154#define OPT_TIMESTAMP_OVERRIDE 1205
155#define OPT_NO_SIGNING_TIME 1206
156#define OPT_FILE_TYPE 1207
157#define OPT_IGNORED 1208
158
159
160/*********************************************************************************************************************************
161* Structures and Typedefs *
162*********************************************************************************************************************************/
163/** Help detail levels. */
164typedef enum RTSIGNTOOLHELP
165{
166 RTSIGNTOOLHELP_USAGE,
167 RTSIGNTOOLHELP_FULL
168} RTSIGNTOOLHELP;
169
170
171/** Filetypes. */
172typedef enum RTSIGNTOOLFILETYPE
173{
174 RTSIGNTOOLFILETYPE_INVALID = 0,
175 RTSIGNTOOLFILETYPE_DETECT,
176 RTSIGNTOOLFILETYPE_EXE,
177 RTSIGNTOOLFILETYPE_CAT,
178 RTSIGNTOOLFILETYPE_UNKNOWN,
179 RTSIGNTOOLFILETYPE_END
180} RTSIGNTOOLFILETYPE;
181
182
183/**
184 * PKCS\#7 signature data.
185 */
186typedef struct SIGNTOOLPKCS7
187{
188 /** The file type. */
189 RTSIGNTOOLFILETYPE enmType;
190 /** The raw signature. */
191 uint8_t *pbBuf;
192 /** Size of the raw signature. */
193 size_t cbBuf;
194 /** The filename. */
195 const char *pszFilename;
196 /** The outer content info wrapper. */
197 RTCRPKCS7CONTENTINFO ContentInfo;
198 /** Pointer to the decoded SignedData inside the ContentInfo member. */
199 PRTCRPKCS7SIGNEDDATA pSignedData;
200
201 /** Newly encoded raw signature.
202 * @sa SignToolPkcs7_Encode() */
203 uint8_t *pbNewBuf;
204 /** Size of newly encoded raw signature. */
205 size_t cbNewBuf;
206
207} SIGNTOOLPKCS7;
208typedef SIGNTOOLPKCS7 *PSIGNTOOLPKCS7;
209
210
211/**
212 * PKCS\#7 signature data for executable.
213 */
214typedef struct SIGNTOOLPKCS7EXE : public SIGNTOOLPKCS7
215{
216 /** The module handle. */
217 RTLDRMOD hLdrMod;
218} SIGNTOOLPKCS7EXE;
219typedef SIGNTOOLPKCS7EXE *PSIGNTOOLPKCS7EXE;
220
221
222/**
223 * Data for the show exe (signature) command.
224 */
225typedef struct SHOWEXEPKCS7 : public SIGNTOOLPKCS7EXE
226{
227 /** The verbosity. */
228 unsigned cVerbosity;
229 /** The prefix buffer. */
230 char szPrefix[256];
231 /** Temporary buffer. */
232 char szTmp[4096];
233} SHOWEXEPKCS7;
234typedef SHOWEXEPKCS7 *PSHOWEXEPKCS7;
235
236
237/*********************************************************************************************************************************
238* Internal Functions *
239*********************************************************************************************************************************/
240static RTEXITCODE HandleHelp(int cArgs, char **papszArgs);
241static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
242static RTEXITCODE HandleVersion(int cArgs, char **papszArgs);
243static int HandleShowExeWorkerPkcs7DisplaySignerInfo(PSHOWEXEPKCS7 pThis, size_t offPrefix, PCRTCRPKCS7SIGNERINFO pSignerInfo);
244static int HandleShowExeWorkerPkcs7Display(PSHOWEXEPKCS7 pThis, PRTCRPKCS7SIGNEDDATA pSignedData, size_t offPrefix,
245 PCRTCRPKCS7CONTENTINFO pContentInfo);
246
247
248/*********************************************************************************************************************************
249* Certificate and Private Key Handling (options, ++). *
250*********************************************************************************************************************************/
251#ifdef RT_OS_WINDOWS
252
253/** @todo create a better fake certificate. */
254const unsigned char g_abFakeCertificate[] =
255{
256 0x30, 0x82, 0x03, 0xb2, 0x30, 0x82, 0x02, 0x9a, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x31, /* 0x00000000: 0...0..........1 */
257 0xba, 0xd6, 0xbc, 0x5d, 0x9a, 0xe0, 0xb0, 0x4e, 0xd4, 0xfa, 0xcc, 0xfb, 0x47, 0x00, 0x5c, 0x30, /* 0x00000010: ...]...N....G.\0 */
258 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x71, /* 0x00000020: ...*.H........0q */
259 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x54, 0x69, 0x6d, 0x65, 0x73, /* 0x00000030: 1.0...U....Times */
260 0x74, 0x61, 0x6d, 0x70, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x32, 0x31, 0x0c, /* 0x00000040: tamp Signing 21. */
261 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x03, 0x44, 0x65, 0x76, 0x31, 0x15, 0x30, 0x13, /* 0x00000050: 0...U....Dev1.0. */
262 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0c, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x6f, 0x6d, 0x70, /* 0x00000060: ..U....Test Comp */
263 0x61, 0x6e, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x09, 0x53, 0x74, /* 0x00000070: any1.0...U....St */
264 0x75, 0x74, 0x74, 0x67, 0x61, 0x72, 0x74, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, /* 0x00000080: uttgart1.0...U.. */
265 0x0c, 0x02, 0x42, 0x42, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x44, /* 0x00000090: ..BB1.0...U....D */
266 0x45, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x31, 0x30, /* 0x000000a0: E0...00010100010 */
267 0x31, 0x5a, 0x17, 0x0d, 0x33, 0x36, 0x31, 0x32, 0x33, 0x31, 0x32, 0x32, 0x35, 0x39, 0x35, 0x39, /* 0x000000b0: 1Z..361231225959 */
268 0x5a, 0x30, 0x71, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x54, 0x69, /* 0x000000c0: Z0q1.0...U....Ti */
269 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x20, /* 0x000000d0: mestamp Signing */
270 0x32, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x03, 0x44, 0x65, 0x76, 0x31, /* 0x000000e0: 21.0...U....Dev1 */
271 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0c, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, /* 0x000000f0: .0...U....Test C */
272 0x6f, 0x6d, 0x70, 0x61, 0x6e, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, /* 0x00000100: ompany1.0...U... */
273 0x09, 0x53, 0x74, 0x75, 0x74, 0x74, 0x67, 0x61, 0x72, 0x74, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, /* 0x00000110: .Stuttgart1.0... */
274 0x55, 0x04, 0x08, 0x0c, 0x02, 0x42, 0x42, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, /* 0x00000120: U....BB1.0...U.. */
275 0x13, 0x02, 0x44, 0x45, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, /* 0x00000130: ..DE0.."0...*.H. */
276 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, /* 0x00000140: ............0... */
277 0x02, 0x82, 0x01, 0x01, 0x00, 0xdb, 0x18, 0x63, 0x33, 0xf2, 0x08, 0x90, 0x5a, 0xab, 0xda, 0x88, /* 0x00000150: .......c3...Z... */
278 0x73, 0x86, 0x49, 0xea, 0x8b, 0xaf, 0xcf, 0x67, 0x15, 0xa5, 0x39, 0xe6, 0xa2, 0x94, 0x0c, 0x3f, /* 0x00000160: s.I....g..9....? */
279 0xa1, 0x2e, 0x6c, 0xd2, 0xdf, 0x01, 0x65, 0x6d, 0xed, 0x6c, 0x4c, 0xac, 0xe7, 0x77, 0x7a, 0x45, /* 0x00000170: ..l...em.lL..wzE */
280 0x05, 0x6b, 0x24, 0xf3, 0xaf, 0x45, 0x35, 0x6e, 0x64, 0x0a, 0xac, 0x1d, 0x37, 0xe1, 0x33, 0xa4, /* 0x00000180: .k$..E5nd...7.3. */
281 0x92, 0xec, 0x45, 0xe8, 0x99, 0xc1, 0xde, 0x6f, 0xab, 0x7c, 0xf0, 0xdc, 0xe2, 0xc5, 0x42, 0xa3, /* 0x00000190: ..E....o.|....B. */
282 0xea, 0xf5, 0x8a, 0xf9, 0x0e, 0xe7, 0xb3, 0x35, 0xa2, 0x75, 0x5e, 0x87, 0xd2, 0x2a, 0xd1, 0x27, /* 0x000001a0: .......5.u^..*.' */
283 0xa6, 0x79, 0x9e, 0xfe, 0x90, 0xbf, 0x97, 0xa4, 0xa1, 0xd8, 0xf7, 0xd7, 0x05, 0x59, 0x44, 0x27, /* 0x000001b0: .y...........YD' */
284 0x39, 0x6e, 0x33, 0x01, 0x2e, 0x46, 0x92, 0x47, 0xbe, 0x50, 0x91, 0x26, 0x27, 0xe5, 0x4b, 0x3a, /* 0x000001c0: 9n3..F.G.P.&'.K: */
285 0x76, 0x26, 0x64, 0x92, 0x0c, 0xa0, 0x54, 0x43, 0x6f, 0x56, 0xcc, 0x7b, 0xd0, 0xe3, 0xd8, 0x39, /* 0x000001d0: v&d...TCoV.{...9 */
286 0x5f, 0xb9, 0x41, 0xda, 0x1c, 0x62, 0x88, 0x0c, 0x45, 0x03, 0x63, 0xf8, 0xff, 0xe5, 0x3e, 0x87, /* 0x000001e0: _.A..b..E.c...>. */
287 0x0c, 0x75, 0xc9, 0xdd, 0xa2, 0xc0, 0x1b, 0x63, 0x19, 0xeb, 0x09, 0x9d, 0xa1, 0xbb, 0x0f, 0x63, /* 0x000001f0: .u.....c.......c */
288 0x67, 0x1c, 0xa3, 0xfd, 0x2f, 0xd1, 0x2a, 0xda, 0xd8, 0x93, 0x66, 0x45, 0x54, 0xef, 0x8b, 0x6d, /* 0x00000200: g.....*...fET..m */
289 0x12, 0x15, 0x0f, 0xd4, 0xb5, 0x04, 0x17, 0x30, 0x5b, 0xfa, 0x12, 0x96, 0x48, 0x5b, 0x38, 0x65, /* 0x00000210: .......0[...H[8e */
290 0xfd, 0x8f, 0x0c, 0xa3, 0x11, 0x46, 0x49, 0xe0, 0x62, 0xc3, 0xcc, 0x34, 0xe6, 0xfb, 0xab, 0x51, /* 0x00000220: .....FI.b..4...Q */
291 0xc3, 0xd4, 0x0b, 0xdc, 0x39, 0x93, 0x87, 0x90, 0x10, 0x9f, 0xce, 0x43, 0x27, 0x31, 0xd5, 0x4e, /* 0x00000230: ....9......C'1.N */
292 0x52, 0x60, 0xf1, 0x93, 0xd5, 0x06, 0xc4, 0x4e, 0x65, 0xb6, 0x35, 0x4a, 0x64, 0x15, 0xf8, 0xaf, /* 0x00000240: R`.....Ne.5Jd... */
293 0x71, 0xb2, 0x42, 0x50, 0x89, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x46, 0x30, 0x44, 0x30, 0x0e, /* 0x00000250: q.BP.......F0D0. */
294 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x07, 0x80, 0x30, 0x13, /* 0x00000260: ..U...........0. */
295 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, /* 0x00000270: ..U.%..0...+.... */
296 0x07, 0x03, 0x08, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x52, 0x9d, /* 0x00000280: ...0...U......R. */
297 0x4d, 0xcd, 0x41, 0xe1, 0xd2, 0x68, 0x22, 0xd3, 0x10, 0x33, 0x01, 0xca, 0xff, 0x00, 0x1d, 0x27, /* 0x00000290: M.A..h"..3.....' */
298 0xa4, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, /* 0x000002a0: ..0...*.H....... */
299 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0xc5, 0x5a, 0x51, 0x83, 0x68, 0x3f, 0x06, 0x39, 0x79, 0x13, /* 0x000002b0: .......ZQ.h?.9y. */
300 0xa6, 0xf0, 0x1a, 0xf9, 0x29, 0x16, 0x2d, 0xa2, 0x07, 0xaa, 0x9b, 0xc3, 0x13, 0x88, 0x39, 0x69, /* 0x000002c0: ....).-.......9i */
301 0xba, 0xf7, 0x0d, 0xfb, 0xc0, 0x6e, 0x3a, 0x0b, 0x49, 0x10, 0xd1, 0xbe, 0x36, 0x91, 0x3f, 0x9d, /* 0x000002d0: .....n:.I...6.?. */
302 0xa1, 0xe8, 0xc4, 0x91, 0xf9, 0x02, 0xe1, 0xf1, 0x01, 0x15, 0x09, 0xb7, 0xa1, 0xf1, 0xec, 0x43, /* 0x000002e0: ...............C */
303 0x0d, 0x73, 0xd1, 0x31, 0x02, 0x4a, 0xce, 0x21, 0xf2, 0xa7, 0x99, 0x7c, 0xee, 0x85, 0x54, 0xc0, /* 0x000002f0: .s.1.J.!...|..T. */
304 0x55, 0x9b, 0x19, 0x37, 0xe8, 0xcf, 0x94, 0x41, 0x10, 0x6e, 0x67, 0xdd, 0x86, 0xaf, 0xb7, 0xfe, /* 0x00000300: U..7...A.ng..... */
305 0x50, 0x05, 0xf6, 0xfb, 0x0a, 0xdf, 0x88, 0xb5, 0x59, 0x69, 0x98, 0x27, 0xf8, 0x81, 0x6a, 0x4a, /* 0x00000310: P.......Yi.'..jJ */
306 0x7c, 0xf3, 0x63, 0xa9, 0x41, 0x78, 0x76, 0x12, 0xdb, 0x0e, 0x94, 0x0a, 0xdb, 0x1d, 0x3c, 0x87, /* 0x00000320: |.c.Axv.......<. */
307 0x35, 0xca, 0x28, 0xeb, 0xb0, 0x62, 0x27, 0x69, 0xe2, 0xf3, 0x84, 0x48, 0xa2, 0x2d, 0xd7, 0x0e, /* 0x00000330: 5.(..b'i...H.-.. */
308 0x4b, 0x6d, 0x39, 0xa7, 0x3e, 0x04, 0x94, 0x8e, 0xb6, 0x4b, 0x91, 0x01, 0x68, 0xf9, 0xd2, 0x75, /* 0x00000340: Km9.>....K..h..u */
309 0x1b, 0xac, 0x42, 0x3b, 0x85, 0xfc, 0x5b, 0x48, 0x3a, 0x13, 0xe7, 0x1c, 0x17, 0xcd, 0x84, 0x89, /* 0x00000350: ..B;..[H:....... */
310 0x9e, 0x5f, 0xe3, 0x77, 0xc0, 0xae, 0x34, 0xc3, 0x87, 0x76, 0x4a, 0x23, 0x30, 0xa0, 0xe1, 0x45, /* 0x00000360: ._.w..4..vJ#0..E */
311 0x94, 0x2a, 0x5b, 0x6b, 0x5a, 0xf0, 0x1a, 0x7e, 0xa6, 0xc4, 0xed, 0xe4, 0xac, 0x5d, 0xdf, 0x87, /* 0x00000370: .*[kZ..~.....].. */
312 0x8f, 0xc5, 0xb4, 0x8c, 0xbc, 0x70, 0xc1, 0xf7, 0xb2, 0x72, 0xbd, 0x73, 0xc9, 0x4e, 0xed, 0x8d, /* 0x00000380: .....p...r.s.N.. */
313 0x29, 0x33, 0xe9, 0x14, 0xc1, 0x5e, 0xff, 0x39, 0xa8, 0xe7, 0x9a, 0x3b, 0x7a, 0x3c, 0xce, 0x5d, /* 0x00000390: )3...^.9...;z<.] */
314 0x0f, 0x3c, 0x82, 0x90, 0xff, 0x81, 0x82, 0x00, 0x82, 0x5f, 0xba, 0x08, 0x79, 0xb1, 0x97, 0xc3, /* 0x000003a0: .<......._..y... */
315 0x09, 0x75, 0xc0, 0x04, 0x9b, 0x67, /* 0x000003b0: .u...g */
316};
317
318const unsigned char g_abFakeRsaKey[] =
319{
320 0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xdb, 0x18, 0x63, 0x33, /* 0x00000000: 0.............c3 */
321 0xf2, 0x08, 0x90, 0x5a, 0xab, 0xda, 0x88, 0x73, 0x86, 0x49, 0xea, 0x8b, 0xaf, 0xcf, 0x67, 0x15, /* 0x00000010: ...Z...s.I....g. */
322 0xa5, 0x39, 0xe6, 0xa2, 0x94, 0x0c, 0x3f, 0xa1, 0x2e, 0x6c, 0xd2, 0xdf, 0x01, 0x65, 0x6d, 0xed, /* 0x00000020: .9....?..l...em. */
323 0x6c, 0x4c, 0xac, 0xe7, 0x77, 0x7a, 0x45, 0x05, 0x6b, 0x24, 0xf3, 0xaf, 0x45, 0x35, 0x6e, 0x64, /* 0x00000030: lL..wzE.k$..E5nd */
324 0x0a, 0xac, 0x1d, 0x37, 0xe1, 0x33, 0xa4, 0x92, 0xec, 0x45, 0xe8, 0x99, 0xc1, 0xde, 0x6f, 0xab, /* 0x00000040: ...7.3...E....o. */
325 0x7c, 0xf0, 0xdc, 0xe2, 0xc5, 0x42, 0xa3, 0xea, 0xf5, 0x8a, 0xf9, 0x0e, 0xe7, 0xb3, 0x35, 0xa2, /* 0x00000050: |....B........5. */
326 0x75, 0x5e, 0x87, 0xd2, 0x2a, 0xd1, 0x27, 0xa6, 0x79, 0x9e, 0xfe, 0x90, 0xbf, 0x97, 0xa4, 0xa1, /* 0x00000060: u^..*.'.y....... */
327 0xd8, 0xf7, 0xd7, 0x05, 0x59, 0x44, 0x27, 0x39, 0x6e, 0x33, 0x01, 0x2e, 0x46, 0x92, 0x47, 0xbe, /* 0x00000070: ....YD'9n3..F.G. */
328 0x50, 0x91, 0x26, 0x27, 0xe5, 0x4b, 0x3a, 0x76, 0x26, 0x64, 0x92, 0x0c, 0xa0, 0x54, 0x43, 0x6f, /* 0x00000080: P.&'.K:v&d...TCo */
329 0x56, 0xcc, 0x7b, 0xd0, 0xe3, 0xd8, 0x39, 0x5f, 0xb9, 0x41, 0xda, 0x1c, 0x62, 0x88, 0x0c, 0x45, /* 0x00000090: V.{...9_.A..b..E */
330 0x03, 0x63, 0xf8, 0xff, 0xe5, 0x3e, 0x87, 0x0c, 0x75, 0xc9, 0xdd, 0xa2, 0xc0, 0x1b, 0x63, 0x19, /* 0x000000a0: .c...>..u.....c. */
331 0xeb, 0x09, 0x9d, 0xa1, 0xbb, 0x0f, 0x63, 0x67, 0x1c, 0xa3, 0xfd, 0x2f, 0xd1, 0x2a, 0xda, 0xd8, /* 0x000000b0: ......cg.....*.. */
332 0x93, 0x66, 0x45, 0x54, 0xef, 0x8b, 0x6d, 0x12, 0x15, 0x0f, 0xd4, 0xb5, 0x04, 0x17, 0x30, 0x5b, /* 0x000000c0: .fET..m.......0[ */
333 0xfa, 0x12, 0x96, 0x48, 0x5b, 0x38, 0x65, 0xfd, 0x8f, 0x0c, 0xa3, 0x11, 0x46, 0x49, 0xe0, 0x62, /* 0x000000d0: ...H[8e.....FI.b */
334 0xc3, 0xcc, 0x34, 0xe6, 0xfb, 0xab, 0x51, 0xc3, 0xd4, 0x0b, 0xdc, 0x39, 0x93, 0x87, 0x90, 0x10, /* 0x000000e0: ..4...Q....9.... */
335 0x9f, 0xce, 0x43, 0x27, 0x31, 0xd5, 0x4e, 0x52, 0x60, 0xf1, 0x93, 0xd5, 0x06, 0xc4, 0x4e, 0x65, /* 0x000000f0: ..C'1.NR`.....Ne */
336 0xb6, 0x35, 0x4a, 0x64, 0x15, 0xf8, 0xaf, 0x71, 0xb2, 0x42, 0x50, 0x89, 0x02, 0x03, 0x01, 0x00, /* 0x00000100: .5Jd...q.BP..... */
337 0x01, 0x02, 0x82, 0x01, 0x01, 0x00, 0xd0, 0x5e, 0x09, 0x3a, 0xc5, 0xdc, 0xcf, 0x2c, 0xec, 0x74, /* 0x00000110: .......^.:...,.t */
338 0x11, 0x81, 0x8d, 0x1d, 0x8f, 0x2a, 0xfa, 0x31, 0x4d, 0xe0, 0x90, 0x1a, 0xd8, 0xf5, 0x95, 0xc7, /* 0x00000120: .....*.1M....... */
339 0x70, 0x5c, 0x62, 0x42, 0xac, 0xe9, 0xd9, 0xf2, 0x14, 0xf1, 0xd0, 0x25, 0xbb, 0xeb, 0x06, 0xfe, /* 0x00000130: p\bB.......%.... */
340 0x09, 0xd6, 0x75, 0x67, 0xd7, 0x39, 0xc1, 0xa0, 0x67, 0x34, 0x4d, 0xd2, 0x12, 0x97, 0xaa, 0x5d, /* 0x00000140: ..ug.9..g4M....] */
341 0xeb, 0x0e, 0xb0, 0x16, 0x6c, 0x78, 0x8e, 0xa0, 0x75, 0xa3, 0xaa, 0x57, 0x88, 0x3b, 0x43, 0x4f, /* 0x00000150: ....lx..u..W.;CO */
342 0x75, 0x85, 0x67, 0xb0, 0x9b, 0xdd, 0x49, 0x0e, 0x6e, 0xdb, 0xea, 0xb3, 0xd4, 0x88, 0x54, 0xa0, /* 0x00000160: u.g...I.n.....T. */
343 0x46, 0x0d, 0x55, 0x6d, 0x98, 0xbd, 0x20, 0xf9, 0x9f, 0x61, 0x2d, 0x6f, 0xc7, 0xd7, 0x16, 0x66, /* 0x00000170: F.Um.. ..a-o...f */
344 0x72, 0xc7, 0x73, 0xbe, 0x9e, 0x48, 0xdc, 0x65, 0x12, 0x46, 0x35, 0x69, 0x55, 0xd8, 0x6b, 0x81, /* 0x00000180: r.s..H.e.F5iU.k. */
345 0x78, 0x40, 0x15, 0x93, 0x60, 0x31, 0x4e, 0x87, 0x15, 0x2a, 0x74, 0x74, 0x7b, 0xa0, 0x1f, 0x59, /* 0x00000190: x@..`1N..*tt{..Y */
346 0x8d, 0xc8, 0x3f, 0xdd, 0xf0, 0x13, 0x88, 0x2a, 0x4a, 0xf2, 0xf5, 0xf1, 0x9e, 0xf3, 0x2d, 0x9c, /* 0x000001a0: ..?....*J.....-. */
347 0x8e, 0xbc, 0xb1, 0x21, 0x45, 0xc7, 0x44, 0x0c, 0x6a, 0xfe, 0x4c, 0x20, 0xdc, 0x73, 0xda, 0x62, /* 0x000001b0: ...!E.D.j.L .s.b */
348 0x21, 0xcb, 0xdf, 0x06, 0xfc, 0x90, 0xc2, 0xbd, 0xd6, 0xde, 0xfb, 0xf6, 0x08, 0x69, 0x5d, 0xea, /* 0x000001c0: !............i]. */
349 0xb3, 0x7f, 0x93, 0x61, 0xf2, 0xc1, 0xd0, 0x61, 0x4f, 0xd5, 0x5b, 0x63, 0xba, 0xb0, 0x3b, 0x07, /* 0x000001d0: ...a...aO.[c..;. */
350 0x7a, 0x55, 0xcd, 0xa1, 0xae, 0x8a, 0x92, 0x21, 0xcc, 0x2f, 0x5b, 0xf8, 0x40, 0x6a, 0xcd, 0xd5, /* 0x000001e0: zU.....!..[.@j.. */
351 0x5f, 0x15, 0xf4, 0xb6, 0xbd, 0xe5, 0x91, 0xb9, 0xa8, 0xcc, 0x2a, 0xa8, 0xa6, 0x67, 0x57, 0x2b, /* 0x000001f0: _.........*..gW+ */
352 0x4b, 0xe9, 0x88, 0xe0, 0xbb, 0x58, 0xac, 0x69, 0x5f, 0x3c, 0x76, 0x28, 0xa6, 0x9d, 0xbc, 0x71, /* 0x00000200: K....X.i_<v(...q */
353 0x7f, 0xcb, 0x0c, 0xc0, 0xbd, 0x61, 0x02, 0x81, 0x81, 0x00, 0xfc, 0x62, 0x79, 0x5b, 0xac, 0xf6, /* 0x00000210: .....a.....by[.. */
354 0x9b, 0x8c, 0xaa, 0x76, 0x2a, 0x30, 0x0e, 0xcf, 0x6b, 0x88, 0x72, 0x54, 0x8c, 0xdf, 0xf3, 0x9d, /* 0x00000220: ...v*0..k.rT.... */
355 0x84, 0xbb, 0xe7, 0x9d, 0xd4, 0x04, 0x29, 0x3c, 0xb5, 0x9d, 0x60, 0x9a, 0xcc, 0x12, 0xf3, 0xfa, /* 0x00000230: ......)<..`..... */
356 0x64, 0x30, 0x23, 0x47, 0xc6, 0xa4, 0x8b, 0x6c, 0x73, 0x6c, 0x6b, 0x78, 0x82, 0xec, 0x05, 0x19, /* 0x00000240: d0#G...lslkx.... */
357 0xde, 0xdd, 0xde, 0x52, 0xc5, 0x20, 0xd1, 0x11, 0x58, 0x19, 0x07, 0x5a, 0x90, 0xdd, 0x22, 0x91, /* 0x00000250: ...R. ..X..Z..". */
358 0x89, 0x22, 0x3f, 0x12, 0x54, 0x1a, 0xb8, 0x79, 0xd8, 0x6c, 0xbc, 0xf5, 0x0d, 0xc7, 0x73, 0x5c, /* 0x00000260: ."?.T..y.l....s\ */
359 0xed, 0xba, 0x40, 0x2b, 0x72, 0x34, 0x34, 0x97, 0xfa, 0x49, 0xf6, 0x43, 0x7c, 0xbc, 0x61, 0x30, /* 0x00000270: ..@+r44..I.C|.a0 */
360 0x54, 0x22, 0x21, 0x5f, 0x77, 0x68, 0x6b, 0x83, 0x95, 0xc6, 0x8d, 0xb8, 0x25, 0x3a, 0xd3, 0xb2, /* 0x00000280: T"!_whk.....%:.. */
361 0xbe, 0x29, 0x94, 0x01, 0x15, 0xf0, 0x36, 0x9d, 0x3e, 0xff, 0x02, 0x81, 0x81, 0x00, 0xde, 0x3b, /* 0x00000290: .)....6.>......; */
362 0xd6, 0x4b, 0x38, 0x69, 0x9b, 0x71, 0x29, 0x89, 0xd4, 0x6d, 0x8c, 0x41, 0xee, 0xe2, 0x4d, 0xfc, /* 0x000002a0: .K8i.q)..m.A..M. */
363 0xf0, 0x9a, 0x73, 0xf1, 0x15, 0x94, 0xac, 0x1b, 0x68, 0x5f, 0x79, 0x15, 0x3a, 0x41, 0x55, 0x09, /* 0x000002b0: ..s.....h_y.:AU. */
364 0xc7, 0x1e, 0xec, 0x27, 0x67, 0xe2, 0xdc, 0x54, 0xa8, 0x09, 0xe6, 0x46, 0x92, 0x92, 0x03, 0x8d, /* 0x000002c0: ...'g..T...F.... */
365 0xe5, 0x96, 0xfb, 0x1a, 0xdd, 0x59, 0x6f, 0x92, 0xf1, 0xf6, 0x8f, 0x76, 0xb0, 0xc5, 0xe6, 0xd7, /* 0x000002d0: .....Yo....v.... */
366 0x1b, 0x25, 0xaf, 0x04, 0x9f, 0xd8, 0x71, 0x27, 0x97, 0x99, 0x23, 0x09, 0x7d, 0xef, 0x06, 0x13, /* 0x000002e0: .%....q'..#.}... */
367 0xab, 0xdc, 0xa2, 0xd8, 0x5f, 0xc5, 0xec, 0xf3, 0x62, 0x20, 0x72, 0x7b, 0xa8, 0xc7, 0x09, 0x24, /* 0x000002f0: ...._...b r{...$ */
368 0xaf, 0x72, 0xc9, 0xea, 0xb8, 0x2d, 0xda, 0x00, 0xc8, 0xfe, 0xb4, 0x9f, 0x9f, 0xc7, 0xa9, 0xf7, /* 0x00000300: .r...-.......... */
369 0x1d, 0xce, 0xb1, 0xdb, 0xc5, 0x8a, 0x4e, 0xe8, 0x88, 0x77, 0x68, 0xdd, 0xf8, 0x77, 0x02, 0x81, /* 0x00000310: ......N..wh..w.. */
370 0x80, 0x5b, 0xa5, 0x8e, 0x98, 0x01, 0xa8, 0xd3, 0x37, 0x33, 0x37, 0x11, 0x7e, 0xbe, 0x02, 0x07, /* 0x00000320: .[......737.~... */
371 0xf4, 0x56, 0x3f, 0xe9, 0x9f, 0xf1, 0x20, 0xc3, 0xf0, 0x4f, 0xdc, 0xf9, 0xfe, 0x40, 0xd3, 0x30, /* 0x00000330: .V?... [email protected] */
372 0xc7, 0xe3, 0x2a, 0x92, 0xec, 0x56, 0xf8, 0x17, 0xa5, 0x7b, 0x4a, 0x37, 0x11, 0xcd, 0x27, 0x26, /* 0x00000340: ..*..V...{J7..'& */
373 0x8a, 0xba, 0x43, 0xda, 0x96, 0xc6, 0x0b, 0x6c, 0xe8, 0x78, 0x30, 0xea, 0x30, 0x4e, 0x7a, 0xd3, /* 0x00000350: ..C....l.x0.0Nz. */
374 0xd8, 0xd2, 0xd8, 0xca, 0x3d, 0xe2, 0xad, 0xa2, 0x74, 0x73, 0x1e, 0xbe, 0xb7, 0xad, 0x41, 0x61, /* 0x00000360: ....=...ts....Aa */
375 0x9b, 0xaa, 0xc9, 0xf9, 0xa4, 0xf1, 0x79, 0x4f, 0x42, 0x10, 0xc7, 0x36, 0x03, 0x4b, 0x0d, 0xdc, /* 0x00000370: ......yOB..6.K.. */
376 0xef, 0x3a, 0xa3, 0xab, 0x09, 0xe4, 0xe8, 0xdd, 0xc4, 0x3f, 0x06, 0x21, 0xa0, 0x23, 0x5a, 0x76, /* 0x00000380: .:.......?.!.#Zv */
377 0xea, 0xd0, 0xcf, 0x8b, 0x85, 0x5f, 0x16, 0x4b, 0x03, 0x62, 0x21, 0x3a, 0xcc, 0x2d, 0xa8, 0xd0, /* 0x00000390: ....._.K.b!:.-.. */
378 0x15, 0x02, 0x81, 0x80, 0x51, 0xf6, 0x89, 0xbb, 0xa6, 0x6b, 0xb4, 0xcb, 0xd0, 0xc1, 0x27, 0xda, /* 0x000003a0: ....Q....k....'. */
379 0xdb, 0x6e, 0xf9, 0xd6, 0xf7, 0x62, 0x81, 0xae, 0xc5, 0x72, 0x36, 0x3e, 0x66, 0x17, 0x99, 0xb0, /* 0x000003b0: .n...b...r6>f... */
380 0x14, 0xad, 0x52, 0x96, 0x03, 0xf2, 0x1e, 0x41, 0x76, 0x61, 0xb6, 0x3c, 0x02, 0x7d, 0x2a, 0x98, /* 0x000003c0: ..R....Ava.<.}*. */
381 0xb4, 0x18, 0x75, 0x38, 0x6b, 0x1d, 0x2b, 0x7f, 0x3a, 0xcf, 0x96, 0xb1, 0xc4, 0xa7, 0xd2, 0x9b, /* 0x000003d0: ..u8k.+.:....... */
382 0xd8, 0x1f, 0xb3, 0x64, 0xda, 0x15, 0x9d, 0xca, 0x91, 0x39, 0x48, 0x67, 0x00, 0x9c, 0xd4, 0x99, /* 0x000003e0: ...d.....9Hg.... */
383 0xc3, 0x45, 0x5d, 0xf0, 0x09, 0x32, 0xba, 0x21, 0x1e, 0xe2, 0x64, 0xb8, 0x50, 0x03, 0x17, 0xbe, /* 0x000003f0: .E]..2.!..d.P... */
384 0xd5, 0xda, 0x6b, 0xce, 0x34, 0xbe, 0x16, 0x03, 0x65, 0x1b, 0x2f, 0xa0, 0xa1, 0x95, 0xc6, 0x8b, /* 0x00000400: ..k.4...e....... */
385 0xc2, 0x3c, 0x59, 0x26, 0xbf, 0xb6, 0x07, 0x85, 0x53, 0x2d, 0xb6, 0x36, 0xa3, 0x91, 0xb9, 0xbb, /* 0x00000410: .<Y&....S-.6.... */
386 0x28, 0xaf, 0x2d, 0x53, 0x02, 0x81, 0x81, 0x00, 0xd7, 0xbc, 0x70, 0xd8, 0x18, 0x4f, 0x65, 0x8c, /* 0x00000420: (.-S......p..Oe. */
387 0x68, 0xca, 0x35, 0x77, 0x43, 0x50, 0x9b, 0xa1, 0xa3, 0x9a, 0x0e, 0x2d, 0x7b, 0x38, 0xf8, 0xba, /* 0x00000430: h.5wCP.....-{8.. */
388 0x14, 0x91, 0x3b, 0xc3, 0x3b, 0x1b, 0xa0, 0x6d, 0x45, 0xe4, 0xa8, 0x28, 0x97, 0xf6, 0x89, 0x13, /* 0x00000440: ..;.;..mE..(.... */
389 0xb6, 0x16, 0x6d, 0x65, 0x47, 0x8c, 0xa6, 0x21, 0xf8, 0x6a, 0xce, 0x4e, 0x44, 0x5e, 0x81, 0x47, /* 0x00000450: ..meG..!.j.ND^.G */
390 0xd9, 0xad, 0x8a, 0xb9, 0xd9, 0xe9, 0x3e, 0x33, 0x1e, 0x5f, 0xe9, 0xe9, 0xa7, 0xea, 0x60, 0x75, /* 0x00000460: ......>3._....`u */
391 0x02, 0x57, 0x71, 0xb5, 0xed, 0x47, 0x77, 0xda, 0x1a, 0x40, 0x38, 0xab, 0x82, 0xd2, 0x0d, 0xf5, /* 0x00000470: .Wq..Gw..@8..... */
392 0x0e, 0x8e, 0xa9, 0x24, 0xdc, 0x30, 0xc9, 0x98, 0xa2, 0x05, 0xcd, 0xca, 0x01, 0xcf, 0xae, 0x1d, /* 0x00000480: ...$.0.......... */
393 0xe9, 0x02, 0x47, 0x0e, 0x46, 0x1d, 0x52, 0x02, 0x9a, 0x99, 0x22, 0x23, 0x7f, 0xf8, 0x9e, 0xc2, /* 0x00000490: ..G.F.R..."#.... */
394 0x16, 0x86, 0xca, 0xa0, 0xa7, 0x34, 0xfb, 0xbc, /* 0x000004a0: .....4.. */
395};
396
397#endif /* RT_OS_WINDOWS */
398
399
400/**
401 * Certificate w/ public key + private key pair for signing.
402 */
403class SignToolKeyPair
404{
405protected:
406 /* Context: */
407 const char *m_pszWhat;
408 bool m_fMandatory;
409
410 /* Parameters kept till finalizing parsing: */
411 const char *m_pszCertFile;
412 const char *m_pszCertSha1;
413 uint8_t m_abCertSha1[RTSHA1_HASH_SIZE];
414 const char *m_pszCertSubject;
415 const char *m_pszCertStore;
416 bool m_fMachineStore; /**< false = personal store */
417
418 const char *m_pszKeyFile;
419 const char *m_pszKeyPassword;
420 const char *m_pszKeyName;
421 const char *m_pszKeyProvider;
422
423 /** String buffer for m_pszKeyPassword when read from file. */
424 RTCString m_strPassword;
425 /** Storage for pCertificate when it's loaded from a file. */
426 RTCRX509CERTIFICATE m_DecodedCert;
427#ifdef RT_OS_WINDOWS
428 /** For the fake certificate */
429 RTCRX509CERTIFICATE m_DecodedFakeCert;
430 /** The certificate store. */
431 HCERTSTORE m_hStore;
432 /** The windows certificate context. */
433 PCCERT_CONTEXT m_pCertCtx;
434 /** Whether hNCryptPrivateKey/hLegacyPrivateKey needs freeing or not. */
435 BOOL m_fFreePrivateHandle;
436#endif
437
438 /** Set if already finalized. */
439 bool m_fFinalized;
440
441 /** Store containing the intermediate certificates available to the host.
442 * */
443 static RTCRSTORE s_hStoreIntermediate;
444 /** Instance counter for helping cleaning up m_hStoreIntermediate. */
445 static uint32_t s_cInstances;
446
447public: /* used to be a struct, thus not prefix either. */
448 /* Result: */
449 PCRTCRX509CERTIFICATE pCertificate;
450 RTCRKEY hPrivateKey;
451#ifdef RT_OS_WINDOWS
452 PCRTCRX509CERTIFICATE pCertificateReal;
453 NCRYPT_KEY_HANDLE hNCryptPrivateKey;
454 HCRYPTPROV hLegacyPrivateKey;
455#endif
456
457public:
458 SignToolKeyPair(const char *a_pszWhat, bool a_fMandatory = false)
459 : m_pszWhat(a_pszWhat)
460 , m_fMandatory(a_fMandatory)
461 , m_pszCertFile(NULL)
462 , m_pszCertSha1(NULL)
463 , m_pszCertSubject(NULL)
464 , m_pszCertStore("MY")
465 , m_fMachineStore(false)
466 , m_pszKeyFile(NULL)
467 , m_pszKeyPassword(NULL)
468 , m_pszKeyName(NULL)
469 , m_pszKeyProvider(NULL)
470#ifdef RT_OS_WINDOWS
471 , m_hStore(NULL)
472 , m_pCertCtx(NULL)
473 , m_fFreePrivateHandle(FALSE)
474#endif
475 , m_fFinalized(false)
476 , pCertificate(NULL)
477 , hPrivateKey(NIL_RTCRKEY)
478#ifdef RT_OS_WINDOWS
479 , pCertificateReal(NULL)
480 , hNCryptPrivateKey(0)
481 , hLegacyPrivateKey(0)
482#endif
483 {
484 RT_ZERO(m_DecodedCert);
485#ifdef RT_OS_WINDOWS
486 RT_ZERO(m_DecodedFakeCert);
487#endif
488 s_cInstances++;
489 }
490
491 virtual ~SignToolKeyPair()
492 {
493 if (hPrivateKey != NIL_RTCRKEY)
494 {
495 RTCrKeyRelease(hPrivateKey);
496 hPrivateKey = NIL_RTCRKEY;
497 }
498 if (pCertificate == &m_DecodedCert)
499 {
500 RTCrX509Certificate_Delete(&m_DecodedCert);
501 pCertificate = NULL;
502 }
503#ifdef RT_OS_WINDOWS
504 if (pCertificate == &m_DecodedFakeCert)
505 {
506 RTCrX509Certificate_Delete(&m_DecodedFakeCert);
507 RTCrX509Certificate_Delete(&m_DecodedCert);
508 pCertificate = NULL;
509 pCertificateReal = NULL;
510 }
511#endif
512#ifdef RT_OS_WINDOWS
513 if (m_pCertCtx != NULL)
514 {
515 CertFreeCertificateContext(m_pCertCtx);
516 m_pCertCtx = NULL;
517 }
518 if (m_hStore != NULL)
519 {
520 CertCloseStore(m_hStore, 0);
521 m_hStore = NULL;
522 }
523#endif
524 s_cInstances--;
525 if (s_cInstances == 0)
526 {
527 RTCrStoreRelease(s_hStoreIntermediate);
528 s_hStoreIntermediate = NIL_RTCRSTORE;
529 }
530 }
531
532 bool isComplete(void) const
533 {
534 return pCertificate && hPrivateKey != NIL_RTCRKEY;
535 }
536
537 bool isNull(void) const
538 {
539 return pCertificate == NULL && hPrivateKey == NIL_RTCRKEY;
540 }
541
542 RTEXITCODE handleOption(unsigned offOpt, PRTGETOPTUNION pValueUnion)
543 {
544 AssertReturn(!m_fFinalized, RTMsgErrorExitFailure("Cannot handle options after finalizeOptions was called!"));
545 switch (offOpt)
546 {
547 case OPT_OFF_CERT_FILE:
548 m_pszCertFile = pValueUnion->psz;
549 m_pszCertSha1 = NULL;
550 m_pszCertSubject = NULL;
551 break;
552 case OPT_OFF_CERT_SHA1:
553 {
554 /* Crude normalization of input separators to colons, since it's likely
555 to use spaces and our conversion function only does colons or nothing. */
556 char szDigest[RTSHA1_DIGEST_LEN * 3 + 1];
557 int rc = RTStrCopy(szDigest, sizeof(szDigest), pValueUnion->psz);
558 if (RT_SUCCESS(rc))
559 {
560 char *pszDigest = RTStrStrip(szDigest);
561 size_t offDst = 0;
562 size_t offSrc = 0;
563 char ch;
564 while ((ch = pszDigest[offSrc++]) != '\0')
565 {
566 if (ch == ' ' || ch == '\t' || ch == ':')
567 {
568 while ((ch = pszDigest[offSrc]) == ' ' || ch == '\t' || ch == ':')
569 offSrc++;
570 ch = ch ? ':' : '\0';
571 }
572 pszDigest[offDst++] = ch;
573 }
574 pszDigest[offDst] = '\0';
575
576 /** @todo add a more relaxed input mode to RTStrConvertHexBytes that can deal
577 * with spaces as well as multi-byte cluster of inputs. */
578 rc = RTStrConvertHexBytes(pszDigest, m_abCertSha1, RTSHA1_HASH_SIZE, RTSTRCONVERTHEXBYTES_F_SEP_COLON);
579 if (RT_SUCCESS(rc))
580 {
581 m_pszCertFile = NULL;
582 m_pszCertSha1 = pValueUnion->psz;
583 m_pszCertSubject = NULL;
584 break;
585 }
586 }
587 return RTMsgErrorExitFailure("malformed SHA-1 certificate fingerprint (%Rrc): %s", rc, pValueUnion->psz);
588 }
589 case OPT_OFF_CERT_SUBJECT:
590 m_pszCertFile = NULL;
591 m_pszCertSha1 = NULL;
592 m_pszCertSubject = pValueUnion->psz;
593 break;
594 case OPT_OFF_CERT_STORE:
595 m_pszCertStore = pValueUnion->psz;
596 break;
597 case OPT_OFF_CERT_STORE_MACHINE:
598 m_fMachineStore = true;
599 break;
600
601 case OPT_OFF_KEY_FILE:
602 m_pszKeyFile = pValueUnion->psz;
603 m_pszKeyName = NULL;
604 break;
605 case OPT_OFF_KEY_NAME:
606 m_pszKeyFile = NULL;
607 m_pszKeyName = pValueUnion->psz;
608 break;
609 case OPT_OFF_KEY_PROVIDER:
610 m_pszKeyProvider = pValueUnion->psz;
611 break;
612 case OPT_OFF_KEY_PASSWORD:
613 m_pszKeyPassword = pValueUnion->psz;
614 break;
615 case OPT_OFF_KEY_PASSWORD_FILE:
616 {
617 m_pszKeyPassword = NULL;
618
619 size_t const cchMax = 512;
620 int rc = m_strPassword.reserveNoThrow(cchMax + 1);
621 if (RT_FAILURE(rc))
622 return RTMsgErrorExitFailure("out of memory");
623
624 PRTSTREAM pStrm = g_pStdIn;
625 bool const fClose = strcmp(pValueUnion->psz, "stdin") != 0;
626 if (fClose)
627 {
628 rc = RTStrmOpen(pValueUnion->psz, "r", &pStrm);
629 if (RT_FAILURE(rc))
630 return RTMsgErrorExitFailure("Failed to open password file '%s' for reading: %Rrc", pValueUnion->psz, rc);
631 }
632 rc = RTStrmGetLine(pStrm, m_strPassword.mutableRaw(), cchMax);
633 if (fClose)
634 RTStrmClose(pStrm);
635 if (rc == VERR_BUFFER_OVERFLOW || rc == VINF_BUFFER_OVERFLOW)
636 return RTMsgErrorExitFailure("Password from '%s' is too long (max %zu)", pValueUnion->psz, cchMax);
637 if (RT_FAILURE(rc))
638 return RTMsgErrorExitFailure("Error reading password from '%s': %Rrc", pValueUnion->psz, rc);
639
640 m_strPassword.jolt();
641 m_strPassword.stripRight();
642 m_pszKeyPassword = m_strPassword.c_str();
643 break;
644 }
645 default:
646 AssertFailedReturn(RTMsgErrorExitFailure("Invalid offOpt=%u!\n", offOpt));
647 }
648 return RTEXITCODE_SUCCESS;
649 }
650
651 RTEXITCODE finalizeOptions(unsigned cVerbosity)
652 {
653 RT_NOREF(cVerbosity);
654
655 /* Only do this once. */
656 if (m_fFinalized)
657 return RTEXITCODE_SUCCESS;
658 m_fFinalized = true;
659
660 /*
661 * Got a cert? Is it required?
662 */
663 bool const fHasKey = ( m_pszKeyFile != NULL
664 || m_pszKeyName != NULL);
665 bool const fHasCert = ( m_pszCertFile != NULL
666 || m_pszCertSha1 != NULL
667 || m_pszCertSubject != NULL);
668 if (!fHasCert)
669 {
670 if (m_fMandatory)
671 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Specifying a %s certificiate is required.", m_pszWhat);
672 return RTEXITCODE_SUCCESS;
673 }
674
675 /*
676 * Get the certificate.
677 */
678 RTERRINFOSTATIC ErrInfo;
679 /* From file: */
680 if (m_pszCertFile)
681 {
682 int rc = RTCrX509Certificate_ReadFromFile(&m_DecodedCert, m_pszCertFile, 0, &g_RTAsn1DefaultAllocator,
683 RTErrInfoInitStatic(&ErrInfo));
684 if (RT_FAILURE(rc))
685 return RTMsgErrorExitFailure("Error reading %s certificate from '%s': %Rrc%#RTeim",
686 m_pszWhat, m_pszCertFile, rc, &ErrInfo.Core);
687 pCertificate = &m_DecodedCert;
688 }
689 /* From certificate store by name (substring) or fingerprint: */
690 else
691 {
692#ifdef RT_OS_WINDOWS
693 m_hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, X509_ASN_ENCODING, NULL,
694 CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | CERT_STORE_READONLY_FLAG
695 | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_ENUM_ARCHIVED_FLAG
696 | (m_fMachineStore ? CERT_SYSTEM_STORE_LOCAL_MACHINE : CERT_SYSTEM_STORE_CURRENT_USER),
697 m_pszCertStore);
698 if (m_hStore == NULL)
699 return RTMsgErrorExitFailure("Failed to open %s store '%s': %Rwc (%u)", m_fMachineStore ? "machine" : "user",
700 m_pszCertStore, GetLastError(), GetLastError());
701
702 CRYPT_HASH_BLOB Thumbprint = { RTSHA1_HASH_SIZE, m_abCertSha1 };
703 PRTUTF16 pwszSubject = NULL;
704 void const *pvFindParam = &Thumbprint;
705 DWORD fFind = CERT_FIND_SHA1_HASH;
706 if (!m_pszCertSha1)
707 {
708 int rc = RTStrToUtf16(m_pszCertSubject, &pwszSubject);
709 if (RT_FAILURE(rc))
710 return RTMsgErrorExitFailure("RTStrToUtf16 failed: %Rrc, input %.*Rhxs",
711 rc, strlen(m_pszCertSubject), m_pszCertSubject);
712 pvFindParam = pwszSubject;
713 fFind = CERT_FIND_SUBJECT_STR;
714 }
715
716 while ((m_pCertCtx = CertFindCertificateInStore(m_hStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0 /*fFlags*/,
717 fFind, pvFindParam, m_pCertCtx)) != NULL)
718 {
719 if (m_pCertCtx->dwCertEncodingType & X509_ASN_ENCODING)
720 {
721 RTASN1CURSORPRIMARY PrimaryCursor;
722 RTAsn1CursorInitPrimary(&PrimaryCursor, m_pCertCtx->pbCertEncoded, m_pCertCtx->cbCertEncoded,
723 RTErrInfoInitStatic(&ErrInfo),
724 &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "CurCtx");
725 int rc = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, &m_DecodedCert, "Cert");
726 if (RT_SUCCESS(rc))
727 {
728 pCertificate = &m_DecodedCert;
729 break;
730 }
731 RTMsgError("failed to decode certificate %p: %Rrc%#RTeim", m_pCertCtx, rc, &ErrInfo.Core);
732 }
733 }
734
735 RTUtf16Free(pwszSubject);
736 if (!m_pCertCtx)
737 return RTMsgErrorExitFailure("No certificate found matching %s '%s' (%Rwc / %u)",
738 m_pszCertSha1 ? "thumbprint" : "subject substring",
739 m_pszCertSha1 ? m_pszCertSha1 : m_pszCertSubject, GetLastError(), GetLastError());
740
741 /* Use this for private key too? */
742 if (!fHasKey)
743 {
744 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hTmpPrivateKey = 0;
745 DWORD dwKeySpec = 0;
746 if (CryptAcquireCertificatePrivateKey(m_pCertCtx,
747 CRYPT_ACQUIRE_SILENT_FLAG | CRYPT_ACQUIRE_COMPARE_KEY_FLAG
748 | CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG
749 | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
750 NULL, &hTmpPrivateKey, &dwKeySpec, &m_fFreePrivateHandle))
751 {
752 if (cVerbosity > 1)
753 RTMsgInfo("hTmpPrivateKey=%p m_fFreePrivateHandle=%d dwKeySpec=%#x",
754 hTmpPrivateKey, m_fFreePrivateHandle, dwKeySpec);
755 Assert(dwKeySpec == CERT_NCRYPT_KEY_SPEC);
756 if (dwKeySpec == CERT_NCRYPT_KEY_SPEC)
757 hNCryptPrivateKey = hTmpPrivateKey;
758 else
759 hLegacyPrivateKey = hTmpPrivateKey; /** @todo remove or drop CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG */
760 return loadFakePrivateKeyAndCert();
761 }
762 return RTMsgErrorExitFailure("CryptAcquireCertificatePrivateKey failed: %Rwc (%d)", GetLastError(), GetLastError());
763 }
764#else
765 return RTMsgErrorExitFailure("Certificate store support is missing on this host");
766#endif
767 }
768
769 /*
770 * Get hold of the private key (if someone above already did, they'd returned already).
771 */
772 Assert(hPrivateKey == NIL_RTCRKEY);
773 /* Use cert file if nothing else specified. */
774 if (!fHasKey && m_pszCertFile)
775 m_pszKeyFile = m_pszCertFile;
776
777 /* Load from file:*/
778 if (m_pszKeyFile)
779 {
780 int rc = RTCrKeyCreateFromFile(&hPrivateKey, 0 /*fFlags*/, m_pszKeyFile, m_pszKeyPassword,
781 RTErrInfoInitStatic(&ErrInfo));
782 if (RT_FAILURE(rc))
783 return RTMsgErrorExitFailure("Error reading the %s private key from '%s': %Rrc%#RTeim",
784 m_pszWhat, m_pszKeyFile, rc, &ErrInfo.Core);
785 }
786 /* From key store: */
787 else
788 {
789 return RTMsgErrorExitFailure("Key store support is missing on this host");
790 }
791
792 return RTEXITCODE_SUCCESS;
793 }
794
795 /** Returns the real certificate. */
796 PCRTCRX509CERTIFICATE getRealCertificate() const
797 {
798#ifdef RT_OS_WINDOWS
799 if (pCertificateReal)
800 return pCertificateReal;
801#endif
802 return pCertificate;
803 }
804
805#ifdef RT_OS_WINDOWS
806 RTEXITCODE loadFakePrivateKeyAndCert()
807 {
808 int rc = RTCrX509Certificate_ReadFromBuffer(&m_DecodedFakeCert, g_abFakeCertificate, sizeof(g_abFakeCertificate),
809 0 /*fFlags*/, &g_RTAsn1DefaultAllocator, NULL, NULL);
810 if (RT_FAILURE(rc))
811 return RTMsgErrorExitFailure("RTCrX509Certificate_ReadFromBuffer/g_abFakeCertificate failed: %Rrc", rc);
812 pCertificateReal = pCertificate;
813 pCertificate = &m_DecodedFakeCert;
814
815 rc = RTCrKeyCreateFromBuffer(&hPrivateKey, 0 /*fFlags*/, g_abFakeRsaKey, sizeof(g_abFakeRsaKey), NULL, NULL, NULL);
816 if (RT_FAILURE(rc))
817 return RTMsgErrorExitFailure("RTCrKeyCreateFromBuffer/g_abFakeRsaKey failed: %Rrc", rc);
818 return RTEXITCODE_SUCCESS;
819 }
820
821#endif
822
823 /**
824 * Search for intermediate CA.
825 *
826 * Currently this only do a single certificate path, so this may go south if
827 * there are multiple paths available. It may work fine for a cross signing
828 * path, as long as the cross over is at the level immediately below the root.
829 */
830 PCRTCRCERTCTX findNextIntermediateCert(PCRTCRCERTCTX pPrev)
831 {
832 /*
833 * Make sure the store is loaded before we start.
834 */
835 if (s_hStoreIntermediate == NIL_RTCRSTORE)
836 {
837 Assert(!pPrev);
838 RTERRINFOSTATIC ErrInfo;
839 int rc = RTCrStoreCreateSnapshotById(&s_hStoreIntermediate,
840 !m_fMachineStore
841 ? RTCRSTOREID_USER_INTERMEDIATE_CAS : RTCRSTOREID_SYSTEM_INTERMEDIATE_CAS,
842 RTErrInfoInitStatic(&ErrInfo));
843 if (RT_FAILURE(rc))
844 {
845 RTMsgError("RTCrStoreCreateSnapshotById/%s-intermediate-CAs failed: %Rrc%#RTeim",
846 m_fMachineStore ? "user" : "machine", rc, &ErrInfo.Core);
847 return NULL;
848 }
849 }
850
851 /*
852 * Open the search handle for the parent of the previous/end certificate.
853 *
854 * We don't need to consider RTCRCERTCTX::pTaInfo here as we're not
855 * after trust anchors, only intermediate certificates.
856 */
857#ifdef RT_OS_WINDOWS
858 PCRTCRX509CERTIFICATE pChildCert = pPrev ? pPrev->pCert : pCertificateReal ? pCertificateReal : pCertificate;
859#else
860 PCRTCRX509CERTIFICATE pChildCert = pPrev ? pPrev->pCert : pCertificate;
861#endif
862 AssertReturnStmt(pChildCert, RTCrCertCtxRelease(pPrev), NULL);
863
864 RTCRSTORECERTSEARCH Search;
865 int rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(s_hStoreIntermediate, &pChildCert->TbsCertificate.Issuer,
866 &Search);
867 if (RT_FAILURE(rc))
868 {
869 RTMsgError("RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280 failed: %Rrc", rc);
870 return NULL;
871 }
872
873 /*
874 * We only gave the subject so, we have to check the serial number our selves.
875 */
876 PCRTCRCERTCTX pCertCtx;
877 while ((pCertCtx = RTCrStoreCertSearchNext(s_hStoreIntermediate, &Search)) != NULL)
878 {
879 if ( pCertCtx->pCert
880 && RTAsn1BitString_Compare(&pCertCtx->pCert->TbsCertificate.T1.IssuerUniqueId,
881 &pChildCert->TbsCertificate.T1.IssuerUniqueId) == 0 /* compares presentness too */
882 && !RTCrX509Certificate_IsSelfSigned(pCertCtx->pCert))
883 {
884 break; /** @todo compare valid periode too and keep a best match when outside the desired period? */
885 }
886 RTCrCertCtxRelease(pCertCtx);
887 }
888
889 RTCrStoreCertSearchDestroy(s_hStoreIntermediate, & Search);
890 RTCrCertCtxRelease(pPrev);
891 return pCertCtx;
892 }
893
894 /**
895 * Merges the user specified certificates with the signing certificate and any
896 * intermediate CAs we can find in the system store.
897 *
898 * @returns Merged store, NIL_RTCRSTORE on failure (messaged).
899 * @param hUserSpecifiedCertificates The user certificate store.
900 */
901 RTCRSTORE assembleAllAdditionalCertificates(RTCRSTORE hUserSpecifiedCertificates)
902 {
903 RTCRSTORE hRetStore;
904 int rc = RTCrStoreCreateInMemEx(&hRetStore, 0, hUserSpecifiedCertificates);
905 if (RT_SUCCESS(rc))
906 {
907 /* Add the signing certificate: */
908 RTERRINFOSTATIC ErrInfo;
909 rc = RTCrStoreCertAddX509(hRetStore, RTCRCERTCTX_F_ENC_X509_DER | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
910#ifdef RT_OS_WINDOWS
911 (PRTCRX509CERTIFICATE)(pCertificateReal ? pCertificateReal : pCertificate),
912#else
913 (PRTCRX509CERTIFICATE)pCertificate,
914#endif
915 RTErrInfoInitStatic(&ErrInfo));
916 if (RT_SUCCESS(rc))
917 {
918 /* Add all intermediate CAs certificates we can find. */
919 PCRTCRCERTCTX pInterCaCert = NULL;
920 while ((pInterCaCert = findNextIntermediateCert(pInterCaCert)) != NULL)
921 {
922 rc = RTCrStoreCertAddEncoded(hRetStore, RTCRCERTCTX_F_ENC_X509_DER | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
923 pInterCaCert->pabEncoded, pInterCaCert->cbEncoded,
924 RTErrInfoInitStatic(&ErrInfo));
925 if (RT_FAILURE(rc))
926 {
927 RTMsgError("RTCrStoreCertAddEncoded/InterCA failed: %Rrc%#RTeim", rc, &ErrInfo.Core);
928 RTCrCertCtxRelease(pInterCaCert);
929 break;
930 }
931 }
932 if (RT_SUCCESS(rc))
933 return hRetStore;
934 }
935 else
936 RTMsgError("RTCrStoreCertAddX509/signer failed: %Rrc%#RTeim", rc, &ErrInfo.Core);
937 RTCrStoreRelease(hRetStore);
938 }
939 else
940 RTMsgError("RTCrStoreCreateInMemEx failed: %Rrc", rc);
941 return NIL_RTCRSTORE;
942 }
943
944};
945
946/*static*/ RTCRSTORE SignToolKeyPair::s_hStoreIntermediate = NIL_RTCRSTORE;
947/*static*/ uint32_t SignToolKeyPair::s_cInstances = 0;
948
949
950/*********************************************************************************************************************************
951*
952*********************************************************************************************************************************/
953/** Timestamp type. */
954typedef enum
955{
956 /** Old timestamp style.
957 * This is just a counter signature with a trustworthy SigningTime attribute.
958 * Specificially it's the SignerInfo part of a detached PKCS#7 covering the
959 * SignerInfo.EncryptedDigest. */
960 kTimestampType_Old = 1,
961 /** This is a whole PKCS#7 signature of an TSTInfo from RFC-3161 (see page 7).
962 * Currently not supported. */
963 kTimestampType_New
964} TIMESTAMPTYPE;
965
966/**
967 * Timestamping options.
968 *
969 * Certificate w/ public key + private key pair for signing and signature type.
970 */
971class SignToolTimestampOpts : public SignToolKeyPair
972{
973public:
974 /** Type timestamp type. */
975 TIMESTAMPTYPE m_enmType;
976
977 SignToolTimestampOpts(const char *a_pszWhat, TIMESTAMPTYPE a_enmType = kTimestampType_Old)
978 : SignToolKeyPair(a_pszWhat)
979 , m_enmType(a_enmType)
980 {
981 }
982
983 bool isOldType() const { return m_enmType == kTimestampType_Old; }
984 bool isNewType() const { return m_enmType == kTimestampType_New; }
985};
986
987
988
989/*********************************************************************************************************************************
990* Crypto Store Auto Cleanup Wrapper. *
991*********************************************************************************************************************************/
992class CryptoStore
993{
994public:
995 RTCRSTORE m_hStore;
996
997 CryptoStore()
998 : m_hStore(NIL_RTCRSTORE)
999 {
1000 }
1001
1002 ~CryptoStore()
1003 {
1004 if (m_hStore != NIL_RTCRSTORE)
1005 {
1006 uint32_t cRefs = RTCrStoreRelease(m_hStore);
1007 Assert(cRefs == 0); RT_NOREF(cRefs);
1008 m_hStore = NIL_RTCRSTORE;
1009 }
1010 }
1011
1012 /**
1013 * Adds one or more certificates from the given file.
1014 *
1015 * @returns boolean success indicator.
1016 */
1017 bool addFromFile(const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
1018 {
1019 int rc = RTCrStoreCertAddFromFile(this->m_hStore, RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR,
1020 pszFilename, RTErrInfoInitStatic(pStaticErrInfo));
1021 if (RT_SUCCESS(rc))
1022 {
1023 if (RTErrInfoIsSet(&pStaticErrInfo->Core))
1024 RTMsgWarning("Warnings loading certificate '%s': %s", pszFilename, pStaticErrInfo->Core.pszMsg);
1025 return true;
1026 }
1027 RTMsgError("Error loading certificate '%s': %Rrc%#RTeim", pszFilename, rc, &pStaticErrInfo->Core);
1028 return false;
1029 }
1030
1031 /**
1032 * Adds trusted self-signed certificates from the system.
1033 *
1034 * @returns boolean success indicator.
1035 * @note The selection is self-signed rather than CAs here so that test signing
1036 * certificates will be included.
1037 */
1038 bool addSelfSignedRootsFromSystem(PRTERRINFOSTATIC pStaticErrInfo)
1039 {
1040 CryptoStore Tmp;
1041 int rc = RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts(&Tmp.m_hStore, RTErrInfoInitStatic(pStaticErrInfo));
1042 if (RT_SUCCESS(rc))
1043 {
1044 RTCRSTORECERTSEARCH Search;
1045 rc = RTCrStoreCertFindAll(Tmp.m_hStore, &Search);
1046 if (RT_SUCCESS(rc))
1047 {
1048 PCRTCRCERTCTX pCertCtx;
1049 while ((pCertCtx = RTCrStoreCertSearchNext(Tmp.m_hStore, &Search)) != NULL)
1050 {
1051 /* Add it if it's a full fledged self-signed certificate, otherwise just skip: */
1052 if ( pCertCtx->pCert
1053 && RTCrX509Certificate_IsSelfSigned(pCertCtx->pCert))
1054 {
1055 int rc2 = RTCrStoreCertAddEncoded(this->m_hStore,
1056 pCertCtx->fFlags | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
1057 pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL);
1058 if (RT_FAILURE(rc2))
1059 RTMsgWarning("RTCrStoreCertAddEncoded failed for a certificate: %Rrc", rc2);
1060 }
1061 RTCrCertCtxRelease(pCertCtx);
1062 }
1063
1064 int rc2 = RTCrStoreCertSearchDestroy(Tmp.m_hStore, &Search);
1065 AssertRC(rc2);
1066 return true;
1067 }
1068 RTMsgError("RTCrStoreCertFindAll failed: %Rrc", rc);
1069 }
1070 else
1071 RTMsgError("RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
1072 return false;
1073 }
1074
1075 /**
1076 * Adds trusted self-signed certificates from the system.
1077 *
1078 * @returns boolean success indicator.
1079 */
1080 bool addIntermediateCertsFromSystem(PRTERRINFOSTATIC pStaticErrInfo)
1081 {
1082 bool fRc = true;
1083 RTCRSTOREID const s_aenmStoreIds[] = { RTCRSTOREID_SYSTEM_INTERMEDIATE_CAS, RTCRSTOREID_USER_INTERMEDIATE_CAS };
1084 for (size_t i = 0; i < RT_ELEMENTS(s_aenmStoreIds); i++)
1085 {
1086 CryptoStore Tmp;
1087 int rc = RTCrStoreCreateSnapshotById(&Tmp.m_hStore, s_aenmStoreIds[i], RTErrInfoInitStatic(pStaticErrInfo));
1088 if (RT_SUCCESS(rc))
1089 {
1090 RTCRSTORECERTSEARCH Search;
1091 rc = RTCrStoreCertFindAll(Tmp.m_hStore, &Search);
1092 if (RT_SUCCESS(rc))
1093 {
1094 PCRTCRCERTCTX pCertCtx;
1095 while ((pCertCtx = RTCrStoreCertSearchNext(Tmp.m_hStore, &Search)) != NULL)
1096 {
1097 /* Skip selfsigned certs as they're useless as intermediate certs (IIRC). */
1098 if ( pCertCtx->pCert
1099 && !RTCrX509Certificate_IsSelfSigned(pCertCtx->pCert))
1100 {
1101 int rc2 = RTCrStoreCertAddEncoded(this->m_hStore,
1102 pCertCtx->fFlags | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
1103 pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL);
1104 if (RT_FAILURE(rc2))
1105 RTMsgWarning("RTCrStoreCertAddEncoded failed for a certificate: %Rrc", rc2);
1106 }
1107 RTCrCertCtxRelease(pCertCtx);
1108 }
1109
1110 int rc2 = RTCrStoreCertSearchDestroy(Tmp.m_hStore, &Search);
1111 AssertRC(rc2);
1112 }
1113 else
1114 {
1115 RTMsgError("RTCrStoreCertFindAll/%d failed: %Rrc", s_aenmStoreIds[i], rc);
1116 fRc = false;
1117 }
1118 }
1119 else
1120 {
1121 RTMsgError("RTCrStoreCreateSnapshotById/%d failed: %Rrc%#RTeim", s_aenmStoreIds[i], rc, &pStaticErrInfo->Core);
1122 fRc = false;
1123 }
1124 }
1125 return fRc;
1126 }
1127
1128};
1129
1130
1131
1132/*********************************************************************************************************************************
1133* Workers. *
1134*********************************************************************************************************************************/
1135
1136
1137/**
1138 * Deletes the structure.
1139 *
1140 * @param pThis The structure to initialize.
1141 */
1142static void SignToolPkcs7_Delete(PSIGNTOOLPKCS7 pThis)
1143{
1144 RTCrPkcs7ContentInfo_Delete(&pThis->ContentInfo);
1145 pThis->pSignedData = NULL;
1146 RTMemFree(pThis->pbBuf);
1147 pThis->pbBuf = NULL;
1148 pThis->cbBuf = 0;
1149 RTMemFree(pThis->pbNewBuf);
1150 pThis->pbNewBuf = NULL;
1151 pThis->cbNewBuf = 0;
1152}
1153
1154
1155/**
1156 * Deletes the structure.
1157 *
1158 * @param pThis The structure to initialize.
1159 */
1160static void SignToolPkcs7Exe_Delete(PSIGNTOOLPKCS7EXE pThis)
1161{
1162 if (pThis->hLdrMod != NIL_RTLDRMOD)
1163 {
1164 int rc2 = RTLdrClose(pThis->hLdrMod);
1165 if (RT_FAILURE(rc2))
1166 RTMsgError("RTLdrClose failed: %Rrc\n", rc2);
1167 pThis->hLdrMod = NIL_RTLDRMOD;
1168 }
1169 SignToolPkcs7_Delete(pThis);
1170}
1171
1172
1173/**
1174 * Decodes the PKCS #7 blob pointed to by pThis->pbBuf.
1175 *
1176 * @returns IPRT status code (error message already shown on failure).
1177 * @param pThis The PKCS\#7 signature to decode.
1178 * @param fCatalog Set if catalog file, clear if executable.
1179 */
1180static int SignToolPkcs7_Decode(PSIGNTOOLPKCS7 pThis, bool fCatalog)
1181{
1182 RTERRINFOSTATIC ErrInfo;
1183 RTASN1CURSORPRIMARY PrimaryCursor;
1184 RTAsn1CursorInitPrimary(&PrimaryCursor, pThis->pbBuf, (uint32_t)pThis->cbBuf, RTErrInfoInitStatic(&ErrInfo),
1185 &g_RTAsn1DefaultAllocator, 0, "WinCert");
1186
1187 int rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &pThis->ContentInfo, "CI");
1188 if (RT_SUCCESS(rc))
1189 {
1190 if (RTCrPkcs7ContentInfo_IsSignedData(&pThis->ContentInfo))
1191 {
1192 pThis->pSignedData = pThis->ContentInfo.u.pSignedData;
1193
1194 /*
1195 * Decode the authenticode bits.
1196 */
1197 if (!strcmp(pThis->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID))
1198 {
1199 PRTCRSPCINDIRECTDATACONTENT pIndData = pThis->pSignedData->ContentInfo.u.pIndirectDataContent;
1200 Assert(pIndData);
1201
1202 /*
1203 * Check that things add up.
1204 */
1205 rc = RTCrPkcs7SignedData_CheckSanity(pThis->pSignedData,
1206 RTCRPKCS7SIGNEDDATA_SANITY_F_AUTHENTICODE
1207 | RTCRPKCS7SIGNEDDATA_SANITY_F_ONLY_KNOWN_HASH
1208 | RTCRPKCS7SIGNEDDATA_SANITY_F_SIGNING_CERT_PRESENT,
1209 RTErrInfoInitStatic(&ErrInfo), "SD");
1210 if (RT_SUCCESS(rc))
1211 {
1212 rc = RTCrSpcIndirectDataContent_CheckSanityEx(pIndData,
1213 pThis->pSignedData,
1214 RTCRSPCINDIRECTDATACONTENT_SANITY_F_ONLY_KNOWN_HASH,
1215 RTErrInfoInitStatic(&ErrInfo));
1216 if (RT_FAILURE(rc))
1217 RTMsgError("SPC indirect data content sanity check failed for '%s': %Rrc - %s\n",
1218 pThis->pszFilename, rc, ErrInfo.szMsg);
1219 }
1220 else
1221 RTMsgError("PKCS#7 sanity check failed for '%s': %Rrc - %s\n", pThis->pszFilename, rc, ErrInfo.szMsg);
1222 }
1223 else if (!strcmp(pThis->pSignedData->ContentInfo.ContentType.szObjId, RTCR_PKCS7_DATA_OID))
1224 { /* apple code signing */ }
1225 else if (!fCatalog)
1226 RTMsgError("Unexpected the signed content in '%s': %s (expected %s)", pThis->pszFilename,
1227 pThis->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID);
1228 }
1229 else
1230 rc = RTMsgErrorRc(VERR_CR_PKCS7_NOT_SIGNED_DATA,
1231 "PKCS#7 content is inside '%s' is not 'signedData': %s\n",
1232 pThis->pszFilename, pThis->ContentInfo.ContentType.szObjId);
1233 }
1234 else
1235 RTMsgError("RTCrPkcs7ContentInfo_DecodeAsn1 failed on '%s': %Rrc - %s\n", pThis->pszFilename, rc, ErrInfo.szMsg);
1236 return rc;
1237}
1238
1239
1240/**
1241 * Reads and decodes PKCS\#7 signature from the given cat file.
1242 *
1243 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
1244 * on failure.
1245 * @param pThis The structure to initialize.
1246 * @param pszFilename The catalog (or any other DER PKCS\#7) filename.
1247 * @param cVerbosity The verbosity.
1248 */
1249static RTEXITCODE SignToolPkcs7_InitFromFile(PSIGNTOOLPKCS7 pThis, const char *pszFilename, unsigned cVerbosity)
1250{
1251 /*
1252 * Init the return structure.
1253 */
1254 RT_ZERO(*pThis);
1255 pThis->pszFilename = pszFilename;
1256 pThis->enmType = RTSIGNTOOLFILETYPE_CAT;
1257
1258 /*
1259 * Lazy bird uses RTFileReadAll and duplicates the allocation.
1260 */
1261 void *pvFile;
1262 int rc = RTFileReadAll(pszFilename, &pvFile, &pThis->cbBuf);
1263 if (RT_SUCCESS(rc))
1264 {
1265 pThis->pbBuf = (uint8_t *)RTMemDup(pvFile, pThis->cbBuf);
1266 RTFileReadAllFree(pvFile, pThis->cbBuf);
1267 if (pThis->pbBuf)
1268 {
1269 if (cVerbosity > 2)
1270 RTPrintf("PKCS#7 signature: %u bytes\n", pThis->cbBuf);
1271
1272 /*
1273 * Decode it.
1274 */
1275 rc = SignToolPkcs7_Decode(pThis, true /*fCatalog*/);
1276 if (RT_SUCCESS(rc))
1277 return RTEXITCODE_SUCCESS;
1278 }
1279 else
1280 RTMsgError("Out of memory!");
1281 }
1282 else
1283 RTMsgError("Error reading '%s' into memory: %Rrc", pszFilename, rc);
1284
1285 SignToolPkcs7_Delete(pThis);
1286 return RTEXITCODE_FAILURE;
1287}
1288
1289
1290/**
1291 * Encodes the signature into the SIGNTOOLPKCS7::pbNewBuf and
1292 * SIGNTOOLPKCS7::cbNewBuf members.
1293 *
1294 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
1295 * on failure.
1296 * @param pThis The signature to encode.
1297 * @param cVerbosity The verbosity.
1298 */
1299static RTEXITCODE SignToolPkcs7_Encode(PSIGNTOOLPKCS7 pThis, unsigned cVerbosity)
1300{
1301 RTERRINFOSTATIC StaticErrInfo;
1302 PRTASN1CORE pRoot = RTCrPkcs7ContentInfo_GetAsn1Core(&pThis->ContentInfo);
1303 uint32_t cbEncoded;
1304 int rc = RTAsn1EncodePrepare(pRoot, RTASN1ENCODE_F_DER, &cbEncoded, RTErrInfoInitStatic(&StaticErrInfo));
1305 if (RT_SUCCESS(rc))
1306 {
1307 if (cVerbosity >= 4)
1308 RTAsn1Dump(pRoot, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
1309
1310 RTMemFree(pThis->pbNewBuf);
1311 pThis->cbNewBuf = cbEncoded;
1312 pThis->pbNewBuf = (uint8_t *)RTMemAllocZ(cbEncoded);
1313 if (pThis->pbNewBuf)
1314 {
1315 rc = RTAsn1EncodeToBuffer(pRoot, RTASN1ENCODE_F_DER, pThis->pbNewBuf, pThis->cbNewBuf,
1316 RTErrInfoInitStatic(&StaticErrInfo));
1317 if (RT_SUCCESS(rc))
1318 {
1319 if (cVerbosity > 1)
1320 RTMsgInfo("Encoded signature to %u bytes", cbEncoded);
1321 return RTEXITCODE_SUCCESS;
1322 }
1323 RTMsgError("RTAsn1EncodeToBuffer failed: %Rrc", rc);
1324
1325 RTMemFree(pThis->pbNewBuf);
1326 pThis->pbNewBuf = NULL;
1327 }
1328 else
1329 RTMsgError("Failed to allocate %u bytes!", cbEncoded);
1330 }
1331 else
1332 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
1333 return RTEXITCODE_FAILURE;
1334}
1335
1336
1337/**
1338 * Helper that makes sure the UnauthenticatedAttributes are present in the given
1339 * SignerInfo structure.
1340 *
1341 * Call this before trying to modify the array.
1342 *
1343 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error already
1344 * displayed on failure.
1345 * @param pSignerInfo The SignerInfo structure in question.
1346 */
1347static RTEXITCODE SignToolPkcs7_EnsureUnauthenticatedAttributesPresent(PRTCRPKCS7SIGNERINFO pSignerInfo)
1348{
1349 if (pSignerInfo->UnauthenticatedAttributes.cItems == 0)
1350 {
1351 /* HACK ALERT! Invent ASN.1 setters/whatever for members to replace this mess. */
1352
1353 if (pSignerInfo->AuthenticatedAttributes.cItems == 0)
1354 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No authenticated or unauthenticated attributes! Sorry, no can do.");
1355
1356 Assert(pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.uTag == 0);
1357 int rc = RTAsn1SetCore_Init(&pSignerInfo->UnauthenticatedAttributes.SetCore,
1358 pSignerInfo->AuthenticatedAttributes.SetCore.Asn1Core.pOps);
1359 if (RT_FAILURE(rc))
1360 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTAsn1SetCore_Init failed: %Rrc", rc);
1361 pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.uTag = 1;
1362 pSignerInfo->UnauthenticatedAttributes.SetCore.Asn1Core.fClass = ASN1_TAGCLASS_CONTEXT | ASN1_TAGFLAG_CONSTRUCTED;
1363 RTAsn1MemInitArrayAllocation(&pSignerInfo->UnauthenticatedAttributes.Allocation,
1364 pSignerInfo->AuthenticatedAttributes.Allocation.pAllocator,
1365 sizeof(**pSignerInfo->UnauthenticatedAttributes.papItems));
1366 }
1367 return RTEXITCODE_SUCCESS;
1368}
1369
1370
1371/**
1372 * Adds the @a pSrc signature as a nested signature.
1373 *
1374 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
1375 * on failure.
1376 * @param pThis The signature to modify.
1377 * @param pSrc The signature to add as nested.
1378 * @param cVerbosity The verbosity.
1379 * @param fPrepend Whether to prepend (true) or append (false) the
1380 * source signature to the nested attribute.
1381 */
1382static RTEXITCODE SignToolPkcs7_AddNestedSignature(PSIGNTOOLPKCS7 pThis, PSIGNTOOLPKCS7 pSrc,
1383 unsigned cVerbosity, bool fPrepend)
1384{
1385 PRTCRPKCS7SIGNERINFO pSignerInfo = pThis->pSignedData->SignerInfos.papItems[0];
1386
1387 /*
1388 * Deal with UnauthenticatedAttributes being absent before trying to append to the array.
1389 */
1390 RTEXITCODE rcExit = SignToolPkcs7_EnsureUnauthenticatedAttributesPresent(pSignerInfo);
1391 if (rcExit != RTEXITCODE_SUCCESS)
1392 return rcExit;
1393
1394 /*
1395 * Find or add an unauthenticated attribute for nested signatures.
1396 */
1397 int rc = VERR_NOT_FOUND;
1398 PRTCRPKCS7ATTRIBUTE pAttr = NULL;
1399 int32_t iPos = pSignerInfo->UnauthenticatedAttributes.cItems;
1400 while (iPos-- > 0)
1401 if (pSignerInfo->UnauthenticatedAttributes.papItems[iPos]->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE)
1402 {
1403 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
1404 rc = VINF_SUCCESS;
1405 break;
1406 }
1407 if (iPos < 0)
1408 {
1409 iPos = RTCrPkcs7Attributes_Append(&pSignerInfo->UnauthenticatedAttributes);
1410 if (iPos >= 0)
1411 {
1412 if (cVerbosity >= 3)
1413 RTMsgInfo("Adding UnauthenticatedAttribute #%u...", iPos);
1414 Assert((uint32_t)iPos < pSignerInfo->UnauthenticatedAttributes.cItems);
1415
1416 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
1417 rc = RTAsn1ObjId_InitFromString(&pAttr->Type, RTCR_PKCS9_ID_MS_NESTED_SIGNATURE, pAttr->Allocation.pAllocator);
1418 if (RT_SUCCESS(rc))
1419 {
1420 /** @todo Generalize the Type + enmType DYN stuff and generate setters. */
1421 Assert(pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_NOT_PRESENT);
1422 Assert(pAttr->uValues.pContentInfos == NULL);
1423 pAttr->enmType = RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE;
1424 rc = RTAsn1MemAllocZ(&pAttr->Allocation, (void **)&pAttr->uValues.pContentInfos,
1425 sizeof(*pAttr->uValues.pContentInfos));
1426 if (RT_SUCCESS(rc))
1427 {
1428 rc = RTCrPkcs7SetOfContentInfos_Init(pAttr->uValues.pContentInfos, pAttr->Allocation.pAllocator);
1429 if (!RT_SUCCESS(rc))
1430 RTMsgError("RTCrPkcs7ContentInfos_Init failed: %Rrc", rc);
1431 }
1432 else
1433 RTMsgError("RTAsn1MemAllocZ failed: %Rrc", rc);
1434 }
1435 else
1436 RTMsgError("RTAsn1ObjId_InitFromString failed: %Rrc", rc);
1437 }
1438 else
1439 RTMsgError("RTCrPkcs7Attributes_Append failed: %Rrc", iPos);
1440 }
1441 else if (cVerbosity >= 2)
1442 RTMsgInfo("Found UnauthenticatedAttribute #%u...", iPos);
1443 if (RT_SUCCESS(rc))
1444 {
1445 /*
1446 * Append/prepend the signature.
1447 */
1448 uint32_t iActualPos = UINT32_MAX;
1449 iPos = fPrepend ? 0 : pAttr->uValues.pContentInfos->cItems;
1450 rc = RTCrPkcs7SetOfContentInfos_InsertEx(pAttr->uValues.pContentInfos, iPos, &pSrc->ContentInfo,
1451 pAttr->Allocation.pAllocator, &iActualPos);
1452 if (RT_SUCCESS(rc))
1453 {
1454 if (cVerbosity > 0)
1455 RTMsgInfo("Added nested signature (#%u)", iActualPos);
1456 if (cVerbosity >= 3)
1457 {
1458 RTMsgInfo("SingerInfo dump after change:");
1459 RTAsn1Dump(RTCrPkcs7SignerInfo_GetAsn1Core(pSignerInfo), 0, 2, RTStrmDumpPrintfV, g_pStdOut);
1460 }
1461 return RTEXITCODE_SUCCESS;
1462 }
1463
1464 RTMsgError("RTCrPkcs7ContentInfos_InsertEx failed: %Rrc", rc);
1465 }
1466 return RTEXITCODE_FAILURE;
1467}
1468
1469
1470/**
1471 * Writes the signature to the file.
1472 *
1473 * Caller must have called SignToolPkcs7_Encode() prior to this function.
1474 *
1475 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
1476 * message on failure.
1477 * @param pThis The file which to write.
1478 * @param cVerbosity The verbosity.
1479 */
1480static RTEXITCODE SignToolPkcs7_WriteSignatureToFile(PSIGNTOOLPKCS7 pThis, const char *pszFilename, unsigned cVerbosity)
1481{
1482 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
1483
1484 /*
1485 * Open+truncate file, write new signature, close. Simple.
1486 */
1487 RTFILE hFile;
1488 int rc = RTFileOpen(&hFile, pszFilename, RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE | RTFILE_O_DENY_WRITE);
1489 if (RT_SUCCESS(rc))
1490 {
1491 rc = RTFileWrite(hFile, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
1492 if (RT_SUCCESS(rc))
1493 {
1494 rc = RTFileClose(hFile);
1495 if (RT_SUCCESS(rc))
1496 {
1497 if (cVerbosity > 0)
1498 RTMsgInfo("Wrote %u bytes to %s", pThis->cbNewBuf, pszFilename);
1499 return RTEXITCODE_SUCCESS;
1500 }
1501
1502 RTMsgError("RTFileClose failed on %s: %Rrc", pszFilename, rc);
1503 }
1504 else
1505 RTMsgError("Write error on %s: %Rrc", pszFilename, rc);
1506 }
1507 else
1508 RTMsgError("Failed to open %s for writing: %Rrc", pszFilename, rc);
1509 return RTEXITCODE_FAILURE;
1510}
1511
1512
1513
1514/**
1515 * Worker for recursively searching for MS nested signatures and signer infos.
1516 *
1517 * @returns Pointer to the signer info corresponding to @a iReqSignature. NULL
1518 * if not found.
1519 * @param pSignedData The signature to search.
1520 * @param piNextSignature Pointer to the variable keeping track of the next
1521 * signature number.
1522 * @param iReqSignature The request signature number.
1523 * @param ppSignedData Where to return the signature data structure.
1524 * Optional.
1525 */
1526static PRTCRPKCS7SIGNERINFO SignToolPkcs7_FindNestedSignatureByIndexWorker(PRTCRPKCS7SIGNEDDATA pSignedData,
1527 uint32_t *piNextSignature,
1528 uint32_t iReqSignature,
1529 PRTCRPKCS7SIGNEDDATA *ppSignedData)
1530{
1531 for (uint32_t iSignerInfo = 0; iSignerInfo < pSignedData->SignerInfos.cItems; iSignerInfo++)
1532 {
1533 /* Match?*/
1534 PRTCRPKCS7SIGNERINFO pSignerInfo = pSignedData->SignerInfos.papItems[iSignerInfo];
1535 if (*piNextSignature == iReqSignature)
1536 {
1537 if (ppSignedData)
1538 *ppSignedData = pSignedData;
1539 return pSignerInfo;
1540 }
1541 *piNextSignature += 1;
1542
1543 /* Look for nested signatures. */
1544 for (uint32_t iAttrib = 0; iAttrib < pSignerInfo->UnauthenticatedAttributes.cItems; iAttrib++)
1545 if (pSignerInfo->UnauthenticatedAttributes.papItems[iAttrib]->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE)
1546 {
1547 PRTCRPKCS7SETOFCONTENTINFOS pCntInfos;
1548 pCntInfos = pSignerInfo->UnauthenticatedAttributes.papItems[iAttrib]->uValues.pContentInfos;
1549 for (uint32_t iCntInfo = 0; iCntInfo < pCntInfos->cItems; iCntInfo++)
1550 {
1551 PRTCRPKCS7CONTENTINFO pCntInfo = pCntInfos->papItems[iCntInfo];
1552 if (RTCrPkcs7ContentInfo_IsSignedData(pCntInfo))
1553 {
1554 PRTCRPKCS7SIGNERINFO pRet;
1555 pRet = SignToolPkcs7_FindNestedSignatureByIndexWorker(pCntInfo->u.pSignedData, piNextSignature,
1556 iReqSignature, ppSignedData);
1557 if (pRet)
1558 return pRet;
1559 }
1560 }
1561 }
1562 }
1563 return NULL;
1564}
1565
1566
1567/**
1568 * Locates the given nested signature.
1569 *
1570 * @returns Pointer to the signer info corresponding to @a iReqSignature. NULL
1571 * if not found.
1572 * @param pThis The PKCS\#7 structure to search.
1573 * @param iReqSignature The requested signature number.
1574 * @param ppSignedData Where to return the pointer to the signed data that
1575 * the returned signer info belongs to.
1576 *
1577 * @todo Move into SPC or PKCS\#7.
1578 */
1579static PRTCRPKCS7SIGNERINFO SignToolPkcs7_FindNestedSignatureByIndex(PSIGNTOOLPKCS7 pThis, uint32_t iReqSignature,
1580 PRTCRPKCS7SIGNEDDATA *ppSignedData)
1581{
1582 uint32_t iNextSignature = 0;
1583 return SignToolPkcs7_FindNestedSignatureByIndexWorker(pThis->pSignedData, &iNextSignature, iReqSignature, ppSignedData);
1584}
1585
1586
1587/**
1588 * Count the number of signatures, nested or otherwise.
1589 *
1590 * @returns Number of signatures.
1591 * @param pThis The PKCS\#7 structure to search.
1592 *
1593 * @todo Move into SPC or PKCS\#7.
1594 */
1595static uint32_t SignToolPkcs7_CountSignatures(PSIGNTOOLPKCS7 pThis)
1596{
1597 uint32_t iNextSignature = 0;
1598 PRTCRPKCS7SIGNEDDATA pSignedData = NULL;
1599 SignToolPkcs7_FindNestedSignatureByIndexWorker(pThis->pSignedData, &iNextSignature, UINT32_MAX / 2, &pSignedData);
1600 return iNextSignature;
1601}
1602
1603
1604/**
1605 * Reads and decodes PKCS\#7 signature from the given executable, if it has one.
1606 *
1607 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
1608 * on failure.
1609 * @param pThis The structure to initialize.
1610 * @param pszFilename The executable filename.
1611 * @param cVerbosity The verbosity.
1612 * @param enmLdrArch For FAT binaries.
1613 * @param fAllowUnsigned Whether to allow unsigned binaries.
1614 */
1615static RTEXITCODE SignToolPkcs7Exe_InitFromFile(PSIGNTOOLPKCS7EXE pThis, const char *pszFilename, unsigned cVerbosity,
1616 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER, bool fAllowUnsigned = false)
1617{
1618 /*
1619 * Init the return structure.
1620 */
1621 RT_ZERO(*pThis);
1622 pThis->hLdrMod = NIL_RTLDRMOD;
1623 pThis->pszFilename = pszFilename;
1624 pThis->enmType = RTSIGNTOOLFILETYPE_EXE;
1625
1626 /*
1627 * Open the image and check if it's signed.
1628 */
1629 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, enmLdrArch, &pThis->hLdrMod);
1630 if (RT_SUCCESS(rc))
1631 {
1632 bool fIsSigned = false;
1633 rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_IS_SIGNED, &fIsSigned, sizeof(fIsSigned));
1634 if (RT_SUCCESS(rc) && fIsSigned)
1635 {
1636 /*
1637 * Query the PKCS#7 data (assuming M$ style signing) and hand it to a worker.
1638 */
1639 size_t cbActual = 0;
1640#ifdef DEBUG
1641 size_t cbBuf = 64;
1642#else
1643 size_t cbBuf = _512K;
1644#endif
1645 void *pvBuf = RTMemAllocZ(cbBuf);
1646 if (pvBuf)
1647 {
1648 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbActual);
1649 if (rc == VERR_BUFFER_OVERFLOW)
1650 {
1651 RTMemFree(pvBuf);
1652 cbBuf = cbActual;
1653 pvBuf = RTMemAllocZ(cbActual);
1654 if (pvBuf)
1655 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/,
1656 pvBuf, cbBuf, &cbActual);
1657 else
1658 rc = VERR_NO_MEMORY;
1659 }
1660 }
1661 else
1662 rc = VERR_NO_MEMORY;
1663
1664 pThis->pbBuf = (uint8_t *)pvBuf;
1665 pThis->cbBuf = cbActual;
1666 if (RT_SUCCESS(rc))
1667 {
1668 if (cVerbosity > 2)
1669 RTPrintf("PKCS#7 signature: %u bytes\n", cbActual);
1670 if (cVerbosity > 3)
1671 RTPrintf("%.*Rhxd\n", cbActual, pvBuf);
1672
1673 /*
1674 * Decode it.
1675 */
1676 rc = SignToolPkcs7_Decode(pThis, false /*fCatalog*/);
1677 if (RT_SUCCESS(rc))
1678 return RTEXITCODE_SUCCESS;
1679 }
1680 else
1681 RTMsgError("RTLdrQueryPropEx/RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc\n", pszFilename, rc);
1682 }
1683 else if (RT_SUCCESS(rc))
1684 {
1685 if (!fAllowUnsigned || cVerbosity >= 2)
1686 RTMsgInfo("'%s': not signed\n", pszFilename);
1687 if (fAllowUnsigned)
1688 return RTEXITCODE_SUCCESS;
1689 }
1690 else
1691 RTMsgError("RTLdrQueryProp/RTLDRPROP_IS_SIGNED failed on '%s': %Rrc\n", pszFilename, rc);
1692 }
1693 else
1694 RTMsgError("Error opening executable image '%s': %Rrc", pszFilename, rc);
1695
1696 SignToolPkcs7Exe_Delete(pThis);
1697 return RTEXITCODE_FAILURE;
1698}
1699
1700
1701/**
1702 * Calculates the checksum of an executable.
1703 *
1704 * @returns Success indicator (errors are reported)
1705 * @param pThis The exe file to checksum.
1706 * @param hFile The file handle.
1707 * @param puCheckSum Where to return the checksum.
1708 */
1709static bool SignToolPkcs7Exe_CalcPeCheckSum(PSIGNTOOLPKCS7EXE pThis, RTFILE hFile, uint32_t *puCheckSum)
1710{
1711#ifdef RT_OS_WINDOWS
1712 /*
1713 * Try use IMAGEHLP!MapFileAndCheckSumW first.
1714 */
1715 PRTUTF16 pwszPath;
1716 int rc = RTStrToUtf16(pThis->pszFilename, &pwszPath);
1717 if (RT_SUCCESS(rc))
1718 {
1719 decltype(MapFileAndCheckSumW) *pfnMapFileAndCheckSumW;
1720 pfnMapFileAndCheckSumW = (decltype(MapFileAndCheckSumW) *)RTLdrGetSystemSymbol("IMAGEHLP.DLL", "MapFileAndCheckSumW");
1721 if (pfnMapFileAndCheckSumW)
1722 {
1723 DWORD uOldSum = UINT32_MAX;
1724 DWORD uCheckSum = UINT32_MAX;
1725 DWORD dwRc = pfnMapFileAndCheckSumW(pwszPath, &uOldSum, &uCheckSum);
1726 if (dwRc == CHECKSUM_SUCCESS)
1727 {
1728 *puCheckSum = uCheckSum;
1729 return true;
1730 }
1731 }
1732 }
1733#endif
1734
1735 RT_NOREF(pThis, hFile, puCheckSum);
1736 RTMsgError("Implement check sum calcuation fallback!");
1737 return false;
1738}
1739
1740
1741/**
1742 * Writes the signature to the file.
1743 *
1744 * This has the side-effect of closing the hLdrMod member. So, it can only be
1745 * called once!
1746 *
1747 * Caller must have called SignToolPkcs7_Encode() prior to this function.
1748 *
1749 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
1750 * message on failure.
1751 * @param pThis The file which to write.
1752 * @param cVerbosity The verbosity.
1753 */
1754static RTEXITCODE SignToolPkcs7Exe_WriteSignatureToFile(PSIGNTOOLPKCS7EXE pThis, unsigned cVerbosity)
1755{
1756 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
1757
1758 /*
1759 * Get the file header offset and arch before closing the destination handle.
1760 */
1761 uint32_t offNtHdrs;
1762 int rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_FILE_OFF_HEADER, &offNtHdrs, sizeof(offNtHdrs));
1763 if (RT_SUCCESS(rc))
1764 {
1765 RTLDRARCH enmLdrArch = RTLdrGetArch(pThis->hLdrMod);
1766 if (enmLdrArch != RTLDRARCH_INVALID)
1767 {
1768 RTLdrClose(pThis->hLdrMod);
1769 pThis->hLdrMod = NIL_RTLDRMOD;
1770 unsigned cbNtHdrs = 0;
1771 switch (enmLdrArch)
1772 {
1773 case RTLDRARCH_AMD64:
1774 case RTLDRARCH_ARM64:
1775 cbNtHdrs = sizeof(IMAGE_NT_HEADERS64);
1776 break;
1777 case RTLDRARCH_X86_32:
1778 cbNtHdrs = sizeof(IMAGE_NT_HEADERS32);
1779 break;
1780 default:
1781 RTMsgError("Unknown image arch: %d", enmLdrArch);
1782 }
1783 if (cbNtHdrs > 0)
1784 {
1785 if (cVerbosity > 0)
1786 RTMsgInfo("offNtHdrs=%#x cbNtHdrs=%u\n", offNtHdrs, cbNtHdrs);
1787
1788 /*
1789 * Open the executable file for writing.
1790 */
1791 RTFILE hFile;
1792 rc = RTFileOpen(&hFile, pThis->pszFilename, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1793 if (RT_SUCCESS(rc))
1794 {
1795 /* Read the file header and locate the security directory entry. */
1796 union
1797 {
1798 IMAGE_NT_HEADERS32 NtHdrs32;
1799 IMAGE_NT_HEADERS64 NtHdrs64;
1800 } uBuf;
1801 PIMAGE_DATA_DIRECTORY pSecDir = cbNtHdrs == sizeof(IMAGE_NT_HEADERS64)
1802 ? &uBuf.NtHdrs64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]
1803 : &uBuf.NtHdrs32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
1804
1805 rc = RTFileReadAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1806 if ( RT_SUCCESS(rc)
1807 && uBuf.NtHdrs32.Signature == IMAGE_NT_SIGNATURE)
1808 {
1809 /*
1810 * Drop any old signature by truncating the file.
1811 */
1812 if ( pSecDir->Size > 8
1813 && pSecDir->VirtualAddress > offNtHdrs + sizeof(IMAGE_NT_HEADERS32))
1814 {
1815 rc = RTFileSetSize(hFile, pSecDir->VirtualAddress);
1816 if (RT_FAILURE(rc))
1817 RTMsgError("Error truncating file to %#x bytes: %Rrc", pSecDir->VirtualAddress, rc);
1818 }
1819 else if (pSecDir->Size != 0 && pSecDir->VirtualAddress == 0)
1820 rc = RTMsgErrorRc(VERR_BAD_EXE_FORMAT, "Bad security directory entry: VA=%#x Size=%#x",
1821 pSecDir->VirtualAddress, pSecDir->Size);
1822 if (RT_SUCCESS(rc))
1823 {
1824 /*
1825 * Pad the file with zero up to a WIN_CERTIFICATE_ALIGNMENT boundary.
1826 *
1827 * Since the hash algorithm hashes everything up to the signature data,
1828 * zero padding included, the alignment we do here must match the alignment
1829 * padding that done while calculating the hash.
1830 */
1831 uint32_t const cbWinCert = RT_UOFFSETOF(WIN_CERTIFICATE, bCertificate);
1832 uint64_t offCur = 0;
1833 rc = RTFileQuerySize(hFile, &offCur);
1834 if ( RT_SUCCESS(rc)
1835 && offCur < _2G)
1836 {
1837 if (offCur != RT_ALIGN_64(offCur, WIN_CERTIFICATE_ALIGNMENT))
1838 {
1839 uint32_t const cbNeeded = (uint32_t)(RT_ALIGN_64(offCur, WIN_CERTIFICATE_ALIGNMENT) - offCur);
1840 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbNeeded, NULL);
1841 if (RT_SUCCESS(rc))
1842 offCur += cbNeeded;
1843 }
1844 if (RT_SUCCESS(rc))
1845 {
1846 /*
1847 * Write the header followed by the signature data.
1848 */
1849 uint32_t const cbZeroPad = (uint32_t)(RT_ALIGN_Z(pThis->cbNewBuf, 8) - pThis->cbNewBuf);
1850 pSecDir->VirtualAddress = (uint32_t)offCur;
1851 pSecDir->Size = cbWinCert + (uint32_t)pThis->cbNewBuf + cbZeroPad;
1852 if (cVerbosity >= 2)
1853 RTMsgInfo("Writing %u (%#x) bytes of signature at %#x (%u).\n",
1854 pSecDir->Size, pSecDir->Size, pSecDir->VirtualAddress, pSecDir->VirtualAddress);
1855
1856 WIN_CERTIFICATE WinCert;
1857 WinCert.dwLength = pSecDir->Size;
1858 WinCert.wRevision = WIN_CERT_REVISION_2_0;
1859 WinCert.wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
1860
1861 rc = RTFileWriteAt(hFile, offCur, &WinCert, cbWinCert, NULL);
1862 if (RT_SUCCESS(rc))
1863 {
1864 offCur += cbWinCert;
1865 rc = RTFileWriteAt(hFile, offCur, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
1866 }
1867 if (RT_SUCCESS(rc) && cbZeroPad)
1868 {
1869 offCur += pThis->cbNewBuf;
1870 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbZeroPad, NULL);
1871 }
1872 if (RT_SUCCESS(rc))
1873 {
1874 /*
1875 * Reset the checksum (sec dir updated already) and rewrite the header.
1876 */
1877 uBuf.NtHdrs32.OptionalHeader.CheckSum = 0;
1878 offCur = offNtHdrs;
1879 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1880 if (RT_SUCCESS(rc))
1881 rc = RTFileFlush(hFile);
1882 if (RT_SUCCESS(rc))
1883 {
1884 /*
1885 * Calc checksum and write out the header again.
1886 */
1887 uint32_t uCheckSum = UINT32_MAX;
1888 if (SignToolPkcs7Exe_CalcPeCheckSum(pThis, hFile, &uCheckSum))
1889 {
1890 uBuf.NtHdrs32.OptionalHeader.CheckSum = uCheckSum;
1891 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1892 if (RT_SUCCESS(rc))
1893 rc = RTFileFlush(hFile);
1894 if (RT_SUCCESS(rc))
1895 {
1896 rc = RTFileClose(hFile);
1897 if (RT_SUCCESS(rc))
1898 return RTEXITCODE_SUCCESS;
1899 RTMsgError("RTFileClose failed: %Rrc\n", rc);
1900 return RTEXITCODE_FAILURE;
1901 }
1902 }
1903 }
1904 }
1905 }
1906 if (RT_FAILURE(rc))
1907 RTMsgError("Write error at %#RX64: %Rrc", offCur, rc);
1908 }
1909 else if (RT_SUCCESS(rc))
1910 RTMsgError("File to big: %'RU64 bytes", offCur);
1911 else
1912 RTMsgError("RTFileQuerySize failed: %Rrc", rc);
1913 }
1914 }
1915 else if (RT_SUCCESS(rc))
1916 RTMsgError("Not NT executable header!");
1917 else
1918 RTMsgError("Error reading NT headers (%#x bytes) at %#x: %Rrc", cbNtHdrs, offNtHdrs, rc);
1919 RTFileClose(hFile);
1920 }
1921 else
1922 RTMsgError("Failed to open '%s' for writing: %Rrc", pThis->pszFilename, rc);
1923 }
1924 }
1925 else
1926 RTMsgError("RTLdrGetArch failed!");
1927 }
1928 else
1929 RTMsgError("RTLdrQueryProp/RTLDRPROP_FILE_OFF_HEADER failed: %Rrc", rc);
1930 return RTEXITCODE_FAILURE;
1931}
1932
1933#ifndef IPRT_SIGNTOOL_NO_SIGNING
1934
1935static PRTCRPKCS7ATTRIBUTE SignToolPkcs7_AuthAttribAppend(PRTCRPKCS7ATTRIBUTES pAuthAttribs)
1936{
1937 int32_t iPos = RTCrPkcs7Attributes_Append(pAuthAttribs);
1938 if (iPos >= 0)
1939 return pAuthAttribs->papItems[iPos];
1940 RTMsgError("RTCrPkcs7Attributes_Append failed: %Rrc", iPos);
1941 return NULL;
1942}
1943
1944
1945static RTEXITCODE SignToolPkcs7_AuthAttribsAddSigningTime(PRTCRPKCS7ATTRIBUTES pAuthAttribs, RTTIMESPEC SigningTime)
1946{
1947 /*
1948 * Signing time. For the old-style timestamps, Symantec used ASN.1 UTC TIME.
1949 * start -vv vv=ASN1_TAG_UTC_TIME
1950 * 00000187d6a65fd0/23b0: 0d 01 09 05 31 0f 17 0d-31 36 31 30 30 35 30 37 ....1...16100507
1951 * 00000187d6a65fe0/23c0: 35 30 33 30 5a 30 23 06-09 2a 86 48 86 f7 0d 01 5030Z0#..*.H....
1952 * ^^- end 2016-10-05T07:50:30.000000000Z (161005075030Z)
1953 */
1954 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
1955 if (!pAttr)
1956 return RTEXITCODE_FAILURE;
1957
1958 int rc = RTCrPkcs7Attribute_SetSigningTime(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
1959 if (RT_FAILURE(rc))
1960 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetSigningTime failed: %Rrc", rc);
1961
1962 /* Create the timestamp. */
1963 int32_t iPos = RTAsn1SetOfTimes_Append(pAttr->uValues.pSigningTime);
1964 if (iPos < 0)
1965 return RTMsgErrorExitFailure("RTAsn1SetOfTimes_Append failed: %Rrc", iPos);
1966
1967 PRTASN1TIME pTime = pAttr->uValues.pSigningTime->papItems[iPos];
1968 rc = RTAsn1Time_SetTimeSpec(pTime, pAttr->Allocation.pAllocator, &SigningTime);
1969 if (RT_FAILURE(rc))
1970 return RTMsgErrorExitFailure("RTAsn1Time_SetTimeSpec failed: %Rrc", rc);
1971
1972 return RTEXITCODE_SUCCESS;
1973}
1974
1975
1976static RTEXITCODE SignToolPkcs7_AuthAttribsAddSpcOpusInfo(PRTCRPKCS7ATTRIBUTES pAuthAttribs, void *pvInfo)
1977{
1978 /** @todo The OpusInfo is a structure with an optional SpcString and an
1979 * optional SpcLink (url). The two attributes can be set using the /d and /du
1980 * options of MS signtool.exe, I think. We shouldn't be using them atm. */
1981
1982 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
1983 if (!pAttr)
1984 return RTEXITCODE_FAILURE;
1985
1986 int rc = RTCrPkcs7Attribute_SetMsStatementType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
1987 if (RT_FAILURE(rc))
1988 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetMsStatementType failed: %Rrc", rc);
1989
1990 /* Override the ID. */
1991 rc = RTAsn1ObjId_SetFromString(&pAttr->Type, RTCR_PKCS9_ID_MS_SP_OPUS_INFO, pAuthAttribs->Allocation.pAllocator);
1992 if (RT_FAILURE(rc))
1993 return RTMsgErrorExitFailure("RTAsn1ObjId_SetFromString failed: %Rrc", rc);
1994
1995 /* Add attribute value entry. */
1996 int32_t iPos = RTAsn1SetOfObjIdSeqs_Append(pAttr->uValues.pObjIdSeqs);
1997 if (iPos < 0)
1998 return RTMsgErrorExitFailure("RTAsn1SetOfObjIdSeqs_Append failed: %Rrc", iPos);
1999
2000 RT_NOREF(pvInfo); Assert(!pvInfo);
2001 return RTEXITCODE_SUCCESS;
2002}
2003
2004
2005static RTEXITCODE SignToolPkcs7_AuthAttribsAddMsStatementType(PRTCRPKCS7ATTRIBUTES pAuthAttribs, const char *pszTypeId)
2006{
2007 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
2008 if (!pAttr)
2009 return RTEXITCODE_FAILURE;
2010
2011 int rc = RTCrPkcs7Attribute_SetMsStatementType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
2012 if (RT_FAILURE(rc))
2013 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetMsStatementType failed: %Rrc", rc);
2014
2015 /* Add attribute value entry. */
2016 int32_t iPos = RTAsn1SetOfObjIdSeqs_Append(pAttr->uValues.pObjIdSeqs);
2017 if (iPos < 0)
2018 return RTMsgErrorExitFailure("RTAsn1SetOfObjIdSeqs_Append failed: %Rrc", iPos);
2019 PRTASN1SEQOFOBJIDS pSeqObjIds = pAttr->uValues.pObjIdSeqs->papItems[iPos];
2020
2021 /* Add a object id to the value. */
2022 RTASN1OBJID ObjIdValue;
2023 rc = RTAsn1ObjId_InitFromString(&ObjIdValue, pszTypeId, &g_RTAsn1DefaultAllocator);
2024 if (RT_FAILURE(rc))
2025 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszTypeId, rc);
2026
2027 rc = RTAsn1SeqOfObjIds_InsertEx(pSeqObjIds, 0 /*iPos*/, &ObjIdValue, &g_RTAsn1DefaultAllocator, NULL);
2028 RTAsn1ObjId_Delete(&ObjIdValue);
2029 if (RT_FAILURE(rc))
2030 return RTMsgErrorExitFailure("RTAsn1SeqOfObjIds_InsertEx failed: %Rrc", rc);
2031
2032 return RTEXITCODE_SUCCESS;
2033}
2034
2035
2036static RTEXITCODE SignToolPkcs7_AuthAttribsAddContentType(PRTCRPKCS7ATTRIBUTES pAuthAttribs, const char *pszContentTypeId)
2037{
2038 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
2039 if (!pAttr)
2040 return RTEXITCODE_FAILURE;
2041
2042 int rc = RTCrPkcs7Attribute_SetContentType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
2043 if (RT_FAILURE(rc))
2044 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetContentType failed: %Rrc", rc);
2045
2046 /* Add a object id to the value. */
2047 RTASN1OBJID ObjIdValue;
2048 rc = RTAsn1ObjId_InitFromString(&ObjIdValue, pszContentTypeId, pAuthAttribs->Allocation.pAllocator);
2049 if (RT_FAILURE(rc))
2050 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszContentTypeId, rc);
2051
2052 rc = RTAsn1SetOfObjIds_InsertEx(pAttr->uValues.pObjIds, 0 /*iPos*/, &ObjIdValue, pAuthAttribs->Allocation.pAllocator, NULL);
2053 RTAsn1ObjId_Delete(&ObjIdValue);
2054 if (RT_FAILURE(rc))
2055 return RTMsgErrorExitFailure("RTAsn1SetOfObjIds_InsertEx failed: %Rrc", rc);
2056
2057 return RTEXITCODE_SUCCESS;
2058}
2059
2060
2061static RTEXITCODE SignToolPkcs7_AddAuthAttribsForTimestamp(PRTCRPKCS7ATTRIBUTES pAuthAttribs, TIMESTAMPTYPE enmTimestampType,
2062 RTTIMESPEC SigningTime, PCRTCRX509CERTIFICATE pTimestampCert)
2063{
2064 /*
2065 * Add content type.
2066 */
2067 RTEXITCODE rcExit = SignToolPkcs7_AuthAttribsAddContentType(pAuthAttribs,
2068 enmTimestampType == kTimestampType_Old
2069 ? RTCR_PKCS7_DATA_OID : RTCRTSPTSTINFO_OID);
2070 if (rcExit != RTEXITCODE_SUCCESS)
2071 return rcExit;
2072
2073 /*
2074 * Add signing time.
2075 */
2076 rcExit = SignToolPkcs7_AuthAttribsAddSigningTime(pAuthAttribs, SigningTime);
2077 if (rcExit != RTEXITCODE_SUCCESS)
2078 return rcExit;
2079
2080 /*
2081 * More later if we want to support fTimestampTypeOld = false perhaps?
2082 */
2083 Assert(enmTimestampType == kTimestampType_Old);
2084 RT_NOREF(pTimestampCert);
2085
2086 return RTEXITCODE_SUCCESS;
2087}
2088
2089
2090static RTEXITCODE SignToolPkcs7_AddAuthAttribsForImageOrCatSignature(PRTCRPKCS7ATTRIBUTES pAuthAttribs, RTTIMESPEC SigningTime,
2091 bool fNoSigningTime, const char *pszContentTypeId)
2092{
2093 /*
2094 * Add SpcOpusInfo. No attribute values.
2095 * SEQ start -vv vv- Type ObjId
2096 * 1c60: 0e 03 02 1a 05 00 a0 70-30 10 06 0a 2b 06 01 04 .......p0...+...
2097 * 1c70: 01 82 37 02 01 0c 31 02-30 00 30 19 06 09 2a 86 ..7...1.0.0...*.
2098 * Set Of -^^ ^^- Empty Sequence.
2099 */
2100 RTEXITCODE rcExit = SignToolPkcs7_AuthAttribsAddSpcOpusInfo(pAuthAttribs, NULL /*pvInfo - none*/);
2101 if (rcExit != RTEXITCODE_SUCCESS)
2102 return rcExit;
2103
2104 /*
2105 * Add ContentType = Ms-SpcIndirectDataContext?
2106 * SEQ start -vv vv- Type ObjId
2107 * 1c70: 01 82 37 02 01 0c 31 02-30 00 30 19 06 09 2a 86 ..7...1.0.0...*.
2108 * 1c80: 48 86 f7 0d 01 09 03 31-0c 06 0a 2b 06 01 04 01 H......1...+....
2109 * 1c90: 82 37 02 01 04 ^^- ^^- ObjId
2110 * ^- Set Of
2111 */
2112 rcExit = SignToolPkcs7_AuthAttribsAddContentType(pAuthAttribs, pszContentTypeId);
2113 if (rcExit != RTEXITCODE_SUCCESS)
2114 return rcExit;
2115
2116 /*
2117 * Add Ms-SpcStatementType = Ms-SpcIndividualCodeSigning.
2118 * SEQ start -vv vv- Type ObjId
2119 * 1c90: 82 37 02 01 04 30 1c 06-0a 2b 06 01 04 01 82 37 .7...0...+.....7
2120 * 1ca0: 02 01 0b 31 0e 30 0c 06-0a 2b 06 01 04 01 82 37 ...1.0...+.....7
2121 * 1cb0: 02 01 15 ^^ ^^ ^^- ObjId
2122 * Set Of -^^ ^^- Sequence Of
2123 */
2124 rcExit = SignToolPkcs7_AuthAttribsAddMsStatementType(pAuthAttribs, RTCRSPC_STMT_TYPE_INDIVIDUAL_CODE_SIGNING);
2125 if (rcExit != RTEXITCODE_SUCCESS)
2126 return rcExit;
2127
2128 /*
2129 * Add signing time. We add this, even if signtool.exe, since OpenSSL will always do it otherwise.
2130 */
2131 if (!fNoSigningTime) /** @todo requires disabling the code in do_pkcs7_signed_attrib that adds it when absent */
2132 {
2133 rcExit = SignToolPkcs7_AuthAttribsAddSigningTime(pAuthAttribs, SigningTime);
2134 if (rcExit != RTEXITCODE_SUCCESS)
2135 return rcExit;
2136 }
2137
2138 /** @todo more? Some certificate stuff? */
2139
2140 return RTEXITCODE_SUCCESS;
2141}
2142
2143
2144static RTEXITCODE SignToolPkcs7_AppendCounterSignature(PRTCRPKCS7SIGNERINFO pSignerInfo,
2145 PCRTCRPKCS7SIGNERINFO pCounterSignerInfo, unsigned cVerbosity)
2146{
2147 /* Make sure the UnauthenticatedAttributes member is there. */
2148 RTEXITCODE rcExit = SignToolPkcs7_EnsureUnauthenticatedAttributesPresent(pSignerInfo);
2149 if (rcExit != RTEXITCODE_SUCCESS)
2150 return rcExit;
2151
2152#if 0 /* Windows won't accept multiple timestamps either way. Doing the latter as it makes more sense to me... */
2153 /* Append an entry to UnauthenticatedAttributes. */
2154 uint32_t iPos;
2155 int rc = RTCrPkcs7Attributes_InsertEx(&pSignerInfo->UnauthenticatedAttributes, 0 /*iPosition*/, NULL /*pToClone*/,
2156 &g_RTAsn1DefaultAllocator, &iPos);
2157 if (RT_FAILURE(rc))
2158 return RTMsgErrorExitFailure("RTCrPkcs7Attributes_Append failed: %Rrc", rc);
2159 Assert(iPos < pSignerInfo->UnauthenticatedAttributes.cItems); Assert(iPos == 0);
2160 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2161
2162 if (cVerbosity >= 2)
2163 RTMsgInfo("Adding UnauthenticatedAttribute #%u...", iPos);
2164#else
2165 /* Look up the counter signature attribute, create one if needed. */
2166 int rc;
2167 uint32_t iPos = 0;
2168 PRTCRPKCS7ATTRIBUTE pAttr = NULL;
2169 for (; iPos < pSignerInfo->UnauthenticatedAttributes.cItems; iPos++)
2170 {
2171 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2172 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES)
2173 break;
2174 }
2175 if (iPos >= pSignerInfo->UnauthenticatedAttributes.cItems)
2176 {
2177 /* Append a new entry to UnauthenticatedAttributes. */
2178 rc = RTCrPkcs7Attributes_InsertEx(&pSignerInfo->UnauthenticatedAttributes, 0 /*iPosition*/, NULL /*pToClone*/,
2179 &g_RTAsn1DefaultAllocator, &iPos);
2180 if (RT_FAILURE(rc))
2181 return RTMsgErrorExitFailure("RTCrPkcs7Attributes_Append failed: %Rrc", rc);
2182 Assert(iPos < pSignerInfo->UnauthenticatedAttributes.cItems); Assert(iPos == 0);
2183 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2184
2185 /* Create the attrib and its sub-set of counter signatures. */
2186 rc = RTCrPkcs7Attribute_SetCounterSignatures(pAttr, NULL, pAttr->Allocation.pAllocator);
2187 if (RT_FAILURE(rc))
2188 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetCounterSignatures failed: %Rrc", rc);
2189 }
2190
2191 if (cVerbosity >= 2)
2192 RTMsgInfo("Adding UnauthenticatedAttribute #%u.%u...", iPos, pAttr->uValues.pCounterSignatures->cItems);
2193
2194#endif
2195
2196 /* Insert the counter signature. */
2197 rc = RTCrPkcs7SignerInfos_InsertEx(pAttr->uValues.pCounterSignatures, pAttr->uValues.pCounterSignatures->cItems /*iPosition*/,
2198 pCounterSignerInfo, pAttr->Allocation.pAllocator, NULL);
2199 if (RT_FAILURE(rc))
2200 return RTMsgErrorExitFailure("RTCrPkcs7SignerInfos_InsertEx failed: %Rrc", rc);
2201
2202 return RTEXITCODE_SUCCESS;
2203}
2204
2205
2206static RTEXITCODE SignToolPkcs7_AppendCertificate(PRTCRPKCS7SIGNEDDATA pSignedData, PCRTCRX509CERTIFICATE pCertToAppend)
2207{
2208 if (pSignedData->Certificates.cItems == 0 && !RTCrPkcs7SetOfCerts_IsPresent(&pSignedData->Certificates))
2209 return RTMsgErrorExitFailure("PKCS#7 signature includes no certificates! Didn't expect that");
2210
2211 /* Already there? */
2212 PCRTCRX509CERTIFICATE pExisting
2213 = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates, &pCertToAppend->TbsCertificate.Issuer,
2214 &pCertToAppend->TbsCertificate.SerialNumber);
2215 if (!pExisting || RTCrX509Certificate_Compare(pExisting, pCertToAppend) != 0)
2216 {
2217 /* Prepend a RTCRPKCS7CERT entry. */
2218 uint32_t iPos;
2219 int rc = RTCrPkcs7SetOfCerts_InsertEx(&pSignedData->Certificates, 0 /*iPosition*/, NULL /*pToClone*/,
2220 &g_RTAsn1DefaultAllocator, &iPos);
2221 if (RT_FAILURE(rc))
2222 return RTMsgErrorExitFailure("RTCrPkcs7SetOfCerts_Append failed: %Rrc", rc);
2223 PRTCRPKCS7CERT pCertEntry = pSignedData->Certificates.papItems[iPos];
2224
2225 /* Set (clone) the certificate. */
2226 rc = RTCrPkcs7Cert_SetX509Cert(pCertEntry, pCertToAppend, pCertEntry->Allocation.pAllocator);
2227 if (RT_FAILURE(rc))
2228 return RTMsgErrorExitFailure("RTCrPkcs7Cert_X509Cert failed: %Rrc", rc);
2229 }
2230 return RTEXITCODE_SUCCESS;
2231}
2232
2233#ifdef RT_OS_WINDOWS
2234
2235static PCRTUTF16 GetBCryptNameFromCrDigest(RTCRDIGEST hDigest)
2236{
2237 switch (RTCrDigestGetType(hDigest))
2238 {
2239 case RTDIGESTTYPE_MD2: return BCRYPT_MD2_ALGORITHM;
2240 case RTDIGESTTYPE_MD4: return BCRYPT_MD4_ALGORITHM;
2241 case RTDIGESTTYPE_SHA1: return BCRYPT_SHA1_ALGORITHM;
2242 case RTDIGESTTYPE_SHA256: return BCRYPT_SHA256_ALGORITHM;
2243 case RTDIGESTTYPE_SHA384: return BCRYPT_SHA384_ALGORITHM;
2244 case RTDIGESTTYPE_SHA512: return BCRYPT_SHA512_ALGORITHM;
2245 default:
2246 RTMsgError("No BCrypt translation for %s/%d!", RTCrDigestGetAlgorithmOid(hDigest), RTCrDigestGetType(hDigest));
2247 return L"No BCrypt translation";
2248 }
2249}
2250
2251static RTEXITCODE
2252SignToolPkcs7_Pkcs7SignStuffAgainWithReal(const char *pszWhat, SignToolKeyPair *pCertKeyPair, unsigned cVerbosity,
2253 PRTCRPKCS7CONTENTINFO pContentInfo, void **ppvSigned, size_t *pcbSigned)
2254
2255{
2256 RT_NOREF(cVerbosity);
2257
2258 /*
2259 * First remove the fake certificate from the PKCS7 structure and insert the real one.
2260 */
2261 PRTCRPKCS7SIGNEDDATA pSignedData = pContentInfo->u.pSignedData;
2262 unsigned iCert = pSignedData->Certificates.cItems;
2263 unsigned cErased = 0;
2264 while (iCert-- > 0)
2265 {
2266 PCRTCRPKCS7CERT pCert = pSignedData->Certificates.papItems[iCert];
2267 if ( pCert->enmChoice == RTCRPKCS7CERTCHOICE_X509
2268 && RTCrX509Certificate_MatchIssuerAndSerialNumber(pCert->u.pX509Cert,
2269 &pCertKeyPair->pCertificate->TbsCertificate.Issuer,
2270 &pCertKeyPair->pCertificate->TbsCertificate.SerialNumber))
2271 {
2272 RTCrPkcs7SetOfCerts_Erase(&pSignedData->Certificates, iCert);
2273 cErased++;
2274 }
2275 }
2276 if (cErased == 0)
2277 return RTMsgErrorExitFailure("(%s) Failed to find temporary signing certificate in PKCS#7 from OpenSSL: %u certs",
2278 pszWhat, pSignedData->Certificates.cItems);
2279
2280 /* Then insert the real signing certificate. */
2281 PCRTCRX509CERTIFICATE const pRealCertificate = pCertKeyPair->getRealCertificate();
2282 RTEXITCODE rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pRealCertificate);
2283 if (rcExit != RTEXITCODE_SUCCESS)
2284 return rcExit;
2285
2286 /*
2287 * Modify the signer info to reflect the real certificate.
2288 */
2289 PRTCRPKCS7SIGNERINFO pSignerInfo = pSignedData->SignerInfos.papItems[0];
2290 RTCrX509Name_Delete(&pSignerInfo->IssuerAndSerialNumber.Name);
2291 int rc = RTCrX509Name_Clone(&pSignerInfo->IssuerAndSerialNumber.Name,
2292 &pRealCertificate->TbsCertificate.Issuer, &g_RTAsn1DefaultAllocator);
2293 if (RT_FAILURE(rc))
2294 return RTMsgErrorExitFailure("(%s) RTCrX509Name_Clone failed: %Rrc", pszWhat, rc);
2295
2296 RTAsn1Integer_Delete(&pSignerInfo->IssuerAndSerialNumber.SerialNumber);
2297 rc = RTAsn1Integer_Clone(&pSignerInfo->IssuerAndSerialNumber.SerialNumber,
2298 &pRealCertificate->TbsCertificate.SerialNumber, &g_RTAsn1DefaultAllocator);
2299 if (RT_FAILURE(rc))
2300 return RTMsgErrorExitFailure("(%s) RTAsn1Integer_Clone failed: %Rrc", pszWhat, rc);
2301
2302 /* There shouldn't be anything in the authenticated attributes that
2303 we need to modify... */
2304
2305 /*
2306 * Now a create a new signature using the real key. Since we haven't modified
2307 * the authenticated attributes, we can just hash them as-is.
2308 */
2309 /* Create the hash to sign. */
2310 RTCRDIGEST hDigest;
2311 rc = RTCrDigestCreateByObjId(&hDigest, &pSignerInfo->DigestAlgorithm.Algorithm);
2312 if (RT_FAILURE(rc))
2313 return RTMsgErrorExitFailure("(%s) RTCrDigestCreateByObjId failed on '%s': %Rrc",
2314 pszWhat, pSignerInfo->DigestAlgorithm.Algorithm.szObjId, rc);
2315
2316 rcExit = RTEXITCODE_FAILURE;
2317 RTERRINFOSTATIC ErrInfo;
2318 rc = RTCrPkcs7Attributes_HashAttributes(&pSignerInfo->AuthenticatedAttributes, hDigest, RTErrInfoInitStatic(&ErrInfo));
2319 if (RT_SUCCESS(rc))
2320 {
2321 BCRYPT_PKCS1_PADDING_INFO PaddingInfo = { GetBCryptNameFromCrDigest(hDigest) };
2322 DWORD cbSignature = 0;
2323 SECURITY_STATUS rcNCrypt = NCryptSignHash(pCertKeyPair->hNCryptPrivateKey, &PaddingInfo,
2324 (PBYTE)RTCrDigestGetHash(hDigest), RTCrDigestGetHashSize(hDigest),
2325 NULL, 0, &cbSignature, NCRYPT_SILENT_FLAG | BCRYPT_PAD_PKCS1);
2326 if (rcNCrypt == ERROR_SUCCESS)
2327 {
2328 if (cVerbosity)
2329 RTMsgInfo("PaddingInfo: '%ls' cb=%#x, was %#zx\n",
2330 PaddingInfo.pszAlgId, cbSignature, pSignerInfo->EncryptedDigest.Asn1Core.cb);
2331
2332 rc = RTAsn1OctetString_AllocContent(&pSignerInfo->EncryptedDigest, NULL /*pvSrc*/, cbSignature,
2333 &g_RTAsn1DefaultAllocator);
2334 if (RT_SUCCESS(rc))
2335 {
2336 Assert(pSignerInfo->EncryptedDigest.Asn1Core.uData.pv);
2337 rcNCrypt = NCryptSignHash(pCertKeyPair->hNCryptPrivateKey, &PaddingInfo,
2338 (PBYTE)RTCrDigestGetHash(hDigest), RTCrDigestGetHashSize(hDigest),
2339 (PBYTE)pSignerInfo->EncryptedDigest.Asn1Core.uData.pv, cbSignature, &cbSignature,
2340 /*NCRYPT_SILENT_FLAG |*/ BCRYPT_PAD_PKCS1);
2341 if (rcNCrypt == ERROR_SUCCESS)
2342 {
2343 /*
2344 * Now we need to re-encode the whole thing and decode it again.
2345 */
2346 PRTASN1CORE pRoot = RTCrPkcs7ContentInfo_GetAsn1Core(pContentInfo);
2347 uint32_t cbRealSigned;
2348 rc = RTAsn1EncodePrepare(pRoot, RTASN1ENCODE_F_DER, &cbRealSigned, RTErrInfoInitStatic(&ErrInfo));
2349 if (RT_SUCCESS(rc))
2350 {
2351 void *pvRealSigned = RTMemAllocZ(cbRealSigned);
2352 if (pvRealSigned)
2353 {
2354 rc = RTAsn1EncodeToBuffer(pRoot, RTASN1ENCODE_F_DER, pvRealSigned, cbRealSigned,
2355 RTErrInfoInitStatic(&ErrInfo));
2356 if (RT_SUCCESS(rc))
2357 {
2358 /* Decode it */
2359 RTCrPkcs7ContentInfo_Delete(pContentInfo);
2360
2361 RTASN1CURSORPRIMARY PrimaryCursor;
2362 RTAsn1CursorInitPrimary(&PrimaryCursor, pvRealSigned, cbRealSigned, RTErrInfoInitStatic(&ErrInfo),
2363 &g_RTAsn1DefaultAllocator, 0, pszWhat);
2364 rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, pContentInfo, "CI");
2365 if (RT_SUCCESS(rc))
2366 {
2367 Assert(RTCrPkcs7ContentInfo_IsSignedData(pContentInfo));
2368
2369 /* Almost done! Just replace output buffer. */
2370 RTMemFree(*ppvSigned);
2371 *ppvSigned = pvRealSigned;
2372 *pcbSigned = cbRealSigned;
2373 pvRealSigned = NULL;
2374 rcExit = RTEXITCODE_SUCCESS;
2375 }
2376 else
2377 RTMsgError("(%s) RTCrPkcs7ContentInfo_DecodeAsn1 failed: %Rrc%#RTeim",
2378 pszWhat, rc, &ErrInfo.Core);
2379 }
2380 else
2381 RTMsgError("(%s) RTAsn1EncodeToBuffer failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2382
2383 RTMemFree(pvRealSigned);
2384 }
2385 else
2386 RTMsgError("(%s) Failed to allocate %u bytes!", pszWhat, cbRealSigned);
2387 }
2388 else
2389 RTMsgError("(%s) RTAsn1EncodePrepare failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2390 }
2391 else
2392 RTMsgError("(%s) NCryptSignHash/2 failed: %Rwc %#x (%u)", pszWhat, rcNCrypt, rcNCrypt, rcNCrypt);
2393 }
2394 else
2395 RTMsgError("(%s) RTAsn1OctetString_AllocContent(,,%#x) failed: %Rrc", pszWhat, cbSignature, rc);
2396 }
2397 else
2398 RTMsgError("(%s) NCryptSignHash/1 failed: %Rwc %#x (%u)", pszWhat, rcNCrypt, rcNCrypt, rcNCrypt);
2399 }
2400 else
2401 RTMsgError("(%s) RTCrPkcs7Attributes_HashAttributes failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2402 RTCrDigestRelease(hDigest);
2403 return rcExit;
2404}
2405
2406#endif /* RT_OS_WINDOWS */
2407
2408static RTEXITCODE SignToolPkcs7_Pkcs7SignStuffInner(const char *pszWhat, const void *pvToDataToSign, size_t cbToDataToSign,
2409 PCRTCRPKCS7ATTRIBUTES pAuthAttribs, RTCRSTORE hAdditionalCerts,
2410 uint32_t fExtraFlags, RTDIGESTTYPE enmDigestType,
2411 SignToolKeyPair *pCertKeyPair, unsigned cVerbosity,
2412 void **ppvSigned, size_t *pcbSigned, PRTCRPKCS7CONTENTINFO pContentInfo,
2413 PRTCRPKCS7SIGNEDDATA *ppSignedData)
2414{
2415 *ppvSigned = NULL;
2416 if (pcbSigned)
2417 *pcbSigned = 0;
2418 if (ppSignedData)
2419 *ppSignedData = NULL;
2420
2421 /* Figure out how large the signature will be. */
2422 uint32_t const fSignFlags = RTCRPKCS7SIGN_SD_F_USE_V1 | RTCRPKCS7SIGN_SD_F_NO_SMIME_CAP | fExtraFlags;
2423 size_t cbSigned = 1024;
2424 RTERRINFOSTATIC ErrInfo;
2425 int rc = RTCrPkcs7SimpleSignSignedData(fSignFlags, pCertKeyPair->pCertificate, pCertKeyPair->hPrivateKey,
2426 pvToDataToSign, cbToDataToSign,enmDigestType, hAdditionalCerts, pAuthAttribs,
2427 NULL, &cbSigned, RTErrInfoInitStatic(&ErrInfo));
2428 if (rc != VERR_BUFFER_OVERFLOW)
2429 return RTMsgErrorExitFailure("(%s) RTCrPkcs7SimpleSignSignedData failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2430
2431 /* Allocate memory for it and do the actual signing. */
2432 void *pvSigned = RTMemAllocZ(cbSigned);
2433 if (!pvSigned)
2434 return RTMsgErrorExitFailure("(%s) Failed to allocate %#zx bytes for %s signature", pszWhat, cbSigned, pszWhat);
2435 rc = RTCrPkcs7SimpleSignSignedData(fSignFlags, pCertKeyPair->pCertificate, pCertKeyPair->hPrivateKey,
2436 pvToDataToSign, cbToDataToSign, enmDigestType, hAdditionalCerts, pAuthAttribs,
2437 pvSigned, &cbSigned, RTErrInfoInitStatic(&ErrInfo));
2438 if (RT_SUCCESS(rc))
2439 {
2440 if (cVerbosity > 2)
2441 RTMsgInfo("%s signature: %#zx bytes\n%.*Rhxd\n", pszWhat, cbSigned, cbSigned, pvSigned);
2442
2443 /*
2444 * Decode the signature and check that it is SignedData.
2445 */
2446 RTASN1CURSORPRIMARY PrimaryCursor;
2447 RTAsn1CursorInitPrimary(&PrimaryCursor, pvSigned, (uint32_t)cbSigned, RTErrInfoInitStatic(&ErrInfo),
2448 &g_RTAsn1DefaultAllocator, 0, pszWhat);
2449 rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, pContentInfo, "CI");
2450 if (RT_SUCCESS(rc))
2451 {
2452 if (RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
2453 {
2454#ifdef RT_OS_WINDOWS
2455 /*
2456 * If we're using a fake key+cert, we now have to re-do the signing using the real
2457 * key+cert and the windows crypto API. This kludge is necessary because we can't
2458 * typically get that the encoded private key, so it isn't possible to feed it to
2459 * openssl.
2460 */
2461 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2462 if (pCertKeyPair->pCertificateReal)
2463 rcExit = SignToolPkcs7_Pkcs7SignStuffAgainWithReal(pszWhat, pCertKeyPair, cVerbosity, pContentInfo,
2464 &pvSigned, &cbSigned);
2465 if (rcExit == RTEXITCODE_SUCCESS)
2466#endif
2467 {
2468 /*
2469 * Set returns and maybe display the result before returning.
2470 */
2471 *ppvSigned = pvSigned;
2472 if (pcbSigned)
2473 *pcbSigned = cbSigned;
2474 if (ppSignedData)
2475 *ppSignedData = pContentInfo->u.pSignedData;
2476
2477 if (cVerbosity)
2478 {
2479 SHOWEXEPKCS7 ShowExe;
2480 RT_ZERO(ShowExe);
2481 ShowExe.cVerbosity = cVerbosity;
2482 HandleShowExeWorkerPkcs7Display(&ShowExe, pContentInfo->u.pSignedData, 0, pContentInfo);
2483 }
2484 return RTEXITCODE_SUCCESS;
2485 }
2486 }
2487
2488 RTMsgError("(%s) RTCrPkcs7SimpleSignSignedData did not create SignedData: %s",
2489 pszWhat, pContentInfo->ContentType.szObjId);
2490 }
2491 else
2492 RTMsgError("(%s) RTCrPkcs7ContentInfo_DecodeAsn1 failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2493 RTCrPkcs7ContentInfo_Delete(pContentInfo);
2494 }
2495 RTMemFree(pvSigned);
2496 return RTEXITCODE_FAILURE;
2497}
2498
2499
2500static RTEXITCODE SignToolPkcs7_Pkcs7SignStuff(const char *pszWhat, const void *pvToDataToSign, size_t cbToDataToSign,
2501 PCRTCRPKCS7ATTRIBUTES pAuthAttribs, RTCRSTORE hAdditionalCerts,
2502 uint32_t fExtraFlags, RTDIGESTTYPE enmDigestType, SignToolKeyPair *pCertKeyPair,
2503 unsigned cVerbosity, void **ppvSigned, size_t *pcbSigned,
2504 PRTCRPKCS7CONTENTINFO pContentInfo, PRTCRPKCS7SIGNEDDATA *ppSignedData)
2505{
2506 /*
2507 * Gather all additional certificates before doing the actual work.
2508 */
2509 RTCRSTORE hAllAdditionalCerts = pCertKeyPair->assembleAllAdditionalCertificates(hAdditionalCerts);
2510 if (hAllAdditionalCerts == NIL_RTCRSTORE)
2511 return RTEXITCODE_FAILURE;
2512 RTEXITCODE rcExit = SignToolPkcs7_Pkcs7SignStuffInner(pszWhat, pvToDataToSign, cbToDataToSign, pAuthAttribs,
2513 hAllAdditionalCerts, fExtraFlags, enmDigestType, pCertKeyPair,
2514 cVerbosity, ppvSigned, pcbSigned, pContentInfo, ppSignedData);
2515 RTCrStoreRelease(hAllAdditionalCerts);
2516 return rcExit;
2517}
2518
2519
2520static RTEXITCODE SignToolPkcs7_AddTimestampSignatureEx(PRTCRPKCS7SIGNERINFO pSignerInfo, PRTCRPKCS7SIGNEDDATA pSignedData,
2521 unsigned cVerbosity, bool fReplaceExisting,
2522 RTTIMESPEC SigningTime, SignToolTimestampOpts *pTimestampOpts)
2523{
2524 AssertReturn(!pTimestampOpts->isNewType(), RTMsgErrorExitFailure("New style signatures not supported yet"));
2525
2526 /*
2527 * Create a set of attributes we need to include in the AuthenticatedAttributes
2528 * of the timestamp signature.
2529 */
2530 RTCRPKCS7ATTRIBUTES AuthAttribs;
2531 int rc = RTCrPkcs7Attributes_Init(&AuthAttribs, &g_RTAsn1DefaultAllocator);
2532 if (RT_FAILURE(rc))
2533 return RTMsgErrorExitFailure("RTCrPkcs7SetOfAttributes_Init failed: %Rrc", rc);
2534
2535 RTEXITCODE rcExit = SignToolPkcs7_AddAuthAttribsForTimestamp(&AuthAttribs, pTimestampOpts->m_enmType, SigningTime,
2536 pTimestampOpts->getRealCertificate());
2537 if (rcExit == RTEXITCODE_SUCCESS)
2538 {
2539 /*
2540 * Now create a PKCS#7 signature of the encrypted signature from the selected signer info.
2541 */
2542 void *pvSigned = NULL;
2543 PRTCRPKCS7SIGNEDDATA pTsSignedData = NULL;
2544 RTCRPKCS7CONTENTINFO TsContentInfo;
2545 rcExit = SignToolPkcs7_Pkcs7SignStuffInner("timestamp", pSignerInfo->EncryptedDigest.Asn1Core.uData.pv,
2546 pSignerInfo->EncryptedDigest.Asn1Core.cb, &AuthAttribs,
2547 NIL_RTCRSTORE /*hAdditionalCerts*/, RTCRPKCS7SIGN_SD_F_DEATCHED,
2548 RTDIGESTTYPE_SHA1, pTimestampOpts, cVerbosity,
2549 &pvSigned, NULL /*pcbSigned*/, &TsContentInfo, &pTsSignedData);
2550 if (rcExit == RTEXITCODE_SUCCESS)
2551 {
2552
2553 /*
2554 * If we're replacing existing timestamp signatures, remove old ones now.
2555 */
2556 if ( fReplaceExisting
2557 && RTCrPkcs7Attributes_IsPresent(&pSignerInfo->UnauthenticatedAttributes))
2558 {
2559 uint32_t iItem = pSignerInfo->UnauthenticatedAttributes.cItems;
2560 while (iItem-- > 0)
2561 {
2562 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iItem];
2563 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES) /* ASSUMES all counter sigs are timstamps */
2564 {
2565 if (cVerbosity > 1)
2566 RTMsgInfo("Removing counter signature in attribute #%u\n", iItem);
2567 rc = RTCrPkcs7Attributes_Erase(&pSignerInfo->UnauthenticatedAttributes, iItem);
2568 if (RT_FAILURE(rc))
2569 rcExit = RTMsgErrorExitFailure("RTCrPkcs7Attributes_Erase failed on #%u: %Rrc", iItem, rc);
2570 }
2571 }
2572 }
2573
2574 /*
2575 * Add the new one.
2576 */
2577 if (rcExit == RTEXITCODE_SUCCESS)
2578 rcExit = SignToolPkcs7_AppendCounterSignature(pSignerInfo, pTsSignedData->SignerInfos.papItems[0], cVerbosity);
2579
2580 /*
2581 * Make sure the signing certificate is included.
2582 */
2583 if (rcExit == RTEXITCODE_SUCCESS)
2584 {
2585 rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pTimestampOpts->getRealCertificate());
2586
2587 PCRTCRCERTCTX pInterCaCtx = NULL;
2588 while ((pInterCaCtx = pTimestampOpts->findNextIntermediateCert(pInterCaCtx)) != NULL)
2589 if (rcExit == RTEXITCODE_SUCCESS)
2590 rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pInterCaCtx->pCert);
2591 }
2592
2593 /*
2594 * Clean up.
2595 */
2596 RTCrPkcs7ContentInfo_Delete(&TsContentInfo);
2597 RTMemFree(pvSigned);
2598 }
2599 }
2600 RTCrPkcs7Attributes_Delete(&AuthAttribs);
2601 return rcExit;
2602}
2603
2604
2605static RTEXITCODE SignToolPkcs7_AddTimestampSignature(SIGNTOOLPKCS7EXE *pThis, unsigned cVerbosity, unsigned iSignature,
2606 bool fReplaceExisting, RTTIMESPEC SigningTime,
2607 SignToolTimestampOpts *pTimestampOpts)
2608{
2609 /*
2610 * Locate the signature specified by iSignature and add a timestamp to it.
2611 */
2612 PRTCRPKCS7SIGNEDDATA pSignedData = NULL;
2613 PRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(pThis, iSignature, &pSignedData);
2614 if (!pSignerInfo)
2615 return RTMsgErrorExitFailure("No signature #%u in %s", iSignature, pThis->pszFilename);
2616
2617 return SignToolPkcs7_AddTimestampSignatureEx(pSignerInfo, pSignedData, cVerbosity, fReplaceExisting,
2618 SigningTime, pTimestampOpts);
2619}
2620
2621
2622typedef enum SIGNDATATWEAK
2623{
2624 kSignDataTweak_NoTweak = 1,
2625 kSignDataTweak_RootIsParent
2626} SIGNDATATWEAK;
2627
2628static RTEXITCODE SignToolPkcs7_SignData(SIGNTOOLPKCS7 *pThis, PRTASN1CORE pToSignRoot, SIGNDATATWEAK enmTweak,
2629 const char *pszContentTypeId, unsigned cVerbosity, uint32_t fExtraFlags,
2630 RTDIGESTTYPE enmSigType, bool fReplaceExisting, bool fNoSigningTime,
2631 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
2632 RTTIMESPEC SigningTime, size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
2633{
2634 /*
2635 * Encode it.
2636 */
2637 RTERRINFOSTATIC ErrInfo;
2638 uint32_t cbEncoded = 0;
2639 int rc = RTAsn1EncodePrepare(pToSignRoot, RTASN1ENCODE_F_DER, &cbEncoded, RTErrInfoInitStatic(&ErrInfo));
2640 if (RT_FAILURE(rc))
2641 return RTMsgErrorExitFailure("RTAsn1EncodePrepare failed: %Rrc%RTeim", rc, &ErrInfo.Core);
2642
2643 if (cVerbosity >= 4)
2644 RTAsn1Dump(pToSignRoot, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
2645
2646 uint8_t *pbEncoded = (uint8_t *)RTMemTmpAllocZ(cbEncoded );
2647 if (!pbEncoded)
2648 return RTMsgErrorExitFailure("Failed to allocate %#z bytes for encoding data we're signing (%s)",
2649 cbEncoded, pszContentTypeId);
2650
2651 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
2652 rc = RTAsn1EncodeToBuffer(pToSignRoot, RTASN1ENCODE_F_DER, pbEncoded, cbEncoded, RTErrInfoInitStatic(&ErrInfo));
2653 if (RT_SUCCESS(rc))
2654 {
2655 size_t const cbToSign = cbEncoded - (enmTweak == kSignDataTweak_RootIsParent ? pToSignRoot->cbHdr : 0);
2656 void const *pvToSign = pbEncoded + (enmTweak == kSignDataTweak_RootIsParent ? pToSignRoot->cbHdr : 0);
2657
2658 /*
2659 * Create additional authenticated attributes.
2660 */
2661 RTCRPKCS7ATTRIBUTES AuthAttribs;
2662 rc = RTCrPkcs7Attributes_Init(&AuthAttribs, &g_RTAsn1DefaultAllocator);
2663 if (RT_SUCCESS(rc))
2664 {
2665 rcExit = SignToolPkcs7_AddAuthAttribsForImageOrCatSignature(&AuthAttribs, SigningTime, fNoSigningTime,
2666 pszContentTypeId);
2667 if (rcExit == RTEXITCODE_SUCCESS)
2668 {
2669 /*
2670 * Ditch the old signature if so desired.
2671 * (It is okay to do this in the CAT case too, as we've already
2672 * encoded the data and won't touch pToSignRoot any more.)
2673 */
2674 pToSignRoot = NULL; /* (may become invalid if replacing) */
2675 if (fReplaceExisting && pThis->pSignedData)
2676 {
2677 RTCrPkcs7ContentInfo_Delete(&pThis->ContentInfo);
2678 pThis->pSignedData = NULL;
2679 RTMemFree(pThis->pbBuf);
2680 pThis->pbBuf = NULL;
2681 pThis->cbBuf = 0;
2682 }
2683
2684 /*
2685 * Do the actual signing.
2686 */
2687 SIGNTOOLPKCS7 Src = { RTSIGNTOOLFILETYPE_DETECT, NULL, 0, NULL };
2688 PSIGNTOOLPKCS7 pSigDst = !pThis->pSignedData ? pThis : &Src;
2689 rcExit = SignToolPkcs7_Pkcs7SignStuff("image", pvToSign, cbToSign, &AuthAttribs, hAddCerts,
2690 fExtraFlags | RTCRPKCS7SIGN_SD_F_NO_DATA_ENCAP, enmSigType /** @todo ?? */,
2691 pSigningCertKey, cVerbosity,
2692 (void **)&pSigDst->pbBuf, &pSigDst->cbBuf,
2693 &pSigDst->ContentInfo, &pSigDst->pSignedData);
2694 if (rcExit == RTEXITCODE_SUCCESS)
2695 {
2696 /*
2697 * Add the requested timestamp signatures if requested.
2698 */
2699 for (size_t i = 0; rcExit == RTEXITCODE_SUCCESS &&i < cTimestampOpts; i++)
2700 if (paTimestampOpts[i].isComplete())
2701 rcExit = SignToolPkcs7_AddTimestampSignatureEx(pSigDst->pSignedData->SignerInfos.papItems[0],
2702 pSigDst->pSignedData,
2703 cVerbosity, false /*fReplaceExisting*/,
2704 SigningTime, &paTimestampOpts[i]);
2705
2706 /*
2707 * Append the signature to the existing one, if that's what we're doing.
2708 */
2709 if (rcExit == RTEXITCODE_SUCCESS && pSigDst == &Src)
2710 rcExit = SignToolPkcs7_AddNestedSignature(pThis, &Src, cVerbosity, true /*fPrepend*/); /** @todo prepend/append option */
2711
2712 /* cleanup */
2713 if (pSigDst == &Src)
2714 SignToolPkcs7_Delete(&Src);
2715 }
2716
2717 }
2718 RTCrPkcs7Attributes_Delete(&AuthAttribs);
2719 }
2720 else
2721 RTMsgError("RTCrPkcs7SetOfAttributes_Init failed: %Rrc", rc);
2722 }
2723 else
2724 RTMsgError("RTAsn1EncodeToBuffer failed: %Rrc", rc);
2725 RTMemTmpFree(pbEncoded);
2726 return rcExit;
2727}
2728
2729
2730static RTEXITCODE SignToolPkcs7_SpcCompleteWithoutPageHashes(RTCRSPCINDIRECTDATACONTENT *pSpcIndData)
2731{
2732 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2733 PRTCRSPCPEIMAGEDATA const pPeImage = pSpcIndData->Data.uValue.pPeImage;
2734 Assert(pPeImage);
2735
2736 /*
2737 * Set it to File with an empty name.
2738 * RTCRSPCPEIMAGEDATA::Flags -vv
2739 * RTCRSPCPEIMAGEDATA::SeqCore -vv T0 -vv vv- pT2/CtxTag2
2740 * 0040: 04 01 82 37 02 01 0f 30-09 03 01 00 a0 04 a2 02 ...7...0........
2741 * 0050: 80 00 30 21 30 09 06 05-2b 0e 03 02 1a 05 00 04 ..0!0...+.......
2742 * ^^- pUcs2 / empty string
2743 */
2744
2745 /* Create an empty BMP string. */
2746 RTASN1STRING EmptyStr;
2747 int rc = RTAsn1BmpString_Init(&EmptyStr, pAllocator);
2748 if (RT_FAILURE(rc))
2749 return RTMsgErrorExitFailure("RTAsn1BmpString_Init/Ucs2 failed: %Rrc", rc);
2750
2751 /* Create an SPC string and use the above empty string with the Ucs2 setter. */
2752 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
2753 RTCRSPCSTRING SpcString;
2754 rc = RTCrSpcString_Init(&SpcString, pAllocator);
2755 if (RT_SUCCESS(rc))
2756 {
2757 rc = RTCrSpcString_SetUcs2(&SpcString, &EmptyStr, pAllocator);
2758 if (RT_SUCCESS(rc))
2759 {
2760 /* Create a temporary SpcLink with the empty SpcString. */
2761 RTCRSPCLINK SpcLink;
2762 rc = RTCrSpcLink_Init(&SpcLink, pAllocator);
2763 if (RT_SUCCESS(rc))
2764 {
2765 /* Use the setter on the SpcLink object to copy the SpcString to it. */
2766 rc = RTCrSpcLink_SetFile(&SpcLink, &SpcString, pAllocator);
2767 if (RT_SUCCESS(rc))
2768 {
2769 /* Use the setter to copy SpcLink to the PeImage structure. */
2770 rc = RTCrSpcPeImageData_SetFile(pPeImage, &SpcLink, pAllocator);
2771 if (RT_SUCCESS(rc))
2772 rcExit = RTEXITCODE_SUCCESS;
2773 else
2774 RTMsgError("RTCrSpcPeImageData_SetFile failed: %Rrc", rc);
2775 }
2776 else
2777 RTMsgError("RTCrSpcLink_SetFile failed: %Rrc", rc);
2778 RTCrSpcLink_Delete(&SpcLink);
2779 }
2780 else
2781 RTMsgError("RTCrSpcLink_Init failed: %Rrc", rc);
2782 }
2783 else
2784 RTMsgError("RTCrSpcString_SetUcs2 failed: %Rrc", rc);
2785 RTCrSpcString_Delete(&SpcString);
2786 }
2787 else
2788 RTMsgError("RTCrSpcString_Init failed: %Rrc", rc);
2789 RTAsn1BmpString_Delete(&EmptyStr);
2790 return rcExit;
2791}
2792
2793
2794static RTEXITCODE SignToolPkcs7_SpcAddImagePageHashes(SIGNTOOLPKCS7EXE *pThis, RTCRSPCINDIRECTDATACONTENT *pSpcIndData,
2795 RTDIGESTTYPE enmSigType)
2796{
2797 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2798 PRTCRSPCPEIMAGEDATA const pPeImage = pSpcIndData->Data.uValue.pPeImage;
2799 Assert(pPeImage);
2800
2801 /*
2802 * The hashes are stored in the 'Moniker' attribute.
2803 */
2804 /* Create a temporary SpcLink with a default moniker. */
2805 RTCRSPCLINK SpcLink;
2806 int rc = RTCrSpcLink_Init(&SpcLink, pAllocator);
2807 if (RT_FAILURE(rc))
2808 return RTMsgErrorExitFailure("RTCrSpcLink_Init failed: %Rrc", rc);
2809 rc = RTCrSpcLink_SetMoniker(&SpcLink, NULL, pAllocator);
2810 if (RT_SUCCESS(rc))
2811 {
2812 /* Use the setter to copy SpcLink to the PeImage structure. */
2813 rc = RTCrSpcPeImageData_SetFile(pPeImage, &SpcLink, pAllocator);
2814 if (RT_FAILURE(rc))
2815 RTMsgError("RTCrSpcLink_SetFile failed: %Rrc", rc);
2816 }
2817 else
2818 RTMsgError("RTCrSpcLink_SetMoniker failed: %Rrc", rc);
2819 RTCrSpcLink_Delete(&SpcLink);
2820 if (RT_FAILURE(rc))
2821 return RTEXITCODE_FAILURE;
2822
2823 /*
2824 * Now go to work on the moniker. It doesn't have any autogenerated
2825 * setters, so we must do stuff manually.
2826 */
2827 PRTCRSPCSERIALIZEDOBJECT pMoniker = pPeImage->T0.File.u.pMoniker;
2828 RTUUID Uuid;
2829 rc = RTUuidFromStr(&Uuid, RTCRSPCSERIALIZEDOBJECT_UUID_STR);
2830 if (RT_FAILURE(rc))
2831 return RTMsgErrorExitFailure("RTUuidFromStr failed: %Rrc", rc);
2832
2833 rc = RTAsn1OctetString_AllocContent(&pMoniker->Uuid, &Uuid, sizeof(Uuid), pAllocator);
2834 if (RT_FAILURE(rc))
2835 return RTMsgErrorExitFailure("RTAsn1String_InitWithValue/UUID failed: %Rrc", rc);
2836
2837 /* Create a new set of attributes and associate this with the SerializedData member. */
2838 PRTCRSPCSERIALIZEDOBJECTATTRIBUTES pSpcAttribs;
2839 rc = RTAsn1MemAllocZ(&pMoniker->SerializedData.EncapsulatedAllocation,
2840 (void **)&pSpcAttribs, sizeof(*pSpcAttribs));
2841 if (RT_FAILURE(rc))
2842 return RTMsgErrorExitFailure("RTAsn1MemAllocZ/pSpcAttribs failed: %Rrc", rc);
2843 pMoniker->SerializedData.pEncapsulated = RTCrSpcSerializedObjectAttributes_GetAsn1Core(pSpcAttribs);
2844 pMoniker->enmType = RTCRSPCSERIALIZEDOBJECTTYPE_ATTRIBUTES;
2845 pMoniker->u.pData = pSpcAttribs;
2846
2847 rc = RTCrSpcSerializedObjectAttributes_Init(pSpcAttribs, pAllocator);
2848 if (RT_FAILURE(rc))
2849 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttributes_Init failed: %Rrc", rc);
2850
2851 /*
2852 * Add a single attribute to the set that we'll use for page hashes.
2853 */
2854 int32_t iPos = RTCrSpcSerializedObjectAttributes_Append(pSpcAttribs);
2855 if (iPos < 0)
2856 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttributes_Append failed: %Rrc", iPos);
2857 PRTCRSPCSERIALIZEDOBJECTATTRIBUTE pSpcObjAttr = pSpcAttribs->papItems[iPos];
2858
2859 if (enmSigType == RTDIGESTTYPE_SHA1)
2860 rc = RTCrSpcSerializedObjectAttribute_SetV1Hashes(pSpcObjAttr, NULL, pAllocator);
2861 else if (enmSigType == RTDIGESTTYPE_SHA256)
2862 rc = RTCrSpcSerializedObjectAttribute_SetV2Hashes(pSpcObjAttr, NULL, pAllocator);
2863 else
2864 rc = VERR_CR_DIGEST_NOT_SUPPORTED;
2865 if (RT_FAILURE(rc))
2866 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttribute_SetV1Hashes/SetV2Hashes failed: %Rrc", rc);
2867 PRTCRSPCSERIALIZEDPAGEHASHES pSpcPageHashes = pSpcObjAttr->u.pPageHashes;
2868 Assert(pSpcPageHashes);
2869
2870 /*
2871 * Now ask the loader for the number of pages in the page hash table
2872 * and calculate its size.
2873 */
2874 uint32_t cPages = 0;
2875 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_HASHABLE_PAGES, NULL, &cPages, sizeof(cPages), NULL);
2876 if (RT_FAILURE(rc))
2877 return RTMsgErrorExitFailure("RTLdrQueryPropEx/RTLDRPROP_HASHABLE_PAGES failed: %Rrc", rc);
2878
2879 uint32_t const cbHash = RTCrDigestTypeToHashSize(enmSigType);
2880 AssertReturn(cbHash > 0, RTMsgErrorExitFailure("Invalid value: enmSigType=%d", enmSigType));
2881 uint32_t const cbTable = (sizeof(uint32_t) + cbHash) * cPages;
2882
2883 /*
2884 * Allocate memory in the octect string.
2885 */
2886 rc = RTAsn1ContentAllocZ(&pSpcPageHashes->RawData.Asn1Core, cbTable, pAllocator);
2887 if (RT_FAILURE(rc))
2888 return RTMsgErrorExitFailure("RTAsn1ContentAllocZ failed to allocate %#x bytes for page hashes: %Rrc", cbTable, rc);
2889 pSpcPageHashes->pData = (PCRTCRSPCPEIMAGEPAGEHASHES)pSpcPageHashes->RawData.Asn1Core.uData.pu8;
2890
2891 RTLDRPROP enmLdrProp;
2892 switch (enmSigType)
2893 {
2894 case RTDIGESTTYPE_SHA1: enmLdrProp = RTLDRPROP_SHA1_PAGE_HASHES; break;
2895 case RTDIGESTTYPE_SHA256: enmLdrProp = RTLDRPROP_SHA256_PAGE_HASHES; break;
2896 default: AssertFailedReturn(RTMsgErrorExitFailure("Invalid value: enmSigType=%d", enmSigType));
2897
2898 }
2899 rc = RTLdrQueryPropEx(pThis->hLdrMod, enmLdrProp, NULL, (void *)pSpcPageHashes->RawData.Asn1Core.uData.pv, cbTable, NULL);
2900 if (RT_FAILURE(rc))
2901 return RTMsgErrorExitFailure("RTLdrQueryPropEx/RTLDRPROP_SHA?_PAGE_HASHES/%#x failed: %Rrc", cbTable, rc);
2902
2903 return RTEXITCODE_SUCCESS;
2904}
2905
2906
2907static RTEXITCODE SignToolPkcs7_SpcAddImageHash(SIGNTOOLPKCS7EXE *pThis, RTCRSPCINDIRECTDATACONTENT *pSpcIndData,
2908 RTDIGESTTYPE enmSigType)
2909{
2910 uint32_t const cbHash = RTCrDigestTypeToHashSize(enmSigType);
2911 const char * const pszAlgId = RTCrDigestTypeToAlgorithmOid(enmSigType);
2912
2913 /*
2914 * Ask the loader for the hash.
2915 */
2916 uint8_t abHash[RTSHA512_HASH_SIZE];
2917 int rc = RTLdrHashImage(pThis->hLdrMod, enmSigType, abHash, sizeof(abHash));
2918 if (RT_FAILURE(rc))
2919 return RTMsgErrorExitFailure("RTLdrHashImage/%s failed: %Rrc", RTCrDigestTypeToName(enmSigType), rc);
2920
2921 /*
2922 * Set it.
2923 */
2924 /** @todo no setter, this should be okay, though... */
2925 rc = RTAsn1ObjId_InitFromString(&pSpcIndData->DigestInfo.DigestAlgorithm.Algorithm, pszAlgId, &g_RTAsn1DefaultAllocator);
2926 if (RT_FAILURE(rc))
2927 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszAlgId, rc);
2928 RTAsn1DynType_SetToNull(&pSpcIndData->DigestInfo.DigestAlgorithm.Parameters); /* ASSUMES RSA or similar */
2929
2930 rc = RTAsn1ContentDup(&pSpcIndData->DigestInfo.Digest.Asn1Core, abHash, cbHash, &g_RTAsn1DefaultAllocator);
2931 if (RT_FAILURE(rc))
2932 return RTMsgErrorExitFailure("RTAsn1ContentDup/%#x failed: %Rrc", cbHash, rc);
2933
2934 return RTEXITCODE_SUCCESS;
2935}
2936
2937
2938static RTEXITCODE SignToolPkcs7_AddOrReplaceSignature(SIGNTOOLPKCS7EXE *pThis, unsigned cVerbosity, RTDIGESTTYPE enmSigType,
2939 bool fReplaceExisting, bool fHashPages, bool fNoSigningTime,
2940 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
2941 RTTIMESPEC SigningTime,
2942 size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
2943{
2944 /*
2945 * We must construct the data to be packed into the PKCS#7 signature
2946 * and signed.
2947 */
2948 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2949 RTCRSPCINDIRECTDATACONTENT SpcIndData;
2950 int rc = RTCrSpcIndirectDataContent_Init(&SpcIndData, pAllocator);
2951 if (RT_FAILURE(rc))
2952 return RTMsgErrorExitFailure("RTCrSpcIndirectDataContent_Init failed: %Rrc", rc);
2953
2954 /* Set the data to PE image. */
2955 /** @todo Generalize the Type + enmType DYN stuff and generate setters. */
2956 Assert(SpcIndData.Data.enmType == RTCRSPCAAOVTYPE_NOT_PRESENT);
2957 Assert(SpcIndData.Data.uValue.pPeImage == NULL);
2958 RTEXITCODE rcExit;
2959 rc = RTAsn1ObjId_SetFromString(&SpcIndData.Data.Type, RTCRSPCPEIMAGEDATA_OID, pAllocator);
2960 if (RT_SUCCESS(rc))
2961 {
2962 SpcIndData.Data.enmType = RTCRSPCAAOVTYPE_PE_IMAGE_DATA;
2963 rc = RTAsn1MemAllocZ(&SpcIndData.Data.Allocation, (void **)&SpcIndData.Data.uValue.pPeImage,
2964 sizeof(*SpcIndData.Data.uValue.pPeImage));
2965 if (RT_SUCCESS(rc))
2966 {
2967 rc = RTCrSpcPeImageData_Init(SpcIndData.Data.uValue.pPeImage, pAllocator);
2968 if (RT_SUCCESS(rc))
2969 {
2970 /* Old (SHA1) signatures has a Flags member, it's zero bits, though. */
2971 if (enmSigType == RTDIGESTTYPE_SHA1)
2972 {
2973 uint8_t bFlags = 0;
2974 RTASN1BITSTRING Flags;
2975 rc = RTAsn1BitString_InitWithData(&Flags, &bFlags, 0, pAllocator);
2976 if (RT_SUCCESS(rc))
2977 {
2978 rc = RTCrSpcPeImageData_SetFlags(SpcIndData.Data.uValue.pPeImage, &Flags, pAllocator);
2979 RTAsn1BitString_Delete(&Flags);
2980 if (RT_FAILURE(rc))
2981 rcExit = RTMsgErrorExitFailure("RTCrSpcPeImageData_SetFlags failed: %Rrc", rc);
2982 }
2983 else
2984 rcExit = RTMsgErrorExitFailure("RTAsn1BitString_InitWithData failed: %Rrc", rc);
2985 }
2986
2987 /*
2988 * Add the hashes.
2989 */
2990 rcExit = SignToolPkcs7_SpcAddImageHash(pThis, &SpcIndData, enmSigType);
2991 if (rcExit == RTEXITCODE_SUCCESS)
2992 {
2993 if (fHashPages)
2994 rcExit = SignToolPkcs7_SpcAddImagePageHashes(pThis, &SpcIndData, enmSigType);
2995 else
2996 rcExit = SignToolPkcs7_SpcCompleteWithoutPageHashes(&SpcIndData);
2997
2998 /*
2999 * Encode and sign the SPC data, timestamp it, and line it up for adding to the executable.
3000 */
3001 if (rcExit == RTEXITCODE_SUCCESS)
3002 rcExit = SignToolPkcs7_SignData(pThis, RTCrSpcIndirectDataContent_GetAsn1Core(&SpcIndData),
3003 kSignDataTweak_NoTweak, RTCRSPCINDIRECTDATACONTENT_OID, cVerbosity, 0,
3004 enmSigType, fReplaceExisting, fNoSigningTime, pSigningCertKey, hAddCerts,
3005 SigningTime, cTimestampOpts, paTimestampOpts);
3006 }
3007 }
3008 else
3009 rcExit = RTMsgErrorExitFailure("RTCrPkcs7SignerInfos_Init failed: %Rrc", rc);
3010 }
3011 else
3012 rcExit = RTMsgErrorExitFailure("RTAsn1MemAllocZ failed for RTCRSPCPEIMAGEDATA: %Rrc", rc);
3013 }
3014 else
3015 rcExit = RTMsgErrorExitFailure("RTAsn1ObjId_SetWithString/SpcPeImageData failed: %Rrc", rc);
3016
3017 RTCrSpcIndirectDataContent_Delete(&SpcIndData);
3018 return rcExit;
3019}
3020
3021
3022static RTEXITCODE SignToolPkcs7_AddOrReplaceCatSignature(SIGNTOOLPKCS7 *pThis, unsigned cVerbosity, RTDIGESTTYPE enmSigType,
3023 bool fReplaceExisting, bool fNoSigningTime,
3024 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
3025 RTTIMESPEC SigningTime,
3026 size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
3027{
3028 AssertReturn(pThis->pSignedData, RTMsgErrorExitFailure("pSignedData is NULL!"));
3029
3030 /*
3031 * Figure out what to sign first.
3032 */
3033 uint32_t fExtraFlags = 0;
3034 PRTASN1CORE pToSign = &pThis->pSignedData->ContentInfo.Content.Asn1Core;
3035 const char *pszType = pThis->pSignedData->ContentInfo.ContentType.szObjId;
3036
3037 if (!fReplaceExisting && pThis->pSignedData->SignerInfos.cItems == 0)
3038 fReplaceExisting = true;
3039 if (!fReplaceExisting)
3040 {
3041 pszType = RTCR_PKCS7_DATA_OID;
3042 fExtraFlags |= RTCRPKCS7SIGN_SD_F_DEATCHED;
3043 }
3044
3045 /*
3046 * Do the signing.
3047 */
3048 RTEXITCODE rcExit = SignToolPkcs7_SignData(pThis, pToSign, kSignDataTweak_RootIsParent,
3049 pszType, cVerbosity, fExtraFlags, enmSigType, fReplaceExisting,
3050 fNoSigningTime, pSigningCertKey, hAddCerts,
3051 SigningTime, cTimestampOpts, paTimestampOpts);
3052
3053 /* probably need to clean up stuff related to nested signatures here later... */
3054 return rcExit;
3055}
3056
3057#endif /* !IPRT_SIGNTOOL_NO_SIGNING */
3058
3059
3060/*********************************************************************************************************************************
3061* Option handlers shared by 'sign-exe', 'sign-cat', 'add-timestamp-exe-signature' and others. *
3062*********************************************************************************************************************************/
3063#ifndef IPRT_SIGNTOOL_NO_SIGNING
3064
3065static RTEXITCODE HandleOptAddCert(PRTCRSTORE phStore, const char *pszFile)
3066{
3067 if (*phStore == NIL_RTCRSTORE)
3068 {
3069 int rc = RTCrStoreCreateInMem(phStore, 2);
3070 if (RT_FAILURE(rc))
3071 return RTMsgErrorExitFailure("RTCrStoreCreateInMem(,2) failed: %Rrc", rc);
3072 }
3073 RTERRINFOSTATIC ErrInfo;
3074 int rc = RTCrStoreCertAddFromFile(*phStore, RTCRCERTCTX_F_ADD_IF_NOT_FOUND, pszFile, RTErrInfoInitStatic(&ErrInfo));
3075 if (RT_FAILURE(rc))
3076 return RTMsgErrorExitFailure("Error reading certificate from '%s': %Rrc%#RTeim", pszFile, rc, &ErrInfo.Core);
3077 return RTEXITCODE_SUCCESS;
3078}
3079
3080static RTEXITCODE HandleOptSignatureType(RTDIGESTTYPE *penmSigType, const char *pszType)
3081{
3082 if ( RTStrICmpAscii(pszType, "sha1") == 0
3083 || RTStrICmpAscii(pszType, "sha-1") == 0)
3084 *penmSigType = RTDIGESTTYPE_SHA1;
3085 else if ( RTStrICmpAscii(pszType, "sha256") == 0
3086 || RTStrICmpAscii(pszType, "sha-256") == 0)
3087 *penmSigType = RTDIGESTTYPE_SHA256;
3088 else
3089 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signature type: %s (expected sha1 or sha256)", pszType);
3090 return RTEXITCODE_SUCCESS;
3091}
3092
3093
3094static RTEXITCODE HandleOptTimestampType(SignToolTimestampOpts *pTimestampOpts, const char *pszType)
3095{
3096 if (strcmp(pszType, "old") == 0)
3097 pTimestampOpts->m_enmType = kTimestampType_Old;
3098 else if (strcmp(pszType, "new") == 0)
3099 pTimestampOpts->m_enmType = kTimestampType_New;
3100 else
3101 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown timestamp type: %s", pszType);
3102 return RTEXITCODE_SUCCESS;
3103}
3104
3105static RTEXITCODE HandleOptTimestampOverride(PRTTIMESPEC pSigningTime, const char *pszPartialTs)
3106{
3107 /*
3108 * First try use it as-is.
3109 */
3110 if (RTTimeSpecFromString(pSigningTime, pszPartialTs) != NULL)
3111 return RTEXITCODE_SUCCESS;
3112
3113 /* Check the input against a pattern, making sure we've got something that
3114 makes sense before trying to merge. */
3115 size_t const cchPartialTs = strlen(pszPartialTs);
3116 static char s_szPattern[] = "0000-00-00T00:00:";
3117 if (cchPartialTs > sizeof(s_szPattern) - 1) /* It is not a partial timestamp if we've got the seconds component. */
3118 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp: %s", pszPartialTs);
3119
3120 for (size_t off = 0; off < cchPartialTs; off++)
3121 switch (s_szPattern[off])
3122 {
3123 case '0':
3124 if (!RT_C_IS_DIGIT(pszPartialTs[off]))
3125 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected digit at position %u: %s",
3126 off + 1, pszPartialTs);
3127 break;
3128 case '-':
3129 case ':':
3130 if (pszPartialTs[off] != s_szPattern[off])
3131 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected '%c' at position %u: %s",
3132 s_szPattern[off], off + 1, pszPartialTs);
3133 break;
3134 case 'T':
3135 if ( pszPartialTs[off] != 'T'
3136 && pszPartialTs[off] != 't'
3137 && pszPartialTs[off] != ' ')
3138 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected 'T' or space at position %u: %s",
3139 off + 1, pszPartialTs);
3140 break;
3141 default:
3142 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Internal error");
3143 }
3144
3145 if (RT_C_IS_DIGIT(s_szPattern[cchPartialTs]) && RT_C_IS_DIGIT(s_szPattern[cchPartialTs - 1]))
3146 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Incomplete timstamp component: %s", pszPartialTs);
3147
3148 /*
3149 * Take the current time and merge in the components from pszPartialTs.
3150 */
3151 char szSigningTime[RTTIME_STR_LEN];
3152 RTTIMESPEC Now;
3153 RTTimeSpecToString(RTTimeNow(&Now), szSigningTime, sizeof(szSigningTime));
3154 memcpy(szSigningTime, pszPartialTs, cchPartialTs);
3155 szSigningTime[4+1+2+1+2] = 'T';
3156
3157 /* Fix 29th for non-leap override: */
3158 if (memcmp(&szSigningTime[5], RT_STR_TUPLE("02-29")) == 0)
3159 {
3160 if (!RTTimeIsLeapYear(RTStrToUInt32(szSigningTime)))
3161 szSigningTime[9] = '8';
3162 }
3163 if (RTTimeSpecFromString(pSigningTime, szSigningTime) == NULL)
3164 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp: %s (%s)", pszPartialTs, szSigningTime);
3165
3166 return RTEXITCODE_SUCCESS;
3167}
3168
3169static RTEXITCODE HandleOptFileType(RTSIGNTOOLFILETYPE *penmFileType, const char *pszType)
3170{
3171 if (strcmp(pszType, "detect") == 0 || strcmp(pszType, "auto") == 0)
3172 *penmFileType = RTSIGNTOOLFILETYPE_DETECT;
3173 else if (strcmp(pszType, "exe") == 0)
3174 *penmFileType = RTSIGNTOOLFILETYPE_EXE;
3175 else if (strcmp(pszType, "cat") == 0)
3176 *penmFileType = RTSIGNTOOLFILETYPE_CAT;
3177 else
3178 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown forced file type: %s", pszType);
3179 return RTEXITCODE_SUCCESS;
3180}
3181
3182#endif /* !IPRT_SIGNTOOL_NO_SIGNING */
3183
3184/**
3185 * Detects the type of files @a pszFile is (by reading from it).
3186 *
3187 * @returns The file type, or RTSIGNTOOLFILETYPE_UNKNOWN (error displayed).
3188 * @param enmForceFileType Usually set to RTSIGNTOOLFILETYPE_DETECT, but if
3189 * not we'll return this without probing the file.
3190 * @param pszFile The name of the file to detect the type of.
3191 */
3192static RTSIGNTOOLFILETYPE DetectFileType(RTSIGNTOOLFILETYPE enmForceFileType, const char *pszFile)
3193{
3194 /*
3195 * Forced?
3196 */
3197 if (enmForceFileType != RTSIGNTOOLFILETYPE_DETECT)
3198 return enmForceFileType;
3199
3200 /*
3201 * Read the start of the file.
3202 */
3203 RTFILE hFile = NIL_RTFILE;
3204 int rc = RTFileOpen(&hFile, pszFile, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
3205 if (RT_FAILURE(rc))
3206 {
3207 RTMsgError("Error opening '%s' for reading: %Rrc", pszFile, rc);
3208 return RTSIGNTOOLFILETYPE_UNKNOWN;
3209 }
3210
3211 union
3212 {
3213 uint8_t ab[256];
3214 uint16_t au16[256/2];
3215 uint32_t au32[256/4];
3216 } uBuf;
3217 RT_ZERO(uBuf);
3218
3219 size_t cbRead = 0;
3220 rc = RTFileRead(hFile, &uBuf, sizeof(uBuf), &cbRead);
3221 if (RT_FAILURE(rc))
3222 RTMsgError("Error reading from '%s': %Rrc", pszFile, rc);
3223
3224 uint64_t cbFile;
3225 int rcSize = RTFileQuerySize(hFile, &cbFile);
3226 if (RT_FAILURE(rcSize))
3227 RTMsgError("Error querying size of '%s': %Rrc", pszFile, rc);
3228
3229 RTFileClose(hFile);
3230 if (RT_FAILURE(rc) || RT_FAILURE(rcSize))
3231 return RTSIGNTOOLFILETYPE_UNKNOWN;
3232
3233 /*
3234 * Try guess the kind of file.
3235 */
3236 /* All the executable magics we know: */
3237 if ( uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_DOS_SIGNATURE)
3238 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_NE_SIGNATURE)
3239 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_LX_SIGNATURE)
3240 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_LE_SIGNATURE)
3241 || uBuf.au32[0] == RT_H2LE_U32_C(IMAGE_NT_SIGNATURE)
3242 || uBuf.au32[0] == RT_H2LE_U32_C(IMAGE_ELF_SIGNATURE)
3243 || uBuf.au32[0] == IMAGE_FAT_SIGNATURE
3244 || uBuf.au32[0] == IMAGE_FAT_SIGNATURE_OE
3245 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE
3246 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE_OE
3247 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE
3248 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE_OE)
3249 return RTSIGNTOOLFILETYPE_EXE;
3250
3251 /*
3252 * Catalog files are PKCS#7 SignedData and starts with a ContentInfo, i.e.:
3253 * SEQUENCE {
3254 * contentType OBJECT IDENTIFIER,
3255 * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
3256 * }
3257 *
3258 * We ASSUME that it's DER encoded and doesn't use an indefinite length form
3259 * at the start and that contentType is signedData (1.2.840.113549.1.7.2).
3260 *
3261 * Example of a 10353 (0x2871) byte long file:
3262 * vv-------- contentType -------vv
3263 * 00000000 30 82 28 6D 06 09 2A 86 48 86 F7 0D 01 07 02 A0
3264 * 00000010 82 28 5E 30 82 28 5A 02 01 01 31 0B 30 09 06 05
3265 */
3266 if ( uBuf.ab[0] == (ASN1_TAG_SEQUENCE | ASN1_TAGFLAG_CONSTRUCTED)
3267 && uBuf.ab[1] != 0x80 /* not indefinite form */
3268 && uBuf.ab[1] > 0x30)
3269 {
3270 size_t off = 1;
3271 uint32_t cbRec = uBuf.ab[1];
3272 if (cbRec & 0x80)
3273 {
3274 cbRec &= 0x7f;
3275 off += cbRec;
3276 switch (cbRec)
3277 {
3278 case 1: cbRec = uBuf.ab[2]; break;
3279 case 2: cbRec = RT_MAKE_U16( uBuf.ab[3], uBuf.ab[2]); break;
3280 case 3: cbRec = RT_MAKE_U32_FROM_U8(uBuf.ab[4], uBuf.ab[3], uBuf.ab[2], 0); break;
3281 case 4: cbRec = RT_MAKE_U32_FROM_U8(uBuf.ab[5], uBuf.ab[4], uBuf.ab[3], uBuf.ab[2]); break;
3282 default: cbRec = UINT32_MAX; break;
3283 }
3284 }
3285 if (off <= 5)
3286 {
3287 off++;
3288 if (off + cbRec == cbFile)
3289 {
3290 /* If the contentType is signedData we're going to treat it as a catalog file,
3291 we don't currently much care about the signed content of a cat file. */
3292 static const uint8_t s_abSignedDataOid[] =
3293 { ASN1_TAG_OID, 9 /*length*/, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
3294 if (memcmp(&uBuf.ab[off], s_abSignedDataOid, sizeof(s_abSignedDataOid)) == 0)
3295 return RTSIGNTOOLFILETYPE_CAT;
3296 }
3297 }
3298 }
3299
3300 RTMsgError("Unable to detect type of '%s'", pszFile);
3301 return RTSIGNTOOLFILETYPE_UNKNOWN;
3302}
3303
3304
3305/*********************************************************************************************************************************
3306* The 'extract-exe-signer-cert' command. *
3307*********************************************************************************************************************************/
3308
3309static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
3310{
3311 RT_NOREF_PV(enmLevel);
3312 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
3313 "extract-exe-signer-cert [--as-c-array=name|--ber|--cer|--der] [--signature-index|-i <num>] [--input|--exe|-e] <exe> [--output|-o] <outfile.cer/h>\n");
3314 return RTEXITCODE_SUCCESS;
3315}
3316
3317static RTEXITCODE WriteCertToFile(PCRTCRX509CERTIFICATE pCert, const char *pszFilename, bool fForce)
3318{
3319 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
3320 RTFILE hFile;
3321 int rc = RTFileOpen(&hFile, pszFilename,
3322 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | (fForce ? RTFILE_O_CREATE_REPLACE : RTFILE_O_CREATE));
3323 if (RT_SUCCESS(rc))
3324 {
3325 uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
3326 rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
3327 cbCert, NULL);
3328 if (RT_SUCCESS(rc))
3329 {
3330 rc = RTFileClose(hFile);
3331 if (RT_SUCCESS(rc))
3332 {
3333 hFile = NIL_RTFILE;
3334 rcExit = RTEXITCODE_SUCCESS;
3335 RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszFilename);
3336 }
3337 else
3338 RTMsgError("RTFileClose failed: %Rrc", rc);
3339 }
3340 else
3341 RTMsgError("RTFileWrite failed: %Rrc", rc);
3342 RTFileClose(hFile);
3343 }
3344 else
3345 RTMsgError("Error opening '%s' for writing: %Rrc", pszFilename, rc);
3346 return rcExit;
3347}
3348
3349
3350static void PrintCertAsCArray(PCRTCRX509CERTIFICATE pCert, uint32_t iSignature, const char *pszBaseNm, PRTSTREAM pStrm)
3351{
3352 uint32_t const cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
3353 uint8_t const * const pbCert = pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr;
3354 if (iSignature == UINT32_MAX)
3355 RTStrmPrintf(pStrm,
3356 "uint32_t const g_cb%s = %u;\n"
3357 "uint8_t const g_ab%s[%u] =\n"
3358 "{",
3359 pszBaseNm, cbCert, pszBaseNm, cbCert);
3360 else
3361 RTStrmPrintf(pStrm, "static uint8_t const g_ab%sCert%u[%u] =\n{", pszBaseNm, iSignature, cbCert);
3362 for (uint32_t off = 0; off < cbCert; off++)
3363 {
3364 if (off % 16 == 0)
3365 RTStrmPrintf(pStrm, "\n ");
3366 RTStrmPrintf(pStrm, " %#04x,", pbCert[off]);
3367 }
3368 RTStrmPrintf(pStrm, "\n};\n\n");
3369}
3370
3371
3372static void PrintCertTableAsC(uint32_t cSignatures, const char *pszBaseNm, PRTSTREAM pStrm)
3373{
3374 RTStrmPrintf(pStrm,
3375 "uint32_t const g_c%s = %u;\n"
3376 "struct { uint8_t const *pbCert; size_t cbCert; } const g_a%s[%u] =\n"
3377 "{\n"
3378 , pszBaseNm, cSignatures, pszBaseNm, cSignatures ? cSignatures : 1);
3379 for (uint32_t iSignature = 0; iSignature < cSignatures; iSignature++)
3380 RTStrmPrintf(pStrm, " { g_ab%sCert%u, sizeof(g_ab%sCert%u) },\n",
3381 pszBaseNm, iSignature, pszBaseNm, iSignature);
3382 if (!cSignatures)
3383 RTStrmPrintf(pStrm, " { NULL, 0 } /* dummy */ \n");
3384 RTStrmPrintf(pStrm, "};\n");
3385}
3386
3387
3388static RTEXITCODE WriteCertToFileAsC(PCRTCRX509CERTIFICATE pCert, const char *pszFilename, bool fForce, const char *pszBaseNm)
3389{
3390 RTEXITCODE rcExit;
3391 PRTSTREAM pStrm = NULL;
3392 int rc = RTStrmOpen(pszFilename, fForce ? "wt+" : "wtx", &pStrm);
3393 if (RT_SUCCESS(rc))
3394 {
3395 PrintCertAsCArray(pCert, UINT32_MAX, pszBaseNm, pStrm);
3396 rc = RTStrmClose(pStrm);
3397 if (RT_SUCCESS(rc))
3398 rcExit = RTEXITCODE_SUCCESS;
3399 else
3400 rcExit = RTMsgErrorExitFailure("Error writing/closing '%s': %Rrc", pszFilename, rc);
3401 }
3402 else
3403 rcExit = RTMsgErrorExitFailure("Failed to open '%s' for writing: %Rrc", pszFilename, rc);
3404 return rcExit;
3405}
3406
3407
3408
3409static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
3410{
3411 /*
3412 * Parse arguments.
3413 */
3414 static const RTGETOPTDEF s_aOptions[] =
3415 {
3416 { "--ber", 'b', RTGETOPT_REQ_NOTHING },
3417 { "--cer", 'c', RTGETOPT_REQ_NOTHING },
3418 { "--der", 'd', RTGETOPT_REQ_NOTHING },
3419 { "--exe", 'e', RTGETOPT_REQ_STRING },
3420 { "--input", 'e', RTGETOPT_REQ_STRING },
3421 { "--output", 'o', RTGETOPT_REQ_STRING },
3422 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
3423 { "--force", 'f', RTGETOPT_REQ_NOTHING },
3424 { "--as-c-array", 'C', RTGETOPT_REQ_STRING },
3425 };
3426
3427 const char *pszExe = NULL;
3428 const char *pszOut = NULL;
3429 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
3430 unsigned cVerbosity = 0;
3431 uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
3432 uint32_t iSignature = 0;
3433 const char *pszCArrayNm = NULL;
3434 bool fForce = false;
3435
3436 RTGETOPTSTATE GetState;
3437 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3438 AssertRCReturn(rc, RTEXITCODE_FAILURE);
3439 RTGETOPTUNION ValueUnion;
3440 int ch;
3441 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
3442 {
3443 switch (ch)
3444 {
3445 case 'e': pszExe = ValueUnion.psz; break;
3446 case 'o': pszOut = ValueUnion.psz; break;
3447 case 'b': fCursorFlags = 0; break;
3448 case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
3449 case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
3450 case 'f': fForce = true; break;
3451 case 'i': iSignature = ValueUnion.u32; break;
3452 case 'V': return HandleVersion(cArgs, papszArgs);
3453 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
3454
3455 case 'C':
3456 pszCArrayNm = *ValueUnion.psz ? ValueUnion.psz : NULL;
3457 if (pszCArrayNm)
3458 iSignature = UINT32_MAX;
3459 break;
3460
3461 case VINF_GETOPT_NOT_OPTION:
3462 if (!pszExe)
3463 pszExe = ValueUnion.psz;
3464 else if (!pszOut)
3465 pszOut = ValueUnion.psz;
3466 else
3467 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
3468 break;
3469
3470 default:
3471 return RTGetOptPrintError(ch, &ValueUnion);
3472 }
3473 }
3474 if (!pszExe)
3475 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
3476 if (!pszOut)
3477 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
3478 if (!fForce && RTPathExists(pszOut))
3479 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
3480
3481 /*
3482 * Do it.
3483 */
3484 /* Read & decode the PKCS#7 signature. */
3485 SIGNTOOLPKCS7EXE This;
3486 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
3487 if (rcExit == RTEXITCODE_SUCCESS)
3488 {
3489 if (pszCArrayNm == NULL || iSignature != UINT32_MAX)
3490 {
3491 /* Find the signing certificate (ASSUMING that the certificate used is shipped in the set of certificates). */
3492 PRTCRPKCS7SIGNEDDATA pSignedData;
3493 PCRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(&This, iSignature, &pSignedData);
3494 rcExit = RTEXITCODE_FAILURE;
3495 if (pSignerInfo)
3496 {
3497 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSignedData->SignerInfos.papItems[0]->IssuerAndSerialNumber;
3498 PCRTCRX509CERTIFICATE pCert;
3499 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
3500 &pISN->Name, &pISN->SerialNumber);
3501 if (pCert)
3502 {
3503 /*
3504 * Write it out.
3505 */
3506 if (pszCArrayNm == NULL)
3507 rcExit = WriteCertToFile(pCert, pszOut, fForce);
3508 else
3509 rcExit = WriteCertToFileAsC(pCert, pszOut, fForce, pszCArrayNm);
3510 }
3511 else
3512 RTMsgError("Certificate not found.");
3513 }
3514 else
3515 RTMsgError("Could not locate signature #%u!", iSignature);
3516 }
3517 else
3518 {
3519 uint32_t const cSignatures = SignToolPkcs7_CountSignatures(&This);
3520 if (cSignatures)
3521 {
3522 PRTSTREAM pStrm = NULL;
3523 rc = RTStrmOpen(pszOut, fForce ? "wt+" : "wtx", &pStrm);
3524 if (RT_SUCCESS(rc))
3525 {
3526 for (iSignature = 0; iSignature < cSignatures; iSignature++)
3527 {
3528 PRTCRPKCS7SIGNEDDATA pSignedData;
3529 PCRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(&This, iSignature, &pSignedData);
3530 if (!pSignerInfo)
3531 {
3532 rcExit = RTMsgErrorExitFailure("Could not locate signature #%u out of %u!", iSignature, cSignatures);
3533 break;
3534 }
3535 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSignedData->SignerInfos.papItems[0]->IssuerAndSerialNumber;
3536 PCRTCRX509CERTIFICATE pCert;
3537 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
3538 &pISN->Name, &pISN->SerialNumber);
3539 if (pCert)
3540 PrintCertAsCArray(pCert, iSignature, pszCArrayNm, pStrm);
3541 else
3542 {
3543 rcExit = RTMsgErrorExitFailure("Could not locate certificate for signature #%u (out of %u)!",
3544 iSignature, cSignatures);
3545 break;
3546 }
3547 }
3548
3549 PrintCertTableAsC(iSignature, pszCArrayNm, pStrm);
3550
3551 rc = RTStrmClose(pStrm);
3552 if (RT_FAILURE(rc))
3553 rcExit = RTMsgErrorExitFailure("Error writing/closing '%s': %Rrc", pszOut, rc);
3554 }
3555 else
3556 rcExit = RTMsgErrorExitFailure("Failed to open '%s' for writing: %Rrc", pszOut, rc);
3557 }
3558 else
3559 rcExit = RTMsgErrorExitFailure("No signatures found!");
3560 }
3561
3562 /* Delete the signature data. */
3563 SignToolPkcs7Exe_Delete(&This);
3564 }
3565 return rcExit;
3566}
3567
3568
3569/*********************************************************************************************************************************
3570* The 'extract-signer-root' & 'extract-timestamp-root' commands. *
3571*********************************************************************************************************************************/
3572class BaseExtractState
3573{
3574public:
3575 const char *pszFile;
3576 const char *pszOut;
3577 RTLDRARCH enmLdrArch;
3578 unsigned cVerbosity;
3579 uint32_t iSignature;
3580 bool fForce;
3581 /** Timestamp or main signature. */
3582 bool const fTimestamp;
3583 const char *pszBaseNm;
3584
3585 BaseExtractState(bool a_fTimestamp)
3586 : pszFile(NULL)
3587 , pszOut(NULL)
3588 , enmLdrArch(RTLDRARCH_WHATEVER)
3589 , cVerbosity(0)
3590 , iSignature(0)
3591 , fForce(false)
3592 , fTimestamp(a_fTimestamp)
3593 , pszBaseNm(NULL)
3594 {
3595 }
3596};
3597
3598class RootExtractState : public BaseExtractState
3599{
3600public:
3601 CryptoStore RootStore;
3602 CryptoStore AdditionalStore;
3603
3604 RootExtractState(bool a_fTimestamp)
3605 : BaseExtractState(a_fTimestamp)
3606 , RootStore()
3607 , AdditionalStore()
3608 { }
3609
3610 /**
3611 * Creates the two stores, filling the root one with trusted CAs and
3612 * certificates found on the system or in the user's account.
3613 */
3614 bool init(void)
3615 {
3616 int rc = RTCrStoreCreateInMem(&this->RootStore.m_hStore, 0);
3617 if (RT_SUCCESS(rc))
3618 {
3619 rc = RTCrStoreCreateInMem(&this->AdditionalStore.m_hStore, 0);
3620 if (RT_SUCCESS(rc))
3621 return true;
3622 }
3623 RTMsgError("RTCrStoreCreateInMem failed: %Rrc", rc);
3624 return false;
3625 }
3626};
3627
3628
3629/**
3630 * Locates the target signature and certificate collection.
3631 */
3632static PRTCRPKCS7SIGNERINFO BaseExtractFindSignerInfo(SIGNTOOLPKCS7 *pThis, BaseExtractState *pState, bool fOptional,
3633 PRTCRPKCS7SIGNEDDATA *ppSignedData, PCRTCRPKCS7SETOFCERTS *ppCerts)
3634{
3635 *ppSignedData = NULL;
3636 *ppCerts = NULL;
3637
3638 /*
3639 * Locate the target signature.
3640 */
3641 PRTCRPKCS7SIGNEDDATA pSignedData = NULL;
3642 PRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(pThis, pState->iSignature, &pSignedData);
3643 if (pSignerInfo)
3644 {
3645 /*
3646 * If the target is the timestamp we have to locate the relevant
3647 * timestamp signature and adjust the return values.
3648 */
3649 if (pState->fTimestamp)
3650 {
3651 for (uint32_t iItem = 0; iItem < pSignerInfo->UnauthenticatedAttributes.cItems; iItem++)
3652 {
3653 PCRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iItem];
3654 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES)
3655 {
3656 /* ASSUME that all counter signatures are timestamping. */
3657 if (pAttr->uValues.pCounterSignatures->cItems > 0)
3658 {
3659 *ppSignedData = pSignedData;
3660 *ppCerts = &pSignedData->Certificates;
3661 return pAttr->uValues.pCounterSignatures->papItems[0];
3662 }
3663 RTMsgWarning("Timestamp signature attribute is empty!");
3664 }
3665 else if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_TIMESTAMP)
3666 {
3667 /* ASSUME that all valid timestamp signatures for now, pick the first. */
3668 if (pAttr->uValues.pContentInfos->cItems > 0)
3669 {
3670 PCRTCRPKCS7CONTENTINFO pContentInfo = pAttr->uValues.pContentInfos->papItems[0];
3671 if (RTAsn1ObjId_CompareWithString(&pContentInfo->ContentType, RTCR_PKCS7_SIGNED_DATA_OID) == 0)
3672 {
3673 pSignedData = pContentInfo->u.pSignedData;
3674 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCRTSPTSTINFO_OID) == 0)
3675 {
3676 if (pSignedData->SignerInfos.cItems > 0)
3677 {
3678 *ppSignedData = pSignedData;
3679 *ppCerts = &pSignedData->Certificates;
3680 return pSignedData->SignerInfos.papItems[0];
3681 }
3682 RTMsgWarning("Timestamp signature has no signers!");
3683 }
3684 else
3685 RTMsgWarning("Timestamp signature contains wrong content (%s)!",
3686 pSignedData->ContentInfo.ContentType.szObjId);
3687 }
3688 else
3689 RTMsgWarning("Timestamp signature is not SignedData but %s!", pContentInfo->ContentType.szObjId);
3690 }
3691 else
3692 RTMsgWarning("Timestamp signature attribute is empty!");
3693 }
3694 }
3695 if (!fOptional)
3696 RTMsgError("Cound not find a timestamp signature associated with signature #%u!", pState->iSignature);
3697 pSignerInfo = NULL;
3698 }
3699 else
3700 {
3701 *ppSignedData = pSignedData;
3702 *ppCerts = &pSignedData->Certificates;
3703 }
3704 }
3705 else if (!fOptional)
3706 RTMsgError("Could not locate signature #%u!", pState->iSignature);
3707 return pSignerInfo;
3708}
3709
3710
3711/** @callback_method_impl{FNRTDUMPPRINTFV} */
3712static DECLCALLBACK(void) DumpToStdOutPrintfV(void *pvUser, const char *pszFormat, va_list va)
3713{
3714 RT_NOREF(pvUser);
3715 RTPrintfV(pszFormat, va);
3716}
3717
3718
3719static RTEXITCODE RootExtractWorker3(SIGNTOOLPKCS7 *pThis, RootExtractState *pState, PRTSTREAM pStrm, uint32_t *pidxCert,
3720 PRTERRINFOSTATIC pStaticErrInfo)
3721{
3722 /*
3723 * Locate the target signature.
3724 */
3725 bool const fOptional = pidxCert != NULL && pStrm != NULL && pState->fTimestamp /*fOptional*/;
3726 PRTCRPKCS7SIGNEDDATA pSignedData;
3727 PCRTCRPKCS7SETOFCERTS pCerts;
3728 PCRTCRPKCS7SIGNERINFO pSignerInfo = BaseExtractFindSignerInfo(pThis, pState, fOptional, &pSignedData, &pCerts);
3729 if (!pSignerInfo)
3730 {
3731 if (!fOptional)
3732 return RTMsgErrorExitFailure("Could not locate signature #%u!", pState->iSignature);
3733 return RTEXITCODE_SUCCESS;
3734 }
3735
3736
3737 /* The next bit is modelled on first half of rtCrPkcs7VerifySignerInfo. */
3738
3739 /*
3740 * Locate the signing certificate.
3741 */
3742 PCRTCRCERTCTX pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(pState->RootStore.m_hStore,
3743 &pSignerInfo->IssuerAndSerialNumber.Name,
3744 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3745 if (!pSignerCertCtx)
3746 pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(pState->AdditionalStore.m_hStore,
3747 &pSignerInfo->IssuerAndSerialNumber.Name,
3748 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3749
3750 PCRTCRX509CERTIFICATE pSignerCert;
3751 if (pSignerCertCtx)
3752 pSignerCert = pSignerCertCtx->pCert;
3753 else
3754 {
3755 pSignerCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(pCerts,
3756 &pSignerInfo->IssuerAndSerialNumber.Name,
3757 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3758 if (!pSignerCert)
3759 return RTMsgErrorExitFailure("Certificate not found: serial=%.*Rhxs",
3760 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.cb,
3761 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.uData.pv);
3762 }
3763
3764 /*
3765 * Now we build paths so we can get to the root certificate.
3766 */
3767 RTCRX509CERTPATHS hCertPaths;
3768 int rc = RTCrX509CertPathsCreate(&hCertPaths, pSignerCert);
3769 if (RT_FAILURE(rc))
3770 return RTMsgErrorExitFailure("RTCrX509CertPathsCreate failed: %Rrc", rc);
3771
3772 /* Configure: */
3773 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
3774 rc = RTCrX509CertPathsSetTrustedStore(hCertPaths, pState->RootStore.m_hStore);
3775 if (RT_SUCCESS(rc))
3776 {
3777 rc = RTCrX509CertPathsSetUntrustedStore(hCertPaths, pState->AdditionalStore.m_hStore);
3778 if (RT_SUCCESS(rc))
3779 {
3780 rc = RTCrX509CertPathsSetUntrustedSet(hCertPaths, pCerts);
3781 if (RT_SUCCESS(rc))
3782 {
3783 /* We don't technically need this, I think. */
3784 rc = RTCrX509CertPathsSetTrustAnchorChecks(hCertPaths, true /*fEnable*/);
3785 if (RT_SUCCESS(rc))
3786 {
3787 /* Seems we might need this for the sha-1 certs and such. */
3788 RTCrX509CertPathsSetValidTimeSpec(hCertPaths, NULL);
3789
3790 /* Build the paths: */
3791 rc = RTCrX509CertPathsBuild(hCertPaths, RTErrInfoInitStatic(pStaticErrInfo));
3792 if (RT_SUCCESS(rc))
3793 {
3794 uint32_t const cPaths = RTCrX509CertPathsGetPathCount(hCertPaths);
3795
3796 /* Validate the paths: */
3797 uint32_t cValidPaths = 0;
3798 rc = RTCrX509CertPathsValidateAll(hCertPaths, &cValidPaths, RTErrInfoInitStatic(pStaticErrInfo));
3799 if (RT_SUCCESS(rc))
3800 {
3801 if (pState->cVerbosity > 0)
3802 RTMsgInfo("%u of %u paths are valid", cValidPaths, cPaths);
3803 if (pState->cVerbosity > 1)
3804 RTCrX509CertPathsDumpAll(hCertPaths, pState->cVerbosity, DumpToStdOutPrintfV, NULL);
3805
3806 /*
3807 * Now, pick the first valid path with a real certificate at the end.
3808 */
3809 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
3810 {
3811 PCRTCRX509CERTIFICATE pRootCert = NULL;
3812 PCRTCRX509NAME pSubject = NULL;
3813 bool fTrusted = false;
3814 int rcVerify = -1;
3815 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/,
3816 &pSubject, NULL, &pRootCert, NULL /*ppCertCtx*/, &rcVerify);
3817 if (RT_SUCCESS(rc))
3818 {
3819 if (fTrusted && RT_SUCCESS(rcVerify) && pRootCert)
3820 {
3821 /*
3822 * Now copy out the certificate.
3823 */
3824 if (!pState->pszBaseNm)
3825 rcExit = WriteCertToFile(pRootCert, pState->pszOut, pState->fForce);
3826 else if (!pStrm)
3827 rcExit = WriteCertToFileAsC(pRootCert, pState->pszOut, pState->fForce,
3828 pState->pszBaseNm);
3829 else
3830 {
3831 PrintCertAsCArray(pRootCert, *pidxCert, pState->pszBaseNm, pStrm);
3832 *pidxCert += 1;
3833 rcExit = RTEXITCODE_SUCCESS;
3834 }
3835 break;
3836 }
3837 }
3838 else
3839 {
3840 RTMsgError("RTCrX509CertPathsQueryPathInfo failed: %Rrc", rc);
3841 break;
3842 }
3843 }
3844 }
3845 else
3846 {
3847 RTMsgError("RTCrX509CertPathsValidateAll failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
3848 RTCrX509CertPathsDumpAll(hCertPaths, pState->cVerbosity, DumpToStdOutPrintfV, NULL);
3849 }
3850 }
3851 else
3852 RTMsgError("RTCrX509CertPathsBuild failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
3853 }
3854 else
3855 RTMsgError("RTCrX509CertPathsSetTrustAnchorChecks failed: %Rrc", rc);
3856 }
3857 else
3858 RTMsgError("RTCrX509CertPathsSetUntrustedSet failed: %Rrc", rc);
3859 }
3860 else
3861 RTMsgError("RTCrX509CertPathsSetUntrustedStore failed: %Rrc", rc);
3862 }
3863 else
3864 RTMsgError("RTCrX509CertPathsSetTrustedStore failed: %Rrc", rc);
3865
3866 uint32_t cRefs = RTCrX509CertPathsRelease(hCertPaths);
3867 Assert(cRefs == 0); RT_NOREF(cRefs);
3868
3869 return rcExit;
3870}
3871
3872
3873static RTEXITCODE RootExtractWorker2(SIGNTOOLPKCS7 *pThis, RootExtractState *pState, PRTERRINFOSTATIC pStaticErrInfo)
3874{
3875 if (!pState->pszBaseNm || pState->iSignature != UINT32_MAX)
3876 return RootExtractWorker3(pThis, pState, NULL, NULL, pStaticErrInfo);
3877
3878 /*
3879 * Dump all these certificates.
3880 */
3881 uint32_t const cSignatures = SignToolPkcs7_CountSignatures(pThis);
3882 if (!cSignatures)
3883 return RTMsgErrorExitFailure("No signatures found!");
3884
3885 PRTSTREAM pStrm = NULL;
3886 int rc = RTStrmOpen(pState->pszOut, pState->fForce ? "wt+" : "wtx", &pStrm);
3887 if (RT_FAILURE(rc))
3888 return RTMsgErrorExitFailure("Failed to open '%s' for writing: %Rrc", pState->pszOut, rc);
3889
3890 uint32_t idxCert = 0; /* tracking separately, as we ignore missing timestamp chains. */
3891 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
3892 for (uint32_t iSignature = 0; iSignature < cSignatures && rcExit == RTEXITCODE_SUCCESS; iSignature++)
3893 {
3894 pState->iSignature = iSignature;
3895 rcExit = RootExtractWorker3(pThis, pState, pStrm, &idxCert, pStaticErrInfo);
3896 }
3897
3898 PrintCertTableAsC(idxCert, pState->pszBaseNm, pStrm);
3899
3900 rc = RTStrmClose(pStrm);
3901 if (RT_FAILURE(rc))
3902 rcExit = RTMsgErrorExitFailure("Error writing/closing '%s': %Rrc", pState->pszOut, rc);
3903 return rcExit;
3904}
3905
3906
3907static RTEXITCODE RootExtractWorker(RootExtractState *pState, PRTERRINFOSTATIC pStaticErrInfo)
3908{
3909 /*
3910 * Check that all we need is there and whether the output file exists.
3911 */
3912 if (!pState->pszFile)
3913 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
3914 if (!pState->pszOut)
3915 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
3916 if (!pState->fForce && RTPathExists(pState->pszOut))
3917 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pState->pszOut);
3918
3919 /*
3920 * Detect the type of file we're dealing with, do type specific setup and
3921 * call common worker to do the rest.
3922 */
3923 RTEXITCODE rcExit;
3924 RTSIGNTOOLFILETYPE enmFileType = DetectFileType(RTSIGNTOOLFILETYPE_DETECT, pState->pszFile);
3925 if (enmFileType == RTSIGNTOOLFILETYPE_EXE)
3926 {
3927 SIGNTOOLPKCS7EXE Exe;
3928 rcExit = SignToolPkcs7Exe_InitFromFile(&Exe, pState->pszFile, pState->cVerbosity, pState->enmLdrArch);
3929 if (rcExit == RTEXITCODE_SUCCESS)
3930 {
3931 rcExit = RootExtractWorker2(&Exe, pState, pStaticErrInfo);
3932 SignToolPkcs7Exe_Delete(&Exe);
3933 }
3934 }
3935 else if (enmFileType == RTSIGNTOOLFILETYPE_CAT)
3936 {
3937 SIGNTOOLPKCS7 Cat;
3938 rcExit = SignToolPkcs7_InitFromFile(&Cat, pState->pszFile, pState->cVerbosity);
3939 if (rcExit == RTEXITCODE_SUCCESS)
3940 {
3941 rcExit = RootExtractWorker2(&Cat, pState, pStaticErrInfo);
3942 SignToolPkcs7_Delete(&Cat);
3943 }
3944 }
3945 else
3946 rcExit = RTEXITCODE_FAILURE;
3947 return rcExit;
3948}
3949
3950
3951static RTEXITCODE HelpExtractRootCommon(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel, bool fTimestamp)
3952{
3953 RT_NOREF_PV(enmLevel);
3954 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
3955 "extract-%s-root [-v|--verbose] [-q|--quiet] [--as-c-array <name>] [--signature-index|-i <num>] "
3956 "[--root <root-cert.der>] [--self-signed-roots-from-system] [--additional <supp-cert.der>] "
3957 "[--intermediate-certs-from-system] [--input] <signed-file> "
3958 "[-f|--force] [--output|-o] <outfile.cer/h>\n",
3959 fTimestamp ? "timestamp" : "signer");
3960 if (enmLevel == RTSIGNTOOLHELP_FULL)
3961 {
3962 RTStrmWrappedPrintf(pStrm, 0,
3963 "\n"
3964 "Extracts the root certificate of the %sgiven "
3965 "signature. If there are more than one valid certificate path, the first one with "
3966 "a full certificate will be picked.\n",
3967 fTimestamp ? "first timestamp associated with the " : "");
3968 RTStrmWrappedPrintf(pStrm, 0,
3969 "\n"
3970 "Options:\n"
3971 " -v, --verbose, -q, --quite\n"
3972 " Controls the noise level. The '-v' options are accumlative while '-q' is absolute.\n"
3973 " Default: -q\n"
3974 " -C <name>, --as-c-array <name>\n"
3975 " Output a C header file containing the roots of all signatures (or a selected one if"
3976 "--signature-index is used again after this option.\n"
3977 " Default: Output one binary certificate.\n"
3978 " -i <num>, --signature-index <num>\n"
3979 " Zero-based index of the signature to extract the root for.\n"
3980 " Default: -i 0\n"
3981 " -r <root-cert.file>, --root <root-cert.file>\n"
3982 " Use the certificate(s) in the specified file as a trusted root(s). "
3983 "The file format can be PEM or DER.\n"
3984 " -R, --self-signed-roots-from-system\n"
3985 " Use all self-signed trusted root certificates found on the system and associated with the "
3986 "current user as trusted roots. This is limited to self-signed certificates, so that we get "
3987 "a full chain even if a non-end-entity certificate is present in any of those system stores for "
3988 "some reason.\n"
3989 " -a <supp-cert.file>, --additional <supp-cert.file>\n"
3990 " Use the certificate(s) in the specified file as a untrusted intermediate certificates. "
3991 "The file format can be PEM or DER.\n"
3992 " -A, --intermediate-certs-from-system\n"
3993 " Use all certificates found on the system and associated with the current user as intermediate "
3994 "certification authorities.\n"
3995 " --input <signed-file>\n"
3996 " Signed executable or security cabinet file to examine. The '--input' option bit is optional "
3997 "and there to allow more flexible parameter ordering.\n"
3998 " -f, --force\n"
3999 " Overwrite existing output file. The default is not to overwriting any existing file.\n"
4000 " -o <outfile.cer> --output <outfile.cer>\n"
4001 " The name of the output file. Again the '-o|--output' bit is optional and only for flexibility.\n"
4002 );
4003 }
4004 return RTEXITCODE_SUCCESS;
4005}
4006
4007
4008static RTEXITCODE HandleExtractRootCommon(int cArgs, char **papszArgs, bool fTimestamp)
4009{
4010 /*
4011 * Parse arguments.
4012 */
4013 static const RTGETOPTDEF s_aOptions[] =
4014 {
4015 { "--root", 'r', RTGETOPT_REQ_STRING },
4016 { "--self-signed-roots-from-system", 'R', RTGETOPT_REQ_NOTHING },
4017 { "--additional", 'a', RTGETOPT_REQ_STRING },
4018 { "--intermediate-certs-from-system",'A', RTGETOPT_REQ_NOTHING },
4019 { "--add", 'a', RTGETOPT_REQ_STRING },
4020 { "--input", 'I', RTGETOPT_REQ_STRING },
4021 { "--output", 'o', RTGETOPT_REQ_STRING },
4022 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
4023 { "--force", 'f', RTGETOPT_REQ_NOTHING },
4024 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4025 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
4026 { "--as-c-array", 'C', RTGETOPT_REQ_STRING },
4027 };
4028 RTERRINFOSTATIC StaticErrInfo;
4029 RootExtractState State(fTimestamp);
4030 if (!State.init())
4031 return RTEXITCODE_FAILURE;
4032 RTGETOPTSTATE GetState;
4033 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4034 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4035 RTGETOPTUNION ValueUnion;
4036 int ch;
4037 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4038 {
4039 switch (ch)
4040 {
4041 case 'a':
4042 if (!State.AdditionalStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
4043 return RTEXITCODE_FAILURE;
4044 break;
4045
4046 case 'A':
4047 if (!State.AdditionalStore.addIntermediateCertsFromSystem(&StaticErrInfo))
4048 return RTEXITCODE_FAILURE;
4049 break;
4050
4051 case 'r':
4052 if (!State.RootStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
4053 return RTEXITCODE_FAILURE;
4054 break;
4055
4056 case 'R':
4057 if (!State.RootStore.addSelfSignedRootsFromSystem(&StaticErrInfo))
4058 return RTEXITCODE_FAILURE;
4059 break;
4060
4061 case 'I': State.pszFile = ValueUnion.psz; break;
4062 case 'o': State.pszOut = ValueUnion.psz; break;
4063 case 'f': State.fForce = true; break;
4064 case 'i': State.iSignature = ValueUnion.u32; break;
4065 case 'v': State.cVerbosity++; break;
4066 case 'q': State.cVerbosity = 0; break;
4067 case 'V': return HandleVersion(cArgs, papszArgs);
4068 case 'h': return HelpExtractRootCommon(g_pStdOut, RTSIGNTOOLHELP_FULL, fTimestamp);
4069
4070 case 'C':
4071 State.pszBaseNm = *ValueUnion.psz ? ValueUnion.psz : NULL;
4072 if (State.pszBaseNm)
4073 State.iSignature = UINT32_MAX;
4074 break;
4075
4076 case VINF_GETOPT_NOT_OPTION:
4077 if (!State.pszFile)
4078 State.pszFile = ValueUnion.psz;
4079 else if (!State.pszOut)
4080 State.pszOut = ValueUnion.psz;
4081 else
4082 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4083 break;
4084
4085 default:
4086 return RTGetOptPrintError(ch, &ValueUnion);
4087 }
4088 }
4089 return RootExtractWorker(&State, &StaticErrInfo);
4090}
4091
4092
4093static RTEXITCODE HelpExtractSignerRoot(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4094{
4095 return HelpExtractRootCommon(pStrm, enmLevel, false /*fTimestamp*/);
4096}
4097
4098
4099static RTEXITCODE HandleExtractSignerRoot(int cArgs, char **papszArgs)
4100{
4101 return HandleExtractRootCommon(cArgs, papszArgs, false /*fTimestamp*/ );
4102}
4103
4104
4105static RTEXITCODE HelpExtractTimestampRoot(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4106{
4107 return HelpExtractRootCommon(pStrm, enmLevel, true /*fTimestamp*/);
4108}
4109
4110
4111static RTEXITCODE HandleExtractTimestampRoot(int cArgs, char **papszArgs)
4112{
4113 return HandleExtractRootCommon(cArgs, papszArgs, true /*fTimestamp*/ );
4114}
4115
4116
4117/*********************************************************************************************************************************
4118* The 'extract-exe-signature' command. *
4119*********************************************************************************************************************************/
4120
4121static RTEXITCODE HelpExtractExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4122{
4123 RT_NOREF_PV(enmLevel);
4124 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4125 "extract-exe-signerature [--input|--exe|-e] <exe> [--output|-o] <outfile.pkcs7>\n");
4126 return RTEXITCODE_SUCCESS;
4127}
4128
4129static RTEXITCODE HandleExtractExeSignature(int cArgs, char **papszArgs)
4130{
4131 /*
4132 * Parse arguments.
4133 */
4134 static const RTGETOPTDEF s_aOptions[] =
4135 {
4136 { "--exe", 'e', RTGETOPT_REQ_STRING },
4137 { "--input", 'e', RTGETOPT_REQ_STRING },
4138 { "--output", 'o', RTGETOPT_REQ_STRING },
4139 { "--force", 'f', RTGETOPT_REQ_NOTHING },
4140 };
4141
4142 const char *pszExe = NULL;
4143 const char *pszOut = NULL;
4144 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
4145 unsigned cVerbosity = 0;
4146 bool fForce = false;
4147
4148 RTGETOPTSTATE GetState;
4149 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4150 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4151 RTGETOPTUNION ValueUnion;
4152 int ch;
4153 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4154 {
4155 switch (ch)
4156 {
4157 case 'e': pszExe = ValueUnion.psz; break;
4158 case 'o': pszOut = ValueUnion.psz; break;
4159 case 'f': fForce = true; break;
4160 case 'V': return HandleVersion(cArgs, papszArgs);
4161 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
4162
4163 case VINF_GETOPT_NOT_OPTION:
4164 if (!pszExe)
4165 pszExe = ValueUnion.psz;
4166 else if (!pszOut)
4167 pszOut = ValueUnion.psz;
4168 else
4169 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4170 break;
4171
4172 default:
4173 return RTGetOptPrintError(ch, &ValueUnion);
4174 }
4175 }
4176 if (!pszExe)
4177 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
4178 if (!pszOut)
4179 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
4180 if (!fForce && RTPathExists(pszOut))
4181 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
4182
4183 /*
4184 * Do it.
4185 */
4186 /* Read & decode the PKCS#7 signature. */
4187 SIGNTOOLPKCS7EXE This;
4188 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
4189 if (rcExit == RTEXITCODE_SUCCESS)
4190 {
4191 /*
4192 * Write out the PKCS#7 signature.
4193 */
4194 RTFILE hFile;
4195 rc = RTFileOpen(&hFile, pszOut,
4196 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | (fForce ? RTFILE_O_CREATE_REPLACE : RTFILE_O_CREATE));
4197 if (RT_SUCCESS(rc))
4198 {
4199 rc = RTFileWrite(hFile, This.pbBuf, This.cbBuf, NULL);
4200 if (RT_SUCCESS(rc))
4201 {
4202 rc = RTFileClose(hFile);
4203 if (RT_SUCCESS(rc))
4204 {
4205 hFile = NIL_RTFILE;
4206 RTMsgInfo("Successfully wrote %u bytes to '%s'", This.cbBuf, pszOut);
4207 rcExit = RTEXITCODE_SUCCESS;
4208 }
4209 else
4210 RTMsgError("RTFileClose failed: %Rrc", rc);
4211 }
4212 else
4213 RTMsgError("RTFileWrite failed: %Rrc", rc);
4214 RTFileClose(hFile);
4215 }
4216 else
4217 RTMsgError("Error opening '%s' for writing: %Rrc", pszOut, rc);
4218
4219 /* Delete the signature data. */
4220 SignToolPkcs7Exe_Delete(&This);
4221 }
4222 return rcExit;
4223}
4224
4225
4226/*********************************************************************************************************************************
4227* The 'add-nested-exe-signature' command. *
4228*********************************************************************************************************************************/
4229
4230static RTEXITCODE HelpAddNestedExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4231{
4232 RT_NOREF_PV(enmLevel);
4233 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4234 "add-nested-exe-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-exe> <source-exe>\n");
4235 if (enmLevel == RTSIGNTOOLHELP_FULL)
4236 RTStrmWrappedPrintf(pStrm, 0,
4237 "\n"
4238 "The --debug option allows the source-exe to be omitted in order to test the "
4239 "encoding and PE file modification.\n"
4240 "\n"
4241 "The --prepend option puts the nested signature first rather than appending it "
4242 "to the end of of the nested signature set. Windows reads nested signatures in "
4243 "reverse order, so --prepend will logically putting it last.\n");
4244 return RTEXITCODE_SUCCESS;
4245}
4246
4247
4248static RTEXITCODE HandleAddNestedExeSignature(int cArgs, char **papszArgs)
4249{
4250 /*
4251 * Parse arguments.
4252 */
4253 static const RTGETOPTDEF s_aOptions[] =
4254 {
4255 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
4256 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4257 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
4258 };
4259
4260 const char *pszDst = NULL;
4261 const char *pszSrc = NULL;
4262 unsigned cVerbosity = 0;
4263 bool fDebug = false;
4264 bool fPrepend = false;
4265
4266 RTGETOPTSTATE GetState;
4267 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4268 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4269 RTGETOPTUNION ValueUnion;
4270 int ch;
4271 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4272 {
4273 switch (ch)
4274 {
4275 case 'v': cVerbosity++; break;
4276 case 'd': fDebug = pszSrc == NULL; break;
4277 case 'p': fPrepend = true; break;
4278 case 'V': return HandleVersion(cArgs, papszArgs);
4279 case 'h': return HelpAddNestedExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4280
4281 case VINF_GETOPT_NOT_OPTION:
4282 if (!pszDst)
4283 pszDst = ValueUnion.psz;
4284 else if (!pszSrc)
4285 {
4286 pszSrc = ValueUnion.psz;
4287 fDebug = false;
4288 }
4289 else
4290 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4291 break;
4292
4293 default:
4294 return RTGetOptPrintError(ch, &ValueUnion);
4295 }
4296 }
4297 if (!pszDst)
4298 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination executable given.");
4299 if (!pszSrc && !fDebug)
4300 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source executable file given.");
4301
4302 /*
4303 * Do it.
4304 */
4305 /* Read & decode the source PKCS#7 signature. */
4306 SIGNTOOLPKCS7EXE Src;
4307 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7Exe_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
4308 if (rcExit == RTEXITCODE_SUCCESS)
4309 {
4310 /* Ditto for the destination PKCS#7 signature. */
4311 SIGNTOOLPKCS7EXE Dst;
4312 rcExit = SignToolPkcs7Exe_InitFromFile(&Dst, pszDst, cVerbosity);
4313 if (rcExit == RTEXITCODE_SUCCESS)
4314 {
4315 /* Do the signature manipulation. */
4316 if (pszSrc)
4317 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
4318 if (rcExit == RTEXITCODE_SUCCESS)
4319 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
4320
4321 /* Update the destination executable file. */
4322 if (rcExit == RTEXITCODE_SUCCESS)
4323 rcExit = SignToolPkcs7Exe_WriteSignatureToFile(&Dst, cVerbosity);
4324
4325 SignToolPkcs7Exe_Delete(&Dst);
4326 }
4327 if (pszSrc)
4328 SignToolPkcs7Exe_Delete(&Src);
4329 }
4330
4331 return rcExit;
4332}
4333
4334
4335/*********************************************************************************************************************************
4336* The 'add-nested-cat-signature' command. *
4337*********************************************************************************************************************************/
4338
4339static RTEXITCODE HelpAddNestedCatSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4340{
4341 RT_NOREF_PV(enmLevel);
4342 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4343 "add-nested-cat-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-cat> <source-cat>\n");
4344 if (enmLevel == RTSIGNTOOLHELP_FULL)
4345 RTStrmWrappedPrintf(pStrm, 0,
4346 "\n"
4347 "The --debug option allows the source-cat to be omitted in order to test the "
4348 "ASN.1 re-encoding of the destination catalog file.\n"
4349 "\n"
4350 "The --prepend option puts the nested signature first rather than appending it "
4351 "to the end of of the nested signature set. Windows reads nested signatures in "
4352 "reverse order, so --prepend will logically putting it last.\n");
4353 return RTEXITCODE_SUCCESS;
4354}
4355
4356
4357static RTEXITCODE HandleAddNestedCatSignature(int cArgs, char **papszArgs)
4358{
4359 /*
4360 * Parse arguments.
4361 */
4362 static const RTGETOPTDEF s_aOptions[] =
4363 {
4364 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
4365 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4366 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
4367 };
4368
4369 const char *pszDst = NULL;
4370 const char *pszSrc = NULL;
4371 unsigned cVerbosity = 0;
4372 bool fDebug = false;
4373 bool fPrepend = false;
4374
4375 RTGETOPTSTATE GetState;
4376 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4377 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4378 RTGETOPTUNION ValueUnion;
4379 int ch;
4380 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4381 {
4382 switch (ch)
4383 {
4384 case 'v': cVerbosity++; break;
4385 case 'd': fDebug = pszSrc == NULL; break;
4386 case 'p': fPrepend = true; break;
4387 case 'V': return HandleVersion(cArgs, papszArgs);
4388 case 'h': return HelpAddNestedCatSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4389
4390 case VINF_GETOPT_NOT_OPTION:
4391 if (!pszDst)
4392 pszDst = ValueUnion.psz;
4393 else if (!pszSrc)
4394 {
4395 pszSrc = ValueUnion.psz;
4396 fDebug = false;
4397 }
4398 else
4399 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4400 break;
4401
4402 default:
4403 return RTGetOptPrintError(ch, &ValueUnion);
4404 }
4405 }
4406 if (!pszDst)
4407 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination catalog file given.");
4408 if (!pszSrc && !fDebug)
4409 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source catalog file given.");
4410
4411 /*
4412 * Do it.
4413 */
4414 /* Read & decode the source PKCS#7 signature. */
4415 SIGNTOOLPKCS7 Src;
4416 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
4417 if (rcExit == RTEXITCODE_SUCCESS)
4418 {
4419 /* Ditto for the destination PKCS#7 signature. */
4420 SIGNTOOLPKCS7EXE Dst;
4421 rcExit = SignToolPkcs7_InitFromFile(&Dst, pszDst, cVerbosity);
4422 if (rcExit == RTEXITCODE_SUCCESS)
4423 {
4424 /* Do the signature manipulation. */
4425 if (pszSrc)
4426 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
4427 if (rcExit == RTEXITCODE_SUCCESS)
4428 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
4429
4430 /* Update the destination executable file. */
4431 if (rcExit == RTEXITCODE_SUCCESS)
4432 rcExit = SignToolPkcs7_WriteSignatureToFile(&Dst, pszDst, cVerbosity);
4433
4434 SignToolPkcs7_Delete(&Dst);
4435 }
4436 if (pszSrc)
4437 SignToolPkcs7_Delete(&Src);
4438 }
4439
4440 return rcExit;
4441}
4442
4443
4444/*********************************************************************************************************************************
4445* The 'add-timestamp-exe-signature' command. *
4446*********************************************************************************************************************************/
4447#ifndef IPRT_SIGNTOOL_NO_SIGNING
4448
4449static RTEXITCODE HelpAddTimestampExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4450{
4451 RT_NOREF_PV(enmLevel);
4452
4453 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4454 "add-timestamp-exe-signature [-v|--verbose] [--signature-index|-i <num>] "
4455 OPT_CERT_KEY_SYNOPSIS("--timestamp-", "")
4456 "[--timestamp-type old|new] "
4457 "[--timestamp-override <partial-isots>] "
4458 "[--replace-existing|-r] "
4459 "<exe>\n");
4460 if (enmLevel == RTSIGNTOOLHELP_FULL)
4461 RTStrmWrappedPrintf(pStrm, 0,
4462 "This is mainly to test timestamp code.\n"
4463 "\n"
4464 "The --timestamp-override option can take a partial or full ISO timestamp. It is merged "
4465 "with the current time if partial.\n"
4466 "\n");
4467 return RTEXITCODE_SUCCESS;
4468}
4469
4470static RTEXITCODE HandleAddTimestampExeSignature(int cArgs, char **papszArgs)
4471{
4472 /*
4473 * Parse arguments.
4474 */
4475 static const RTGETOPTDEF s_aOptions[] =
4476 {
4477 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
4478 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "", 1000),
4479 { "--timestamp-type", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4480 { "--timestamp-override", OPT_TIMESTAMP_OVERRIDE, RTGETOPT_REQ_STRING },
4481 { "--replace-existing", 'r', RTGETOPT_REQ_NOTHING },
4482 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4483 };
4484
4485 unsigned cVerbosity = 0;
4486 unsigned iSignature = 0;
4487 bool fReplaceExisting = false;
4488 SignToolTimestampOpts TimestampOpts("timestamp");
4489 RTTIMESPEC SigningTime;
4490 RTTimeNow(&SigningTime);
4491
4492 RTGETOPTSTATE GetState;
4493 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4494 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4495
4496 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
4497 RTGETOPTUNION ValueUnion;
4498 int ch;
4499 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4500 {
4501 RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
4502 switch (ch)
4503 {
4504 OPT_CERT_KEY_SWITCH_CASES(TimestampOpts, 1000, ch, ValueUnion, rcExit2);
4505 case 'i': iSignature = ValueUnion.u32; break;
4506 case OPT_TIMESTAMP_TYPE: rcExit2 = HandleOptTimestampType(&TimestampOpts, ValueUnion.psz); break;
4507 case OPT_TIMESTAMP_OVERRIDE: rcExit2 = HandleOptTimestampOverride(&SigningTime, ValueUnion.psz); break;
4508 case 'r': fReplaceExisting = true; break;
4509 case 'v': cVerbosity++; break;
4510 case 'V': return HandleVersion(cArgs, papszArgs);
4511 case 'h': return HelpAddTimestampExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4512
4513 case VINF_GETOPT_NOT_OPTION:
4514 /* Do final certificate and key option processing (first file only). */
4515 rcExit2 = TimestampOpts.finalizeOptions(cVerbosity);
4516 if (rcExit2 == RTEXITCODE_SUCCESS)
4517 {
4518 /* Do the work: */
4519 SIGNTOOLPKCS7EXE Exe;
4520 rcExit2 = SignToolPkcs7Exe_InitFromFile(&Exe, ValueUnion.psz, cVerbosity);
4521 if (rcExit2 == RTEXITCODE_SUCCESS)
4522 {
4523 rcExit2 = SignToolPkcs7_AddTimestampSignature(&Exe, cVerbosity, iSignature, fReplaceExisting,
4524 SigningTime, &TimestampOpts);
4525 if (rcExit2 == RTEXITCODE_SUCCESS)
4526 rcExit2 = SignToolPkcs7_Encode(&Exe, cVerbosity);
4527 if (rcExit2 == RTEXITCODE_SUCCESS)
4528 rcExit2 = SignToolPkcs7Exe_WriteSignatureToFile(&Exe, cVerbosity);
4529 SignToolPkcs7Exe_Delete(&Exe);
4530 }
4531 if (rcExit2 != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
4532 rcExit = rcExit2;
4533 rcExit2 = RTEXITCODE_SUCCESS;
4534 }
4535 break;
4536
4537 default:
4538 return RTGetOptPrintError(ch, &ValueUnion);
4539 }
4540
4541 if (rcExit2 != RTEXITCODE_SUCCESS)
4542 {
4543 rcExit = rcExit2;
4544 break;
4545 }
4546 }
4547 return rcExit;
4548}
4549
4550#endif /*!IPRT_SIGNTOOL_NO_SIGNING */
4551
4552
4553/*********************************************************************************************************************************
4554* The 'sign-exe' command. *
4555*********************************************************************************************************************************/
4556#ifndef IPRT_SIGNTOOL_NO_SIGNING
4557
4558static RTEXITCODE HelpSign(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4559{
4560 RT_NOREF_PV(enmLevel);
4561
4562 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4563 "sign [-v|--verbose] "
4564 "[--file-type exe|cat] "
4565 "[--type|/fd sha1|sha256] "
4566 "[--hash-pages|/ph] "
4567 "[--no-hash-pages|/nph] "
4568 "[--append/as] "
4569 "[--no-signing-time] "
4570 "[--add-cert <file>] "
4571 "[--timestamp-type old|new] "
4572 "[--timestamp-override <partial-isots>] "
4573 "[--verbose|/debug|-v] "
4574 OPT_CERT_KEY_SYNOPSIS("--", "")
4575 OPT_CERT_KEY_SYNOPSIS("--timestamp-", "")
4576 //OPT_CERT_KEY_SYNOPSIS("--timestamp-", "-2") - doesn't work, windows only uses one. Check again with new-style signatures
4577 "<exe>\n");
4578 if (enmLevel == RTSIGNTOOLHELP_FULL)
4579 RTStrmWrappedPrintf(pStrm, 0,
4580 "\n"
4581 "Create a new code signature for an executable or catalog.\n"
4582 "\n"
4583 "Options:\n"
4584 " --append, /as\n"
4585 " Append the signature if one already exists. The default is to replace any existing signature.\n"
4586 " --type sha1|sha256, /fd sha1|sha256\n"
4587 " Signature type, SHA-1 or SHA-256.\n"
4588 " --hash-pages, /ph, --no-page-hashes, /nph\n"
4589 " Enables or disables page hashing. Ignored for catalog files. Default: --no-page-hashes\n"
4590 " --add-cert <file>, /ac <file>\n"
4591 " Adds (first) certificate from the file to the signature. Both PEM and DER (binary) encodings "
4592 "are accepted. Repeat to add more certiifcates.\n"
4593 " --timestamp-override <partial-iso-timestamp>\n"
4594 " This specifies the signing time as a ISO timestamp. Partial timestamps are merged with the "
4595 "current time. This is applied to any timestamp signature as well as the signingTime attribute of "
4596 "main signature. Higher resolution than seconds is not supported. Default: Current time.\n"
4597 " --no-signing-time\n"
4598 " Don't set the signing time on the main signature, only on the timestamp one. Unfortunately, "
4599 "this doesn't work without modifying OpenSSL a little.\n"
4600 " --timestamp-type old|new\n"
4601 " Selects the timstamp type. 'old' is the old style /t <url> stuff from signtool.exe. "
4602 "'new' means a RTC-3161 timstamp - currently not implemented. Default: old\n"
4603 //" --timestamp-type-2 old|new\n"
4604 //" Same as --timestamp-type but for the 2nd timstamp signature.\n"
4605 "\n"
4606 //"Certificate and Key Options (--timestamp-cert-name[-2] etc for timestamps):\n"
4607 "Certificate and Key Options (--timestamp-cert-name etc for timestamps):\n"
4608 " --cert-subject <partial name>, /n <partial name>\n"
4609 " Locate the main signature signing certificate and key, unless anything else is given, "
4610 "by the given name substring. Overrides any previous --cert-sha1 and --cert-file options.\n"
4611 " --cert-sha1 <hex bytes>, /sha1 <hex bytes>\n"
4612 " Locate the main signature signing certificate and key, unless anything else is given, "
4613 "by the given thumbprint. The hex bytes can be space separated, colon separated, just "
4614 "bunched together, or a mix of these. This overrids any previous --cert-name and --cert-file "
4615 "options.\n"
4616 " --cert-store <name>, /s <store>\n"
4617 " Certificate store to search when using --cert-name or --cert-sha1. Default: MY\n"
4618 " --cert-machine-store, /sm\n"
4619 " Use the machine store rather the ones of the current user.\n"
4620 " --cert-file <file>, /f <file>\n"
4621 " Load the certificate and key, unless anything else is given, from given file. Both PEM and "
4622 "DER (binary) encodings are supported. Keys file can be RSA or PKCS#12 formatted.\n"
4623 " --key-file <file>\n"
4624 " Load the private key from the given file. Support RSA and PKCS#12 formatted files.\n"
4625 " --key-password <password>, /p <password>\n"
4626 " Password to use to decrypt a PKCS#12 password file.\n"
4627 " --key-password-file <file>|stdin\n"
4628 " Load password to decrypt the password file from the given file or from stdin.\n"
4629 " --key-name <name>, /kc <name>\n"
4630 " The private key container name. Not implemented.\n"
4631 " --key-provider <name>, /csp <name>\n"
4632 " The name of the crypto provider where the private key conatiner specified via --key-name "
4633 "can be found.\n"
4634 );
4635
4636 return RTEXITCODE_SUCCESS;
4637}
4638
4639
4640static RTEXITCODE HandleSign(int cArgs, char **papszArgs)
4641{
4642 /*
4643 * Parse arguments.
4644 */
4645 static const RTGETOPTDEF s_aOptions[] =
4646 {
4647 { "--append", 'A', RTGETOPT_REQ_NOTHING },
4648 { "/as", 'A', RTGETOPT_REQ_NOTHING },
4649 { "/a", OPT_IGNORED, RTGETOPT_REQ_NOTHING }, /* select best cert automatically */
4650 { "--type", 't', RTGETOPT_REQ_STRING },
4651 { "/fd", 't', RTGETOPT_REQ_STRING },
4652 { "--hash-pages", OPT_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4653 { "/ph", OPT_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4654 { "--no-hash-pages", OPT_NO_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4655 { "/nph", OPT_NO_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4656 { "--add-cert", OPT_ADD_CERT, RTGETOPT_REQ_STRING },
4657 { "/ac", OPT_ADD_CERT, RTGETOPT_REQ_STRING },
4658 { "--description", 'd', RTGETOPT_REQ_STRING },
4659 { "--desc", 'd', RTGETOPT_REQ_STRING },
4660 { "/d", 'd', RTGETOPT_REQ_STRING },
4661 { "--description-url", 'D', RTGETOPT_REQ_STRING },
4662 { "--desc-url", 'D', RTGETOPT_REQ_STRING },
4663 { "/du", 'D', RTGETOPT_REQ_STRING },
4664 { "--no-signing-time", OPT_NO_SIGNING_TIME, RTGETOPT_REQ_NOTHING },
4665 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--", "", 1000),
4666 OPT_CERT_KEY_GETOPTDEF_COMPAT_ENTRIES( 1000),
4667 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "", 1020),
4668 //OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "-1", 1020),
4669 //OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "-2", 1040), - disabled as windows cannot make use of it. Try again when
4670 // new-style timestamp signatures has been implemented. Otherwise, just add two primary signatures with the two
4671 // different timestamps certificates / hashes / whatever.
4672 { "--timestamp-type", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4673 { "--timestamp-type-1", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4674 { "--timestamp-type-2", OPT_TIMESTAMP_TYPE_2, RTGETOPT_REQ_STRING },
4675 { "--timestamp-override", OPT_TIMESTAMP_OVERRIDE, RTGETOPT_REQ_STRING },
4676 { "--file-type", OPT_FILE_TYPE, RTGETOPT_REQ_STRING },
4677 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4678 { "/v", 'v', RTGETOPT_REQ_NOTHING },
4679 { "/debug", 'v', RTGETOPT_REQ_NOTHING },
4680 };
4681
4682 unsigned cVerbosity = 0;
4683 RTDIGESTTYPE enmSigType = RTDIGESTTYPE_SHA1;
4684 bool fReplaceExisting = true;
4685 bool fHashPages = false;
4686 bool fNoSigningTime = false;
4687 RTSIGNTOOLFILETYPE enmForceFileType = RTSIGNTOOLFILETYPE_DETECT;
4688 SignToolKeyPair SigningCertKey("signing", true);
4689 CryptoStore AddCerts;
4690 const char *pszDescription = NULL; /** @todo implement putting descriptions into the OpusInfo stuff. */
4691 const char *pszDescriptionUrl = NULL;
4692 SignToolTimestampOpts aTimestampOpts[2] = { SignToolTimestampOpts("timestamp"), SignToolTimestampOpts("timestamp#2") };
4693 RTTIMESPEC SigningTime;
4694 RTTimeNow(&SigningTime);
4695
4696 RTGETOPTSTATE GetState;
4697 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4698 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4699
4700 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
4701 RTGETOPTUNION ValueUnion;
4702 int ch;
4703 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4704 {
4705 RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
4706 switch (ch)
4707 {
4708 OPT_CERT_KEY_SWITCH_CASES(SigningCertKey, 1000, ch, ValueUnion, rcExit2);
4709 OPT_CERT_KEY_SWITCH_CASES(aTimestampOpts[0], 1020, ch, ValueUnion, rcExit2);
4710 OPT_CERT_KEY_SWITCH_CASES(aTimestampOpts[1], 1040, ch, ValueUnion, rcExit2);
4711 case 't': rcExit2 = HandleOptSignatureType(&enmSigType, ValueUnion.psz); break;
4712 case 'A': fReplaceExisting = false; break;
4713 case 'd': pszDescription = ValueUnion.psz; break;
4714 case 'D': pszDescriptionUrl = ValueUnion.psz; break;
4715 case OPT_HASH_PAGES: fHashPages = true; break;
4716 case OPT_NO_HASH_PAGES: fHashPages = false; break;
4717 case OPT_NO_SIGNING_TIME: fNoSigningTime = true; break;
4718 case OPT_ADD_CERT: rcExit2 = HandleOptAddCert(&AddCerts.m_hStore, ValueUnion.psz); break;
4719 case OPT_TIMESTAMP_TYPE: rcExit2 = HandleOptTimestampType(&aTimestampOpts[0], ValueUnion.psz); break;
4720 case OPT_TIMESTAMP_TYPE_2: rcExit2 = HandleOptTimestampType(&aTimestampOpts[1], ValueUnion.psz); break;
4721 case OPT_TIMESTAMP_OVERRIDE: rcExit2 = HandleOptTimestampOverride(&SigningTime, ValueUnion.psz); break;
4722 case OPT_FILE_TYPE: rcExit2 = HandleOptFileType(&enmForceFileType, ValueUnion.psz); break;
4723 case OPT_IGNORED: break;
4724 case 'v': cVerbosity++; break;
4725 case 'V': return HandleVersion(cArgs, papszArgs);
4726 case 'h': return HelpSign(g_pStdOut, RTSIGNTOOLHELP_FULL);
4727
4728 case VINF_GETOPT_NOT_OPTION:
4729 /*
4730 * Do final certificate and key option processing (first file only).
4731 */
4732 rcExit2 = SigningCertKey.finalizeOptions(cVerbosity);
4733 for (unsigned i = 0; rcExit2 == RTEXITCODE_SUCCESS && i < RT_ELEMENTS(aTimestampOpts); i++)
4734 rcExit2 = aTimestampOpts[i].finalizeOptions(cVerbosity);
4735 if (rcExit2 == RTEXITCODE_SUCCESS)
4736 {
4737 /*
4738 * Detect file type.
4739 */
4740 RTSIGNTOOLFILETYPE enmFileType = DetectFileType(enmForceFileType, ValueUnion.psz);
4741 if (enmFileType == RTSIGNTOOLFILETYPE_EXE)
4742 {
4743 /*
4744 * Sign executable image.
4745 */
4746 SIGNTOOLPKCS7EXE Exe;
4747 rcExit2 = SignToolPkcs7Exe_InitFromFile(&Exe, ValueUnion.psz, cVerbosity,
4748 RTLDRARCH_WHATEVER, true /*fAllowUnsigned*/);
4749 if (rcExit2 == RTEXITCODE_SUCCESS)
4750 {
4751 rcExit2 = SignToolPkcs7_AddOrReplaceSignature(&Exe, cVerbosity, enmSigType, fReplaceExisting,
4752 fHashPages, fNoSigningTime, &SigningCertKey,
4753 AddCerts.m_hStore, SigningTime,
4754 RT_ELEMENTS(aTimestampOpts), aTimestampOpts);
4755 if (rcExit2 == RTEXITCODE_SUCCESS)
4756 rcExit2 = SignToolPkcs7_Encode(&Exe, cVerbosity);
4757 if (rcExit2 == RTEXITCODE_SUCCESS)
4758 rcExit2 = SignToolPkcs7Exe_WriteSignatureToFile(&Exe, cVerbosity);
4759 SignToolPkcs7Exe_Delete(&Exe);
4760 }
4761 }
4762 else if (enmFileType == RTSIGNTOOLFILETYPE_CAT)
4763 {
4764 /*
4765 * Sign catalog file.
4766 */
4767 SIGNTOOLPKCS7 Cat;
4768 rcExit2 = SignToolPkcs7_InitFromFile(&Cat, ValueUnion.psz, cVerbosity);
4769 if (rcExit2 == RTEXITCODE_SUCCESS)
4770 {
4771 rcExit2 = SignToolPkcs7_AddOrReplaceCatSignature(&Cat, cVerbosity, enmSigType, fReplaceExisting,
4772 fNoSigningTime, &SigningCertKey,
4773 AddCerts.m_hStore, SigningTime,
4774 RT_ELEMENTS(aTimestampOpts), aTimestampOpts);
4775 if (rcExit2 == RTEXITCODE_SUCCESS)
4776 rcExit2 = SignToolPkcs7_Encode(&Cat, cVerbosity);
4777 if (rcExit2 == RTEXITCODE_SUCCESS)
4778 rcExit2 = SignToolPkcs7_WriteSignatureToFile(&Cat, ValueUnion.psz, cVerbosity);
4779 SignToolPkcs7_Delete(&Cat);
4780 }
4781 }
4782 else
4783 rcExit2 = RTEXITCODE_FAILURE;
4784 if (rcExit2 != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
4785 rcExit = rcExit2;
4786 rcExit2 = RTEXITCODE_SUCCESS;
4787 }
4788 break;
4789
4790 default:
4791 return RTGetOptPrintError(ch, &ValueUnion);
4792 }
4793 if (rcExit2 != RTEXITCODE_SUCCESS)
4794 {
4795 rcExit = rcExit2;
4796 break;
4797 }
4798 }
4799
4800 return rcExit;
4801}
4802
4803#endif /*!IPRT_SIGNTOOL_NO_SIGNING */
4804
4805
4806/*********************************************************************************************************************************
4807* The 'verify-exe' command. *
4808*********************************************************************************************************************************/
4809#ifndef IPRT_IN_BUILD_TOOL
4810
4811static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4812{
4813 RT_NOREF_PV(enmLevel);
4814 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4815 "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--self-signed-roots-from-system] "
4816 "[--additional <supp-cert.der>] [--type <win|osx>] <exe1> [exe2 [..]]\n");
4817 return RTEXITCODE_SUCCESS;
4818}
4819
4820typedef struct VERIFYEXESTATE
4821{
4822 CryptoStore RootStore;
4823 CryptoStore KernelRootStore;
4824 CryptoStore AdditionalStore;
4825 bool fKernel;
4826 int cVerbose;
4827 enum { kSignType_Windows, kSignType_OSX } enmSignType;
4828 RTLDRARCH enmLdrArch;
4829 uint32_t cBad;
4830 uint32_t cOkay;
4831 const char *pszFilename;
4832 RTTIMESPEC ValidationTime;
4833
4834 VERIFYEXESTATE()
4835 : fKernel(false)
4836 , cVerbose(0)
4837 , enmSignType(kSignType_Windows)
4838 , enmLdrArch(RTLDRARCH_WHATEVER)
4839 , cBad(0)
4840 , cOkay(0)
4841 , pszFilename(NULL)
4842 {
4843 RTTimeSpecSetSeconds(&ValidationTime, 0);
4844 }
4845} VERIFYEXESTATE;
4846
4847# ifdef VBOX
4848/** Certificate store load set.
4849 * Declared outside HandleVerifyExe because of braindead gcc visibility crap. */
4850struct STSTORESET
4851{
4852 RTCRSTORE hStore;
4853 PCSUPTAENTRY paTAs;
4854 unsigned cTAs;
4855};
4856# endif
4857
4858/**
4859 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
4860 * Standard code signing. Use this for Microsoft SPC.}
4861 */
4862static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
4863 void *pvUser, PRTERRINFO pErrInfo)
4864{
4865 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
4866 uint32_t cPaths = RTCrX509CertPathsGetPathCount(hCertPaths);
4867
4868 /*
4869 * Dump all the paths.
4870 */
4871 if (pState->cVerbose > 0)
4872 {
4873 RTPrintf(fFlags & RTCRPKCS7VCC_F_TIMESTAMP ? "Timestamp Path%s:\n" : "Signature Path%s:\n",
4874 cPaths == 1 ? "" : "s");
4875 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
4876 {
4877 //if (iPath != 0)
4878 // RTPrintf("---\n");
4879 RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
4880 *pErrInfo->pszMsg = '\0';
4881 }
4882 //RTPrintf(fFlags & RTCRPKCS7VCC_F_TIMESTAMP ? "--- end timestamp ---\n" : "--- end signature ---\n");
4883 }
4884
4885 /*
4886 * Test signing certificates normally doesn't have all the necessary
4887 * features required below. So, treat them as special cases.
4888 */
4889 if ( hCertPaths == NIL_RTCRX509CERTPATHS
4890 && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
4891 {
4892 RTMsgInfo("Test signed.\n");
4893 return VINF_SUCCESS;
4894 }
4895
4896 if (hCertPaths == NIL_RTCRX509CERTPATHS)
4897 RTMsgInfo("Signed by trusted certificate.\n");
4898
4899 /*
4900 * Standard code signing capabilites required.
4901 */
4902 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
4903 if ( RT_SUCCESS(rc)
4904 && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
4905 {
4906 /*
4907 * If windows kernel signing, a valid certificate path must be anchored
4908 * by the microsoft kernel signing root certificate. The only
4909 * alternative is test signing.
4910 */
4911 if ( pState->fKernel
4912 && hCertPaths != NIL_RTCRX509CERTPATHS
4913 && pState->enmSignType == VERIFYEXESTATE::kSignType_Windows)
4914 {
4915 uint32_t cFound = 0;
4916 uint32_t cValid = 0;
4917 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
4918 {
4919 bool fTrusted;
4920 PCRTCRX509NAME pSubject;
4921 PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
4922 int rcVerify;
4923 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
4924 NULL, NULL /*pCertCtx*/, &rcVerify);
4925 AssertRCBreak(rc);
4926
4927 if (RT_SUCCESS(rcVerify))
4928 {
4929 Assert(fTrusted);
4930 cValid++;
4931
4932 /* Search the kernel signing root store for a matching anchor. */
4933 RTCRSTORECERTSEARCH Search;
4934 rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->KernelRootStore.m_hStore, pSubject, &Search);
4935 AssertRCBreak(rc);
4936 PCRTCRCERTCTX pCertCtx;
4937 while ((pCertCtx = RTCrStoreCertSearchNext(pState->KernelRootStore.m_hStore, &Search)) != NULL)
4938 {
4939 PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo;
4940 if (pCertCtx->pCert)
4941 pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
4942 else if (pCertCtx->pTaInfo)
4943 pPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
4944 else
4945 pPubKeyInfo = NULL;
4946 if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0)
4947 cFound++;
4948 RTCrCertCtxRelease(pCertCtx);
4949 }
4950
4951 int rc2 = RTCrStoreCertSearchDestroy(pState->KernelRootStore.m_hStore, &Search); AssertRC(rc2);
4952 }
4953 }
4954 if (RT_SUCCESS(rc) && cFound == 0)
4955 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
4956 if (RT_SUCCESS(rc) && cValid != 2)
4957 RTMsgWarning("%u valid paths, expected 2", cValid);
4958 }
4959 /*
4960 * For Mac OS X signing, check for special developer ID attributes.
4961 */
4962 else if (pState->enmSignType == VERIFYEXESTATE::kSignType_OSX)
4963 {
4964 uint32_t cDevIdApp = 0;
4965 uint32_t cDevIdKext = 0;
4966 uint32_t cDevIdMacDev = 0;
4967 for (uint32_t i = 0; i < pCert->TbsCertificate.T3.Extensions.cItems; i++)
4968 {
4969 PCRTCRX509EXTENSION pExt = pCert->TbsCertificate.T3.Extensions.papItems[i];
4970 if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_APPLICATION_OID) == 0)
4971 {
4972 cDevIdApp++;
4973 if (!pExt->Critical.fValue)
4974 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
4975 "Dev ID Application certificate extension is not flagged critical");
4976 }
4977 else if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_KEXT_OID) == 0)
4978 {
4979 cDevIdKext++;
4980 if (!pExt->Critical.fValue)
4981 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
4982 "Dev ID kext certificate extension is not flagged critical");
4983 }
4984 else if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_MAC_SW_DEV_OID) == 0)
4985 {
4986 cDevIdMacDev++;
4987 if (!pExt->Critical.fValue)
4988 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
4989 "Dev ID Mac SW dev certificate extension is not flagged critical");
4990 }
4991 }
4992 if (cDevIdApp == 0)
4993 {
4994 if (cDevIdMacDev == 0)
4995 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
4996 "Certificate is missing the 'Dev ID Application' extension");
4997 else
4998 RTMsgWarning("Mac SW dev certificate used to sign code.");
4999 }
5000 if (cDevIdKext == 0 && pState->fKernel)
5001 {
5002 if (cDevIdMacDev == 0)
5003 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
5004 "Certificate is missing the 'Dev ID kext' extension");
5005 else
5006 RTMsgWarning("Mac SW dev certificate used to sign kernel code.");
5007 }
5008 }
5009 }
5010
5011 return rc;
5012}
5013
5014/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
5015static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, PCRTLDRSIGNATUREINFO pInfo, PRTERRINFO pErrInfo, void *pvUser)
5016{
5017 VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
5018 RT_NOREF_PV(hLdrMod);
5019
5020 switch (pInfo->enmType)
5021 {
5022 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
5023 {
5024 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pInfo->pvSignature;
5025
5026 if (pState->cVerbose > 0)
5027 RTMsgInfo("Verifying '%s' signature #%u ...\n", pState->pszFilename, pInfo->iSignature + 1);
5028
5029 /*
5030 * Dump the signed data if so requested and it's the first one, assuming that
5031 * additional signatures in contained wihtin the same ContentInfo structure.
5032 */
5033 if (pState->cVerbose > 1 && pInfo->iSignature == 0)
5034 RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
5035
5036 /*
5037 * We'll try different alternative timestamps here.
5038 */
5039 struct { RTTIMESPEC TimeSpec; const char *pszDesc; } aTimes[3];
5040 unsigned cTimes = 0;
5041
5042 /* The specified timestamp. */
5043 if (RTTimeSpecGetSeconds(&pState->ValidationTime) != 0)
5044 {
5045 aTimes[cTimes].TimeSpec = pState->ValidationTime;
5046 aTimes[cTimes].pszDesc = "validation time";
5047 cTimes++;
5048 }
5049
5050 /* Linking timestamp: */
5051 uint64_t uLinkingTime = 0;
5052 int rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &uLinkingTime, sizeof(uLinkingTime));
5053 if (RT_SUCCESS(rc))
5054 {
5055 RTTimeSpecSetSeconds(&aTimes[cTimes].TimeSpec, uLinkingTime);
5056 aTimes[cTimes].pszDesc = "at link time";
5057 cTimes++;
5058 }
5059 else if (rc != VERR_NOT_FOUND)
5060 RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pState->pszFilename, rc);
5061
5062 /* Now: */
5063 RTTimeNow(&aTimes[cTimes].TimeSpec);
5064 aTimes[cTimes].pszDesc = "now";
5065 cTimes++;
5066
5067 /*
5068 * Do the actual verification.
5069 */
5070 for (unsigned iTime = 0; iTime < cTimes; iTime++)
5071 {
5072 if (pInfo->pvExternalData)
5073 rc = RTCrPkcs7VerifySignedDataWithExternalData(pContentInfo,
5074 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
5075 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
5076 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT
5077 | RTCRPKCS7VERIFY_SD_F_CHECK_TRUST_ANCHORS,
5078 pState->AdditionalStore.m_hStore, pState->RootStore.m_hStore,
5079 &aTimes[iTime].TimeSpec,
5080 VerifyExecCertVerifyCallback, pState,
5081 pInfo->pvExternalData, pInfo->cbExternalData, pErrInfo);
5082 else
5083 rc = RTCrPkcs7VerifySignedData(pContentInfo,
5084 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
5085 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
5086 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT
5087 | RTCRPKCS7VERIFY_SD_F_CHECK_TRUST_ANCHORS,
5088 pState->AdditionalStore.m_hStore, pState->RootStore.m_hStore,
5089 &aTimes[iTime].TimeSpec,
5090 VerifyExecCertVerifyCallback, pState, pErrInfo);
5091 if (RT_SUCCESS(rc))
5092 {
5093 Assert(rc == VINF_SUCCESS || rc == VINF_CR_DIGEST_DEPRECATED);
5094 const char *pszNote = rc == VINF_CR_DIGEST_DEPRECATED ? " (deprecated digest)" : "";
5095 if (pInfo->cSignatures == 1)
5096 RTMsgInfo("'%s' is valid %s%s.\n", pState->pszFilename, aTimes[iTime].pszDesc, pszNote);
5097 else
5098 RTMsgInfo("'%s' signature #%u is valid %s%s.\n",
5099 pState->pszFilename, pInfo->iSignature + 1, aTimes[iTime].pszDesc, pszNote);
5100 pState->cOkay++;
5101 return VINF_SUCCESS;
5102 }
5103 if (rc != VERR_CR_X509_CPV_NOT_VALID_AT_TIME)
5104 {
5105 if (pInfo->cSignatures == 1)
5106 RTMsgError("%s: Failed to verify signature: %Rrc%#RTeim\n", pState->pszFilename, rc, pErrInfo);
5107 else
5108 RTMsgError("%s: Failed to verify signature #%u: %Rrc%#RTeim\n",
5109 pState->pszFilename, pInfo->iSignature + 1, rc, pErrInfo);
5110 pState->cBad++;
5111 return VINF_SUCCESS;
5112 }
5113 }
5114
5115 if (pInfo->cSignatures == 1)
5116 RTMsgError("%s: Signature is not valid at present or link time.\n", pState->pszFilename);
5117 else
5118 RTMsgError("%s: Signature #%u is not valid at present or link time.\n",
5119 pState->pszFilename, pInfo->iSignature + 1);
5120 pState->cBad++;
5121 return VINF_SUCCESS;
5122 }
5123
5124 default:
5125 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", pInfo->enmType);
5126 }
5127}
5128
5129/**
5130 * Worker for HandleVerifyExe.
5131 */
5132static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
5133{
5134 /*
5135 * Open the executable image and verify it.
5136 */
5137 RTLDRMOD hLdrMod;
5138 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod);
5139 if (RT_FAILURE(rc))
5140 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc);
5141
5142 /* Reset the state. */
5143 pState->cBad = 0;
5144 pState->cOkay = 0;
5145 pState->pszFilename = pszFilename;
5146
5147 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
5148 if (RT_FAILURE(rc))
5149 RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg);
5150
5151 int rc2 = RTLdrClose(hLdrMod);
5152 if (RT_FAILURE(rc2))
5153 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
5154 if (RT_FAILURE(rc))
5155 return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
5156
5157 return pState->cOkay > 0 ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
5158}
5159
5160
5161static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
5162{
5163 RTERRINFOSTATIC StaticErrInfo;
5164
5165 /*
5166 * Parse arguments.
5167 */
5168 static const RTGETOPTDEF s_aOptions[] =
5169 {
5170 { "--kernel", 'k', RTGETOPT_REQ_NOTHING },
5171 { "--root", 'r', RTGETOPT_REQ_STRING },
5172 { "--self-signed-roots-from-system", 'R', RTGETOPT_REQ_NOTHING },
5173 { "--additional", 'a', RTGETOPT_REQ_STRING },
5174 { "--add", 'a', RTGETOPT_REQ_STRING },
5175 { "--type", 't', RTGETOPT_REQ_STRING },
5176 { "--validation-time", 'T', RTGETOPT_REQ_STRING },
5177 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
5178 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
5179 };
5180
5181 VERIFYEXESTATE State;
5182 int rc = RTCrStoreCreateInMem(&State.RootStore.m_hStore, 0);
5183 if (RT_SUCCESS(rc))
5184 rc = RTCrStoreCreateInMem(&State.KernelRootStore.m_hStore, 0);
5185 if (RT_SUCCESS(rc))
5186 rc = RTCrStoreCreateInMem(&State.AdditionalStore.m_hStore, 0);
5187 if (RT_FAILURE(rc))
5188 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
5189
5190 RTGETOPTSTATE GetState;
5191 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
5192 AssertRCReturn(rc, RTEXITCODE_FAILURE);
5193 RTGETOPTUNION ValueUnion;
5194 int ch;
5195 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
5196 {
5197 switch (ch)
5198 {
5199 case 'a':
5200 if (!State.AdditionalStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
5201 return RTEXITCODE_FAILURE;
5202 break;
5203
5204 case 'r':
5205 if (!State.RootStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
5206 return RTEXITCODE_FAILURE;
5207 break;
5208
5209 case 'R':
5210 if (!State.RootStore.addSelfSignedRootsFromSystem(&StaticErrInfo))
5211 return RTEXITCODE_FAILURE;
5212 break;
5213
5214 case 't':
5215 if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
5216 State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
5217 else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
5218 State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
5219 else
5220 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
5221 break;
5222
5223 case 'T':
5224 if (!RTTimeSpecFromString(&State.ValidationTime, ValueUnion.psz))
5225 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid validation time (%s): %Rrc", ValueUnion.psz, rc);
5226 break;
5227
5228 case 'k': State.fKernel = true; break;
5229 case 'v': State.cVerbose++; break;
5230 case 'q': State.cVerbose = 0; break;
5231 case 'V': return HandleVersion(cArgs, papszArgs);
5232 case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
5233 default: return RTGetOptPrintError(ch, &ValueUnion);
5234 }
5235 }
5236 if (ch != VINF_GETOPT_NOT_OPTION)
5237 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
5238
5239 /*
5240 * Populate the certificate stores according to the signing type.
5241 */
5242# ifdef VBOX
5243 unsigned cSets = 0;
5244 struct STSTORESET aSets[6];
5245 switch (State.enmSignType)
5246 {
5247 case VERIFYEXESTATE::kSignType_Windows:
5248 aSets[cSets].hStore = State.RootStore.m_hStore;
5249 aSets[cSets].paTAs = g_aSUPTimestampTAs;
5250 aSets[cSets].cTAs = g_cSUPTimestampTAs;
5251 cSets++;
5252 aSets[cSets].hStore = State.RootStore.m_hStore;
5253 aSets[cSets].paTAs = g_aSUPSpcRootTAs;
5254 aSets[cSets].cTAs = g_cSUPSpcRootTAs;
5255 cSets++;
5256 aSets[cSets].hStore = State.RootStore.m_hStore;
5257 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
5258 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
5259 cSets++;
5260 aSets[cSets].hStore = State.KernelRootStore.m_hStore;
5261 aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
5262 aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
5263 cSets++;
5264 break;
5265
5266 case VERIFYEXESTATE::kSignType_OSX:
5267 aSets[cSets].hStore = State.RootStore.m_hStore;
5268 aSets[cSets].paTAs = g_aSUPAppleRootTAs;
5269 aSets[cSets].cTAs = g_cSUPAppleRootTAs;
5270 cSets++;
5271 break;
5272 }
5273 for (unsigned i = 0; i < cSets; i++)
5274 for (unsigned j = 0; j < aSets[i].cTAs; j++)
5275 {
5276 rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
5277 aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
5278 if (RT_FAILURE(rc))
5279 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
5280 i, j, StaticErrInfo.szMsg);
5281 }
5282# endif /* VBOX */
5283
5284 /*
5285 * Do it.
5286 */
5287 RTEXITCODE rcExit;
5288 for (;;)
5289 {
5290 rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo);
5291 if (rcExit != RTEXITCODE_SUCCESS)
5292 break;
5293
5294 /*
5295 * Next file
5296 */
5297 ch = RTGetOpt(&GetState, &ValueUnion);
5298 if (ch == 0)
5299 break;
5300 if (ch != VINF_GETOPT_NOT_OPTION)
5301 {
5302 rcExit = RTGetOptPrintError(ch, &ValueUnion);
5303 break;
5304 }
5305 }
5306
5307 return rcExit;
5308}
5309
5310#endif /* !IPRT_IN_BUILD_TOOL */
5311
5312/*
5313 * common code for show-exe and show-cat:
5314 */
5315
5316/**
5317 * Display an object ID.
5318 *
5319 * @returns IPRT status code.
5320 * @param pThis The show exe instance data.
5321 * @param pObjId The object ID to display.
5322 * @param pszLabel The field label (prefixed by szPrefix).
5323 * @param pszPost What to print after the ID (typically newline).
5324 */
5325static void HandleShowExeWorkerDisplayObjId(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszLabel, const char *pszPost)
5326{
5327 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
5328 if (RT_SUCCESS(rc))
5329 {
5330 if (pThis->cVerbosity > 1)
5331 RTPrintf("%s%s%s (%s)%s", pThis->szPrefix, pszLabel, pThis->szTmp, pObjId->szObjId, pszPost);
5332 else
5333 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pThis->szTmp, pszPost);
5334 }
5335 else
5336 RTPrintf("%s%s%s%s", pThis->szPrefix, pszLabel, pObjId->szObjId, pszPost);
5337}
5338
5339
5340/**
5341 * Display an object ID, without prefix and label
5342 *
5343 * @returns IPRT status code.
5344 * @param pThis The show exe instance data.
5345 * @param pObjId The object ID to display.
5346 * @param pszPost What to print after the ID (typically newline).
5347 */
5348static void HandleShowExeWorkerDisplayObjIdSimple(PSHOWEXEPKCS7 pThis, PCRTASN1OBJID pObjId, const char *pszPost)
5349{
5350 int rc = RTAsn1QueryObjIdName(pObjId, pThis->szTmp, sizeof(pThis->szTmp));
5351 if (RT_SUCCESS(rc))
5352 {
5353 if (pThis->cVerbosity > 1)
5354 RTPrintf("%s (%s)%s", pThis->szTmp, pObjId->szObjId, pszPost);
5355 else
5356 RTPrintf("%s%s", pThis->szTmp, pszPost);
5357 }
5358 else
5359 RTPrintf("%s%s", pObjId->szObjId, pszPost);
5360}
5361
5362
5363/**
5364 * Display a signer info attribute.
5365 *
5366 * @returns IPRT status code.
5367 * @param pThis The show exe instance data.
5368 * @param offPrefix The current prefix offset.
5369 * @param pAttr The attribute to display.
5370 */
5371static int HandleShowExeWorkerPkcs7DisplayAttrib(PSHOWEXEPKCS7 pThis, size_t offPrefix, PCRTCRPKCS7ATTRIBUTE pAttr)
5372{
5373 HandleShowExeWorkerDisplayObjId(pThis, &pAttr->Type, "", ":\n");
5374 if (pThis->cVerbosity > 4 && pAttr->SeqCore.Asn1Core.uData.pu8)
5375 RTPrintf("%s uData.pu8=%p cb=%#x\n", pThis->szPrefix, pAttr->SeqCore.Asn1Core.uData.pu8, pAttr->SeqCore.Asn1Core.cb);
5376
5377 int rc = VINF_SUCCESS;
5378 switch (pAttr->enmType)
5379 {
5380 case RTCRPKCS7ATTRIBUTETYPE_UNKNOWN:
5381 if (pAttr->uValues.pCores->cItems <= 1)
5382 RTPrintf("%s %u bytes\n", pThis->szPrefix,pAttr->uValues.pCores->SetCore.Asn1Core.cb);
5383 else
5384 RTPrintf("%s %u bytes divided by %u items\n", pThis->szPrefix, pAttr->uValues.pCores->SetCore.Asn1Core.cb, pAttr->uValues.pCores->cItems);
5385 break;
5386
5387 /* Object IDs, use pObjIds. */
5388 case RTCRPKCS7ATTRIBUTETYPE_OBJ_IDS:
5389 if (pAttr->uValues.pObjIds->cItems != 1)
5390 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIds->cItems);
5391 for (unsigned i = 0; i < pAttr->uValues.pObjIds->cItems; i++)
5392 {
5393 if (pAttr->uValues.pObjIds->cItems == 1)
5394 RTPrintf("%s ", pThis->szPrefix);
5395 else
5396 RTPrintf("%s ObjId[%u]: ", pThis->szPrefix, i);
5397 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIds->papItems[i], "\n");
5398 }
5399 break;
5400
5401 /* Sequence of object IDs, use pObjIdSeqs. */
5402 case RTCRPKCS7ATTRIBUTETYPE_MS_STATEMENT_TYPE:
5403 if (pAttr->uValues.pObjIdSeqs->cItems != 1)
5404 RTPrintf("%s%u object IDs:", pThis->szPrefix, pAttr->uValues.pObjIdSeqs->cItems);
5405 for (unsigned i = 0; i < pAttr->uValues.pObjIdSeqs->cItems; i++)
5406 {
5407 uint32_t const cObjIds = pAttr->uValues.pObjIdSeqs->papItems[i]->cItems;
5408 for (unsigned j = 0; j < cObjIds; j++)
5409 {
5410 if (pAttr->uValues.pObjIdSeqs->cItems == 1)
5411 RTPrintf("%s ", pThis->szPrefix);
5412 else
5413 RTPrintf("%s ObjIdSeq[%u]: ", pThis->szPrefix, i);
5414 if (cObjIds != 1)
5415 RTPrintf(" ObjId[%u]: ", j);
5416 HandleShowExeWorkerDisplayObjIdSimple(pThis, pAttr->uValues.pObjIdSeqs->papItems[i]->papItems[i], "\n");
5417 }
5418 }
5419 break;
5420
5421 /* Octet strings, use pOctetStrings. */
5422 case RTCRPKCS7ATTRIBUTETYPE_OCTET_STRINGS:
5423 if (pAttr->uValues.pOctetStrings->cItems != 1)
5424 RTPrintf("%s%u octet strings:", pThis->szPrefix, pAttr->uValues.pOctetStrings->cItems);
5425 for (unsigned i = 0; i < pAttr->uValues.pOctetStrings->cItems; i++)
5426 {
5427 PCRTASN1OCTETSTRING pOctetString = pAttr->uValues.pOctetStrings->papItems[i];
5428 uint32_t cbContent = pOctetString->Asn1Core.cb;
5429 if (cbContent > 0 && (cbContent <= 128 || pThis->cVerbosity >= 2))
5430 {
5431 uint8_t const *pbContent = pOctetString->Asn1Core.uData.pu8;
5432 uint32_t off = 0;
5433 while (off < cbContent)
5434 {
5435 uint32_t cbNow = RT_MIN(cbContent - off, 16);
5436 if (pAttr->uValues.pOctetStrings->cItems == 1)
5437 RTPrintf("%s %#06x: %.*Rhxs\n", pThis->szPrefix, off, cbNow, &pbContent[off]);
5438 else
5439 RTPrintf("%s OctetString[%u]: %#06x: %.*Rhxs\n", pThis->szPrefix, i, off, cbNow, &pbContent[off]);
5440 off += cbNow;
5441 }
5442 }
5443 else
5444 RTPrintf("%s: OctetString[%u]: %u bytes\n", pThis->szPrefix, i, pOctetString->Asn1Core.cb);
5445 }
5446 break;
5447
5448 /* Counter signatures (PKCS \#9), use pCounterSignatures. */
5449 case RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES:
5450 RTPrintf("%s%u counter signatures, %u bytes in total\n", pThis->szPrefix,
5451 pAttr->uValues.pCounterSignatures->cItems, pAttr->uValues.pCounterSignatures->SetCore.Asn1Core.cb);
5452 for (uint32_t i = 0; i < pAttr->uValues.pCounterSignatures->cItems; i++)
5453 {
5454 size_t offPrefix2 = offPrefix;
5455 if (pAttr->uValues.pContentInfos->cItems > 1)
5456 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "CounterSig[%u]: ", i);
5457 else
5458 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " ");
5459
5460 int rc2 = HandleShowExeWorkerPkcs7DisplaySignerInfo(pThis, offPrefix2,
5461 pAttr->uValues.pCounterSignatures->papItems[i]);
5462 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
5463 rc = rc2;
5464 }
5465 break;
5466
5467 /* Signing time (PKCS \#9), use pSigningTime. */
5468 case RTCRPKCS7ATTRIBUTETYPE_SIGNING_TIME:
5469 for (uint32_t i = 0; i < pAttr->uValues.pSigningTime->cItems; i++)
5470 {
5471 PCRTASN1TIME pTime = pAttr->uValues.pSigningTime->papItems[i];
5472 char szTS[RTTIME_STR_LEN];
5473 RTTimeToString(&pTime->Time, szTS, sizeof(szTS));
5474 if (pAttr->uValues.pSigningTime->cItems == 1)
5475 RTPrintf("%s %s (%.*s)\n", pThis->szPrefix, szTS, pTime->Asn1Core.cb, pTime->Asn1Core.uData.pch);
5476 else
5477 RTPrintf("%s #%u: %s (%.*s)\n", pThis->szPrefix, i, szTS, pTime->Asn1Core.cb, pTime->Asn1Core.uData.pch);
5478 }
5479 break;
5480
5481 /* Microsoft timestamp info (RFC-3161) signed data, use pContentInfo. */
5482 case RTCRPKCS7ATTRIBUTETYPE_MS_TIMESTAMP:
5483 case RTCRPKCS7ATTRIBUTETYPE_MS_NESTED_SIGNATURE:
5484 if (pAttr->uValues.pContentInfos->cItems > 1)
5485 RTPrintf("%s%u nested signatures, %u bytes in total\n", pThis->szPrefix,
5486 pAttr->uValues.pContentInfos->cItems, pAttr->uValues.pContentInfos->SetCore.Asn1Core.cb);
5487 for (unsigned i = 0; i < pAttr->uValues.pContentInfos->cItems; i++)
5488 {
5489 size_t offPrefix2 = offPrefix;
5490 if (pAttr->uValues.pContentInfos->cItems > 1)
5491 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig[%u]: ", i);
5492 else
5493 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " ");
5494 // offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "NestedSig: ", i);
5495 PCRTCRPKCS7CONTENTINFO pContentInfo = pAttr->uValues.pContentInfos->papItems[i];
5496 int rc2;
5497 if (RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
5498 rc2 = HandleShowExeWorkerPkcs7Display(pThis, pContentInfo->u.pSignedData, offPrefix2, pContentInfo);
5499 else
5500 rc2 = RTMsgErrorRc(VERR_ASN1_UNEXPECTED_OBJ_ID, "%sPKCS#7 content in nested signature is not 'signedData': %s",
5501 pThis->szPrefix, pContentInfo->ContentType.szObjId);
5502 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
5503 rc = rc2;
5504 }
5505 break;
5506
5507 case RTCRPKCS7ATTRIBUTETYPE_APPLE_MULTI_CD_PLIST:
5508 if (pAttr->uValues.pContentInfos->cItems != 1)
5509 RTPrintf("%s%u plists, expected only 1.\n", pThis->szPrefix, pAttr->uValues.pOctetStrings->cItems);
5510 for (unsigned i = 0; i < pAttr->uValues.pOctetStrings->cItems; i++)
5511 {
5512 PCRTASN1OCTETSTRING pOctetString = pAttr->uValues.pOctetStrings->papItems[i];
5513 size_t cbContent = pOctetString->Asn1Core.cb;
5514 char const *pchContent = pOctetString->Asn1Core.uData.pch;
5515 rc = RTStrValidateEncodingEx(pchContent, cbContent, RTSTR_VALIDATE_ENCODING_EXACT_LENGTH);
5516 if (RT_SUCCESS(rc))
5517 {
5518 while (cbContent > 0)
5519 {
5520 const char *pchNewLine = (const char *)memchr(pchContent, '\n', cbContent);
5521 size_t cchToWrite = pchNewLine ? pchNewLine - pchContent : cbContent;
5522 if (pAttr->uValues.pOctetStrings->cItems == 1)
5523 RTPrintf("%s %.*s\n", pThis->szPrefix, cchToWrite, pchContent);
5524 else
5525 RTPrintf("%s plist[%u]: %.*s\n", pThis->szPrefix, i, cchToWrite, pchContent);
5526 if (!pchNewLine)
5527 break;
5528 pchContent = pchNewLine + 1;
5529 cbContent -= cchToWrite + 1;
5530 }
5531 }
5532 else
5533 {
5534 if (pAttr->uValues.pContentInfos->cItems != 1)
5535 RTPrintf("%s: plist[%u]: Invalid UTF-8: %Rrc\n", pThis->szPrefix, i, rc);
5536 else
5537 RTPrintf("%s: Invalid UTF-8: %Rrc\n", pThis->szPrefix, rc);
5538 for (uint32_t off = 0; off < cbContent; off += 16)
5539 {
5540 size_t cbNow = RT_MIN(cbContent - off, 16);
5541 if (pAttr->uValues.pOctetStrings->cItems == 1)
5542 RTPrintf("%s %#06x: %.*Rhxs\n", pThis->szPrefix, off, cbNow, &pchContent[off]);
5543 else
5544 RTPrintf("%s plist[%u]: %#06x: %.*Rhxs\n", pThis->szPrefix, i, off, cbNow, &pchContent[off]);
5545 }
5546 }
5547 }
5548 break;
5549
5550 case RTCRPKCS7ATTRIBUTETYPE_INVALID:
5551 RTPrintf("%sINVALID!\n", pThis->szPrefix);
5552 break;
5553 case RTCRPKCS7ATTRIBUTETYPE_NOT_PRESENT:
5554 RTPrintf("%sNOT PRESENT!\n", pThis->szPrefix);
5555 break;
5556 default:
5557 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pAttr->enmType);
5558 break;
5559 }
5560 return rc;
5561}
5562
5563
5564/**
5565 * Displays a SignerInfo structure.
5566 *
5567 * @returns IPRT status code.
5568 * @param pThis The show exe instance data.
5569 * @param offPrefix The current prefix offset.
5570 * @param pSignerInfo The structure to display.
5571 */
5572static int HandleShowExeWorkerPkcs7DisplaySignerInfo(PSHOWEXEPKCS7 pThis, size_t offPrefix, PCRTCRPKCS7SIGNERINFO pSignerInfo)
5573{
5574 int rc = RTAsn1Integer_ToString(&pSignerInfo->IssuerAndSerialNumber.SerialNumber,
5575 pThis->szTmp, sizeof(pThis->szTmp), 0 /*fFlags*/, NULL);
5576 if (RT_FAILURE(rc))
5577 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
5578 RTPrintf("%s Serial No: %s\n", pThis->szPrefix, pThis->szTmp);
5579
5580 rc = RTCrX509Name_FormatAsString(&pSignerInfo->IssuerAndSerialNumber.Name, pThis->szTmp, sizeof(pThis->szTmp), NULL);
5581 if (RT_FAILURE(rc))
5582 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc);
5583 RTPrintf("%s Issuer: %s\n", pThis->szPrefix, pThis->szTmp);
5584
5585 const char *pszType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_GetDigestType(&pSignerInfo->DigestAlgorithm,
5586 true /*fPureDigestsOnly*/));
5587 if (!pszType)
5588 pszType = pSignerInfo->DigestAlgorithm.Algorithm.szObjId;
5589 RTPrintf("%s Digest Algorithm: %s", pThis->szPrefix, pszType);
5590 if (pThis->cVerbosity > 1)
5591 RTPrintf(" (%s)\n", pSignerInfo->DigestAlgorithm.Algorithm.szObjId);
5592 else
5593 RTPrintf("\n");
5594
5595 HandleShowExeWorkerDisplayObjId(pThis, &pSignerInfo->DigestEncryptionAlgorithm.Algorithm,
5596 "Digest Encryption Algorithm: ", "\n");
5597
5598 if (pSignerInfo->AuthenticatedAttributes.cItems == 0)
5599 RTPrintf("%s Authenticated Attributes: none\n", pThis->szPrefix);
5600 else
5601 {
5602 RTPrintf("%s Authenticated Attributes: %u item%s\n", pThis->szPrefix,
5603 pSignerInfo->AuthenticatedAttributes.cItems, pSignerInfo->AuthenticatedAttributes.cItems > 1 ? "s" : "");
5604 for (unsigned j = 0; j < pSignerInfo->AuthenticatedAttributes.cItems; j++)
5605 {
5606 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->AuthenticatedAttributes.papItems[j];
5607 size_t offPrefix3 = offPrefix+ RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix,
5608 " AuthAttrib[%u]: ", j);
5609 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
5610 }
5611 pThis->szPrefix[offPrefix] = '\0';
5612 }
5613
5614 if (pSignerInfo->UnauthenticatedAttributes.cItems == 0)
5615 RTPrintf("%s Unauthenticated Attributes: none\n", pThis->szPrefix);
5616 else
5617 {
5618 RTPrintf("%s Unauthenticated Attributes: %u item%s\n", pThis->szPrefix,
5619 pSignerInfo->UnauthenticatedAttributes.cItems, pSignerInfo->UnauthenticatedAttributes.cItems > 1 ? "s" : "");
5620 for (unsigned j = 0; j < pSignerInfo->UnauthenticatedAttributes.cItems; j++)
5621 {
5622 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[j];
5623 size_t offPrefix3 = offPrefix + RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix,
5624 " UnauthAttrib[%u]: ", j);
5625 HandleShowExeWorkerPkcs7DisplayAttrib(pThis, offPrefix3, pAttr);
5626 }
5627 pThis->szPrefix[offPrefix] = '\0';
5628 }
5629
5630 /** @todo show the encrypted stuff (EncryptedDigest)? */
5631 return rc;
5632}
5633
5634
5635/**
5636 * Displays a Microsoft SPC indirect data structure.
5637 *
5638 * @returns IPRT status code.
5639 * @param pThis The show exe instance data.
5640 * @param offPrefix The current prefix offset.
5641 * @param pIndData The indirect data to display.
5642 */
5643static int HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(PSHOWEXEPKCS7 pThis, size_t offPrefix,
5644 PCRTCRSPCINDIRECTDATACONTENT pIndData)
5645{
5646 /*
5647 * The image hash.
5648 */
5649 RTDIGESTTYPE const enmDigestType = RTCrX509AlgorithmIdentifier_GetDigestType(&pIndData->DigestInfo.DigestAlgorithm,
5650 true /*fPureDigestsOnly*/);
5651 const char *pszDigestType = RTCrDigestTypeToName(enmDigestType);
5652 RTPrintf("%s Digest Type: %s", pThis->szPrefix, pszDigestType);
5653 if (pThis->cVerbosity > 1)
5654 RTPrintf(" (%s)\n", pIndData->DigestInfo.DigestAlgorithm.Algorithm.szObjId);
5655 else
5656 RTPrintf("\n");
5657 RTPrintf("%s Digest: %.*Rhxs\n",
5658 pThis->szPrefix, pIndData->DigestInfo.Digest.Asn1Core.cb, pIndData->DigestInfo.Digest.Asn1Core.uData.pu8);
5659
5660 /*
5661 * The data/file/url.
5662 */
5663 switch (pIndData->Data.enmType)
5664 {
5665 case RTCRSPCAAOVTYPE_PE_IMAGE_DATA:
5666 {
5667 RTPrintf("%s Data Type: PE Image Data\n", pThis->szPrefix);
5668 PRTCRSPCPEIMAGEDATA pPeImage = pIndData->Data.uValue.pPeImage;
5669 /** @todo display "Flags". */
5670
5671 switch (pPeImage->T0.File.enmChoice)
5672 {
5673 case RTCRSPCLINKCHOICE_MONIKER:
5674 {
5675 PRTCRSPCSERIALIZEDOBJECT pMoniker = pPeImage->T0.File.u.pMoniker;
5676 if (RTCrSpcSerializedObject_IsPresent(pMoniker))
5677 {
5678 if (RTUuidCompareStr(pMoniker->Uuid.Asn1Core.uData.pUuid, RTCRSPCSERIALIZEDOBJECT_UUID_STR) == 0)
5679 {
5680 RTPrintf("%s Moniker: SpcSerializedObject (%RTuuid)\n",
5681 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
5682
5683 PCRTCRSPCSERIALIZEDOBJECTATTRIBUTES pData = pMoniker->u.pData;
5684 if (pData)
5685 for (uint32_t i = 0; i < pData->cItems; i++)
5686 {
5687 RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix,
5688 "MonikerAttrib[%u]: ", i);
5689
5690 switch (pData->papItems[i]->enmType)
5691 {
5692 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V2:
5693 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1:
5694 {
5695 PCRTCRSPCSERIALIZEDPAGEHASHES pPgHashes = pData->papItems[i]->u.pPageHashes;
5696 uint32_t const cbHash = pData->papItems[i]->enmType
5697 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1
5698 ? 160/8 /*SHA-1*/ : 256/8 /*SHA-256*/;
5699 uint32_t const cPages = pPgHashes->RawData.Asn1Core.cb / (cbHash + sizeof(uint32_t));
5700
5701 RTPrintf("%sPage Hashes version %u - %u pages (%u bytes total)\n", pThis->szPrefix,
5702 pData->papItems[i]->enmType
5703 == RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_PAGE_HASHES_V1 ? 1 : 2,
5704 cPages, pPgHashes->RawData.Asn1Core.cb);
5705 if (pThis->cVerbosity > 0)
5706 {
5707 PCRTCRSPCPEIMAGEPAGEHASHES pPg = pPgHashes->pData;
5708 for (unsigned iPg = 0; iPg < cPages; iPg++)
5709 {
5710 uint32_t offHash = 0;
5711 do
5712 {
5713 if (offHash == 0)
5714 RTPrintf("%.*s Page#%04u/%#08x: ",
5715 offPrefix, pThis->szPrefix, iPg, pPg->Generic.offFile);
5716 else
5717 RTPrintf("%.*s ", offPrefix, pThis->szPrefix);
5718 uint32_t cbLeft = cbHash - offHash;
5719 if (cbLeft > 24)
5720 cbLeft = 16;
5721 RTPrintf("%.*Rhxs\n", cbLeft, &pPg->Generic.abHash[offHash]);
5722 offHash += cbLeft;
5723 } while (offHash < cbHash);
5724 pPg = (PCRTCRSPCPEIMAGEPAGEHASHES)&pPg->Generic.abHash[cbHash];
5725 }
5726
5727 if (pThis->cVerbosity > 3)
5728 RTPrintf("%.*Rhxd\n",
5729 pPgHashes->RawData.Asn1Core.cb,
5730 pPgHashes->RawData.Asn1Core.uData.pu8);
5731 }
5732 break;
5733 }
5734
5735 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_UNKNOWN:
5736 HandleShowExeWorkerDisplayObjIdSimple(pThis, &pData->papItems[i]->Type, "\n");
5737 break;
5738 case RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE_NOT_PRESENT:
5739 RTPrintf("%sNot present!\n", pThis->szPrefix);
5740 break;
5741 default:
5742 RTPrintf("%senmType=%d!\n", pThis->szPrefix, pData->papItems[i]->enmType);
5743 break;
5744 }
5745 pThis->szPrefix[offPrefix] = '\0';
5746 }
5747 else
5748 RTPrintf("%s pData is NULL!\n", pThis->szPrefix);
5749 }
5750 else
5751 RTPrintf("%s Moniker: Unknown UUID: %RTuuid\n",
5752 pThis->szPrefix, pMoniker->Uuid.Asn1Core.uData.pUuid);
5753 }
5754 else
5755 RTPrintf("%s Moniker: not present\n", pThis->szPrefix);
5756 break;
5757 }
5758
5759 case RTCRSPCLINKCHOICE_URL:
5760 {
5761 const char *pszUrl = NULL;
5762 int rc = pPeImage->T0.File.u.pUrl
5763 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pUrl, &pszUrl, NULL)
5764 : VERR_NOT_FOUND;
5765 if (RT_SUCCESS(rc))
5766 RTPrintf("%s URL: '%s'\n", pThis->szPrefix, pszUrl);
5767 else
5768 RTPrintf("%s URL: rc=%Rrc\n", pThis->szPrefix, rc);
5769 break;
5770 }
5771
5772 case RTCRSPCLINKCHOICE_FILE:
5773 {
5774 const char *pszFile = NULL;
5775 int rc = pPeImage->T0.File.u.pT2 && pPeImage->T0.File.u.pT2->File.u.pAscii
5776 ? RTAsn1String_QueryUtf8(pPeImage->T0.File.u.pT2->File.u.pAscii, &pszFile, NULL)
5777 : VERR_NOT_FOUND;
5778 if (RT_SUCCESS(rc))
5779 RTPrintf("%s File: '%s'\n", pThis->szPrefix, pszFile);
5780 else
5781 RTPrintf("%s File: rc=%Rrc\n", pThis->szPrefix, rc);
5782 if (pThis->cVerbosity > 4 && pPeImage->T0.File.u.pT2 == NULL)
5783 RTPrintf("%s pT2=NULL\n", pThis->szPrefix);
5784 else if (pThis->cVerbosity > 4)
5785 {
5786 PCRTASN1STRING pStr = pPeImage->T0.File.u.pT2->File.u.pAscii;
5787 RTPrintf("%s pT2=%p/%p LB %#x fFlags=%#x pOps=%p (%s)\n"
5788 "%s enmChoice=%d pStr=%p/%p LB %#x fFlags=%#x\n",
5789 pThis->szPrefix,
5790 pPeImage->T0.File.u.pT2,
5791 pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.uData.pu8,
5792 pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.cb,
5793 pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.fFlags,
5794 pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.pOps,
5795 pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.pOps
5796 ? pPeImage->T0.File.u.pT2->CtxTag2.Asn1Core.pOps->pszName : "",
5797 pThis->szPrefix,
5798 pPeImage->T0.File.u.pT2->File.enmChoice,
5799 pStr,
5800 pStr ? pStr->Asn1Core.uData.pu8 : NULL,
5801 pStr ? pStr->Asn1Core.cb : 0,
5802 pStr ? pStr->Asn1Core.fFlags : 0);
5803 }
5804 break;
5805 }
5806
5807 case RTCRSPCLINKCHOICE_NOT_PRESENT:
5808 RTPrintf("%s File not present!\n", pThis->szPrefix);
5809 break;
5810 default:
5811 RTPrintf("%s enmChoice=%d!\n", pThis->szPrefix, pPeImage->T0.File.enmChoice);
5812 break;
5813 }
5814 break;
5815 }
5816
5817 case RTCRSPCAAOVTYPE_UNKNOWN:
5818 HandleShowExeWorkerDisplayObjId(pThis, &pIndData->Data.Type, " Data Type: ", "\n");
5819 break;
5820 case RTCRSPCAAOVTYPE_NOT_PRESENT:
5821 RTPrintf("%s Data Type: Not present!\n", pThis->szPrefix);
5822 break;
5823 default:
5824 RTPrintf("%s Data Type: enmType=%d!\n", pThis->szPrefix, pIndData->Data.enmType);
5825 break;
5826 }
5827
5828 return VINF_SUCCESS;
5829}
5830
5831
5832/**
5833 * Display an PKCS#7 signed data instance.
5834 *
5835 * @returns IPRT status code.
5836 * @param pThis The show exe instance data.
5837 * @param pSignedData The signed data to display.
5838 * @param offPrefix The current prefix offset.
5839 * @param pContentInfo The content info structure (for the size).
5840 */
5841static int HandleShowExeWorkerPkcs7Display(PSHOWEXEPKCS7 pThis, PRTCRPKCS7SIGNEDDATA pSignedData, size_t offPrefix,
5842 PCRTCRPKCS7CONTENTINFO pContentInfo)
5843{
5844 pThis->szPrefix[offPrefix] = '\0';
5845 RTPrintf("%sPKCS#7 signature: %u (%#x) bytes\n", pThis->szPrefix,
5846 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core),
5847 RTASN1CORE_GET_RAW_ASN1_SIZE(&pContentInfo->SeqCore.Asn1Core));
5848
5849 /*
5850 * Display list of signing algorithms.
5851 */
5852 RTPrintf("%sDigestAlgorithms: ", pThis->szPrefix);
5853 if (pSignedData->DigestAlgorithms.cItems == 0)
5854 RTPrintf("none");
5855 for (unsigned i = 0; i < pSignedData->DigestAlgorithms.cItems; i++)
5856 {
5857 PCRTCRX509ALGORITHMIDENTIFIER pAlgoId = pSignedData->DigestAlgorithms.papItems[i];
5858 const char *pszDigestType = RTCrDigestTypeToName(RTCrX509AlgorithmIdentifier_GetDigestType(pAlgoId,
5859 true /*fPureDigestsOnly*/));
5860 if (!pszDigestType)
5861 pszDigestType = pAlgoId->Algorithm.szObjId;
5862 RTPrintf(i == 0 ? "%s" : ", %s", pszDigestType);
5863 if (pThis->cVerbosity > 1)
5864 RTPrintf(" (%s)", pAlgoId->Algorithm.szObjId);
5865 }
5866 RTPrintf("\n");
5867
5868 /*
5869 * Display the signed data content.
5870 */
5871 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCRSPCINDIRECTDATACONTENT_OID) == 0)
5872 {
5873 RTPrintf("%s ContentType: SpcIndirectDataContent (" RTCRSPCINDIRECTDATACONTENT_OID ")\n", pThis->szPrefix);
5874 size_t offPrefix2 = RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, " SPC Ind Data: ");
5875 HandleShowExeWorkerPkcs7DisplaySpcIdirectDataContent(pThis, offPrefix2 + offPrefix,
5876 pSignedData->ContentInfo.u.pIndirectDataContent);
5877 pThis->szPrefix[offPrefix] = '\0';
5878 }
5879 else
5880 {
5881 HandleShowExeWorkerDisplayObjId(pThis, &pSignedData->ContentInfo.ContentType, " ContentType: ", " - not implemented.\n");
5882 RTPrintf("%s %u (%#x) bytes\n", pThis->szPrefix,
5883 pSignedData->ContentInfo.Content.Asn1Core.cb, pSignedData->ContentInfo.Content.Asn1Core.cb);
5884 }
5885
5886 /*
5887 * Display certificates (Certificates).
5888 */
5889 if (pSignedData->Certificates.cItems > 0)
5890 {
5891 RTPrintf("%s Certificates: %u\n", pThis->szPrefix, pSignedData->Certificates.cItems);
5892 for (uint32_t i = 0; i < pSignedData->Certificates.cItems; i++)
5893 {
5894 PCRTCRPKCS7CERT pCert = pSignedData->Certificates.papItems[i];
5895 if (i != 0 && pThis->cVerbosity >= 2)
5896 RTPrintf("\n");
5897 switch (pCert->enmChoice)
5898 {
5899 case RTCRPKCS7CERTCHOICE_X509:
5900 {
5901 PCRTCRX509CERTIFICATE pX509Cert = pCert->u.pX509Cert;
5902 int rc2 = RTAsn1QueryObjIdName(&pX509Cert->SignatureAlgorithm.Algorithm, pThis->szTmp, sizeof(pThis->szTmp));
5903 RTPrintf("%s Certificate #%u: %s\n", pThis->szPrefix, i,
5904 RT_SUCCESS(rc2) ? pThis->szTmp : pX509Cert->SignatureAlgorithm.Algorithm.szObjId);
5905
5906 rc2 = RTCrX509Name_FormatAsString(&pX509Cert->TbsCertificate.Subject,
5907 pThis->szTmp, sizeof(pThis->szTmp), NULL);
5908 if (RT_FAILURE(rc2))
5909 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc2);
5910 RTPrintf("%s Subject: %s\n", pThis->szPrefix, pThis->szTmp);
5911
5912 rc2 = RTCrX509Name_FormatAsString(&pX509Cert->TbsCertificate.Issuer,
5913 pThis->szTmp, sizeof(pThis->szTmp), NULL);
5914 if (RT_FAILURE(rc2))
5915 RTStrPrintf(pThis->szTmp, sizeof(pThis->szTmp), "%Rrc", rc2);
5916 RTPrintf("%s Issuer: %s\n", pThis->szPrefix, pThis->szTmp);
5917
5918
5919 char szNotAfter[RTTIME_STR_LEN];
5920 RTPrintf("%s Valid: %s thru %s\n", pThis->szPrefix,
5921 RTTimeToString(&pX509Cert->TbsCertificate.Validity.NotBefore.Time,
5922 pThis->szTmp, sizeof(pThis->szTmp)),
5923 RTTimeToString(&pX509Cert->TbsCertificate.Validity.NotAfter.Time,
5924 szNotAfter, sizeof(szNotAfter)));
5925 break;
5926 }
5927
5928 default:
5929 RTPrintf("%s Certificate #%u: Unsupported type\n", pThis->szPrefix, i);
5930 break;
5931 }
5932
5933
5934 if (pThis->cVerbosity >= 2)
5935 RTAsn1Dump(RTCrPkcs7Cert_GetAsn1Core(pSignedData->Certificates.papItems[i]), 0,
5936 ((uint32_t)offPrefix + 9) / 2, RTStrmDumpPrintfV, g_pStdOut);
5937 }
5938
5939 /** @todo display certificates properly. */
5940 }
5941
5942 if (pSignedData->Crls.cb > 0)
5943 RTPrintf("%s CRLs: %u bytes\n", pThis->szPrefix, pSignedData->Crls.cb);
5944
5945 /*
5946 * Show signatures (SignerInfos).
5947 */
5948 unsigned const cSigInfos = pSignedData->SignerInfos.cItems;
5949 if (cSigInfos != 1)
5950 RTPrintf("%s SignerInfos: %u signers\n", pThis->szPrefix, cSigInfos);
5951 else
5952 RTPrintf("%s SignerInfos:\n", pThis->szPrefix);
5953 int rc = VINF_SUCCESS;
5954 for (unsigned i = 0; i < cSigInfos; i++)
5955 {
5956 size_t offPrefix2 = offPrefix;
5957 if (cSigInfos != 1)
5958 offPrefix2 += RTStrPrintf(&pThis->szPrefix[offPrefix], sizeof(pThis->szPrefix) - offPrefix, "SignerInfo[%u]: ", i);
5959
5960 int rc2 = HandleShowExeWorkerPkcs7DisplaySignerInfo(pThis, offPrefix2, pSignedData->SignerInfos.papItems[i]);
5961 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
5962 rc = rc2;
5963 }
5964 pThis->szPrefix[offPrefix] = '\0';
5965
5966 return rc;
5967}
5968
5969
5970/*
5971 * The 'show-exe' command.
5972 */
5973static RTEXITCODE HelpShowExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
5974{
5975 RT_NOREF_PV(enmLevel);
5976 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT, "show-exe [--verbose|-v] [--quiet|-q] <exe1> [exe2 [..]]\n");
5977 return RTEXITCODE_SUCCESS;
5978}
5979
5980
5981static RTEXITCODE HandleShowExe(int cArgs, char **papszArgs)
5982{
5983 /*
5984 * Parse arguments.
5985 */
5986 static const RTGETOPTDEF s_aOptions[] =
5987 {
5988 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
5989 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
5990 };
5991
5992 unsigned cVerbosity = 0;
5993 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
5994
5995 RTGETOPTSTATE GetState;
5996 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
5997 AssertRCReturn(rc, RTEXITCODE_FAILURE);
5998 RTGETOPTUNION ValueUnion;
5999 int ch;
6000 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
6001 {
6002 switch (ch)
6003 {
6004 case 'v': cVerbosity++; break;
6005 case 'q': cVerbosity = 0; break;
6006 case 'V': return HandleVersion(cArgs, papszArgs);
6007 case 'h': return HelpShowExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
6008 default: return RTGetOptPrintError(ch, &ValueUnion);
6009 }
6010 }
6011 if (ch != VINF_GETOPT_NOT_OPTION)
6012 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
6013
6014 /*
6015 * Do it.
6016 */
6017 unsigned iFile = 0;
6018 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
6019 do
6020 {
6021 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
6022
6023 SHOWEXEPKCS7 This;
6024 RT_ZERO(This);
6025 This.cVerbosity = cVerbosity;
6026
6027 RTEXITCODE rcExitThis = SignToolPkcs7Exe_InitFromFile(&This, ValueUnion.psz, cVerbosity, enmLdrArch);
6028 if (rcExitThis == RTEXITCODE_SUCCESS)
6029 {
6030 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
6031 if (RT_FAILURE(rc))
6032 rcExit = RTEXITCODE_FAILURE;
6033 SignToolPkcs7Exe_Delete(&This);
6034 }
6035 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
6036 rcExit = rcExitThis;
6037
6038 iFile++;
6039 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
6040 if (ch != 0)
6041 return RTGetOptPrintError(ch, &ValueUnion);
6042
6043 return rcExit;
6044}
6045
6046
6047/*
6048 * The 'show-cat' command.
6049 */
6050static RTEXITCODE HelpShowCat(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6051{
6052 RT_NOREF_PV(enmLevel);
6053 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT, "show-cat [--verbose|-v] [--quiet|-q] <cat1> [cat2 [..]]\n");
6054 return RTEXITCODE_SUCCESS;
6055}
6056
6057
6058static RTEXITCODE HandleShowCat(int cArgs, char **papszArgs)
6059{
6060 /*
6061 * Parse arguments.
6062 */
6063 static const RTGETOPTDEF s_aOptions[] =
6064 {
6065 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
6066 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
6067 };
6068
6069 unsigned cVerbosity = 0;
6070
6071 RTGETOPTSTATE GetState;
6072 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
6073 AssertRCReturn(rc, RTEXITCODE_FAILURE);
6074 RTGETOPTUNION ValueUnion;
6075 int ch;
6076 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
6077 {
6078 switch (ch)
6079 {
6080 case 'v': cVerbosity++; break;
6081 case 'q': cVerbosity = 0; break;
6082 case 'V': return HandleVersion(cArgs, papszArgs);
6083 case 'h': return HelpShowCat(g_pStdOut, RTSIGNTOOLHELP_FULL);
6084 default: return RTGetOptPrintError(ch, &ValueUnion);
6085 }
6086 }
6087 if (ch != VINF_GETOPT_NOT_OPTION)
6088 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
6089
6090 /*
6091 * Do it.
6092 */
6093 unsigned iFile = 0;
6094 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
6095 do
6096 {
6097 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
6098
6099 SHOWEXEPKCS7 This;
6100 RT_ZERO(This);
6101 This.cVerbosity = cVerbosity;
6102
6103 RTEXITCODE rcExitThis = SignToolPkcs7_InitFromFile(&This, ValueUnion.psz, cVerbosity);
6104 if (rcExitThis == RTEXITCODE_SUCCESS)
6105 {
6106 This.hLdrMod = NIL_RTLDRMOD;
6107
6108 rc = HandleShowExeWorkerPkcs7Display(&This, This.pSignedData, 0, &This.ContentInfo);
6109 if (RT_FAILURE(rc))
6110 rcExit = RTEXITCODE_FAILURE;
6111 SignToolPkcs7Exe_Delete(&This);
6112 }
6113 if (rcExitThis != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
6114 rcExit = rcExitThis;
6115
6116 iFile++;
6117 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
6118 if (ch != 0)
6119 return RTGetOptPrintError(ch, &ValueUnion);
6120
6121 return rcExit;
6122}
6123
6124
6125/*********************************************************************************************************************************
6126* The 'hash-exe' command. *
6127*********************************************************************************************************************************/
6128static RTEXITCODE HelpHashExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6129{
6130 RT_NOREF_PV(enmLevel);
6131 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT, "hash-exe [--verbose|-v] [--quiet|-q] <exe1> [exe2 [..]]\n");
6132 return RTEXITCODE_SUCCESS;
6133}
6134
6135
6136static RTEXITCODE HandleHashExe(int cArgs, char **papszArgs)
6137{
6138 /*
6139 * Parse arguments.
6140 */
6141 static const RTGETOPTDEF s_aOptions[] =
6142 {
6143 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
6144 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
6145 };
6146
6147 unsigned cVerbosity = 0;
6148 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
6149
6150 RTGETOPTSTATE GetState;
6151 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
6152 AssertRCReturn(rc, RTEXITCODE_FAILURE);
6153 RTGETOPTUNION ValueUnion;
6154 int ch;
6155 while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
6156 {
6157 switch (ch)
6158 {
6159 case 'v': cVerbosity++; break;
6160 case 'q': cVerbosity = 0; break;
6161 case 'V': return HandleVersion(cArgs, papszArgs);
6162 case 'h': return HelpHashExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
6163 default: return RTGetOptPrintError(ch, &ValueUnion);
6164 }
6165 }
6166 if (ch != VINF_GETOPT_NOT_OPTION)
6167 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
6168
6169 /*
6170 * Do it.
6171 */
6172 unsigned iFile = 0;
6173 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
6174 do
6175 {
6176 RTPrintf(iFile == 0 ? "%s:\n" : "\n%s:\n", ValueUnion.psz);
6177
6178 RTERRINFOSTATIC ErrInfo;
6179 RTLDRMOD hLdrMod;
6180 rc = RTLdrOpenEx(ValueUnion.psz, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod, RTErrInfoInitStatic(&ErrInfo));
6181 if (RT_SUCCESS(rc))
6182 {
6183 uint8_t abHash[RTSHA512_HASH_SIZE];
6184 char szDigest[RTSHA512_DIGEST_LEN + 1];
6185
6186 /* SHA-1: */
6187 rc = RTLdrHashImage(hLdrMod, RTDIGESTTYPE_SHA1, abHash, sizeof(abHash));
6188 if (RT_SUCCESS(rc))
6189 RTSha1ToString(abHash, szDigest, sizeof(szDigest));
6190 else
6191 RTStrPrintf(szDigest, sizeof(szDigest), "%Rrc", rc);
6192 RTPrintf(" SHA-1: %s\n", szDigest);
6193
6194 /* SHA-256: */
6195 rc = RTLdrHashImage(hLdrMod, RTDIGESTTYPE_SHA256, abHash, sizeof(abHash));
6196 if (RT_SUCCESS(rc))
6197 RTSha256ToString(abHash, szDigest, sizeof(szDigest));
6198 else
6199 RTStrPrintf(szDigest, sizeof(szDigest), "%Rrc", rc);
6200 RTPrintf(" SHA-256: %s\n", szDigest);
6201
6202 /* SHA-512: */
6203 rc = RTLdrHashImage(hLdrMod, RTDIGESTTYPE_SHA512, abHash, sizeof(abHash));
6204 if (RT_SUCCESS(rc))
6205 RTSha512ToString(abHash, szDigest, sizeof(szDigest));
6206 else
6207 RTStrPrintf(szDigest, sizeof(szDigest), "%Rrc", rc);
6208 RTPrintf(" SHA-512: %s\n", szDigest);
6209
6210 RTLdrClose(hLdrMod);
6211 }
6212 else
6213 rcExit = RTMsgErrorExitFailure("Failed to open '%s': %Rrc%#RTeim", ValueUnion.psz, rc, &ErrInfo.Core);
6214
6215 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) == VINF_GETOPT_NOT_OPTION);
6216 if (ch != 0)
6217 return RTGetOptPrintError(ch, &ValueUnion);
6218
6219 return rcExit;
6220}
6221
6222
6223/*********************************************************************************************************************************
6224* The 'make-tainfo' command. *
6225*********************************************************************************************************************************/
6226static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6227{
6228 RT_NOREF_PV(enmLevel);
6229 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
6230 "make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
6231 return RTEXITCODE_SUCCESS;
6232}
6233
6234
6235typedef struct MAKETAINFOSTATE
6236{
6237 int cVerbose;
6238 const char *pszCert;
6239 const char *pszOutput;
6240} MAKETAINFOSTATE;
6241
6242
6243/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
6244static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
6245{
6246 RT_NOREF_PV(pErrInfo);
6247 return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
6248}
6249
6250
6251static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
6252{
6253 /*
6254 * Parse arguments.
6255 */
6256 static const RTGETOPTDEF s_aOptions[] =
6257 {
6258 { "--cert", 'c', RTGETOPT_REQ_STRING },
6259 { "--output", 'o', RTGETOPT_REQ_STRING },
6260 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
6261 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
6262 };
6263
6264 MAKETAINFOSTATE State = { 0, NULL, NULL };
6265
6266 RTGETOPTSTATE GetState;
6267 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
6268 AssertRCReturn(rc, RTEXITCODE_FAILURE);
6269 RTGETOPTUNION ValueUnion;
6270 int ch;
6271 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
6272 {
6273 switch (ch)
6274 {
6275 case 'c':
6276 if (State.pszCert)
6277 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
6278 State.pszCert = ValueUnion.psz;
6279 break;
6280
6281 case 'o':
6282 case VINF_GETOPT_NOT_OPTION:
6283 if (State.pszOutput)
6284 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
6285 State.pszOutput = ValueUnion.psz;
6286 break;
6287
6288 case 'v': State.cVerbose++; break;
6289 case 'q': State.cVerbose = 0; break;
6290 case 'V': return HandleVersion(cArgs, papszArgs);
6291 case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
6292 default: return RTGetOptPrintError(ch, &ValueUnion);
6293 }
6294 }
6295 if (!State.pszCert)
6296 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
6297 if (!State.pszOutput)
6298 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
6299
6300 /*
6301 * Read the certificate.
6302 */
6303 RTERRINFOSTATIC StaticErrInfo;
6304 RTCRX509CERTIFICATE Certificate;
6305 rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
6306 RTErrInfoInitStatic(&StaticErrInfo));
6307 if (RT_FAILURE(rc))
6308 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
6309 State.pszCert, rc, StaticErrInfo.szMsg);
6310 /*
6311 * Construct the trust anchor information.
6312 */
6313 RTCRTAFTRUSTANCHORINFO TrustAnchor;
6314 rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
6315 if (RT_SUCCESS(rc))
6316 {
6317 /* Public key. */
6318 Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
6319 RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
6320 rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
6321 &g_RTAsn1DefaultAllocator);
6322 if (RT_FAILURE(rc))
6323 RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
6324 RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
6325
6326 /* Key Identifier. */
6327 PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
6328 if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
6329 pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
6330 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
6331 && RTCrX509Certificate_IsSelfSigned(&Certificate)
6332 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
6333 pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
6334 else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
6335 && RTCrX509Certificate_IsSelfSigned(&Certificate)
6336 && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
6337 pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
6338 if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
6339 {
6340 Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
6341 RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
6342 rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
6343 if (RT_FAILURE(rc))
6344 RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
6345 RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
6346 }
6347 else
6348 RTMsgWarning("No key identifier found or has zero length.");
6349
6350 /* Subject */
6351 if (RT_SUCCESS(rc))
6352 {
6353 Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
6354 rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
6355 if (RT_SUCCESS(rc))
6356 {
6357 Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
6358 RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
6359 rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
6360 &g_RTAsn1DefaultAllocator);
6361 if (RT_SUCCESS(rc))
6362 {
6363 RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
6364 rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
6365 if (RT_FAILURE(rc))
6366 RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
6367 }
6368 else
6369 RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
6370 }
6371 else
6372 RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
6373 }
6374
6375 /* Check that what we've constructed makes some sense. */
6376 if (RT_SUCCESS(rc))
6377 {
6378 rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
6379 if (RT_FAILURE(rc))
6380 RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
6381 }
6382
6383 if (RT_SUCCESS(rc))
6384 {
6385 /*
6386 * Encode it and write it to the output file.
6387 */
6388 uint32_t cbEncoded;
6389 rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
6390 RTErrInfoInitStatic(&StaticErrInfo));
6391 if (RT_SUCCESS(rc))
6392 {
6393 if (State.cVerbose >= 1)
6394 RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
6395
6396 PRTSTREAM pStrm;
6397 rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
6398 if (RT_SUCCESS(rc))
6399 {
6400 rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
6401 handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
6402 if (RT_SUCCESS(rc))
6403 {
6404 rc = RTStrmClose(pStrm);
6405 if (RT_SUCCESS(rc))
6406 RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
6407 else
6408 RTMsgError("RTStrmClose failed: %Rrc", rc);
6409 }
6410 else
6411 {
6412 RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
6413 RTStrmClose(pStrm);
6414 }
6415 }
6416 else
6417 RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
6418 }
6419 else
6420 RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
6421 }
6422
6423 RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
6424 }
6425 else
6426 RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
6427
6428 RTCrX509Certificate_Delete(&Certificate);
6429 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
6430}
6431
6432
6433
6434/*********************************************************************************************************************************
6435* The 'create-self-signed-rsa-cert' command. *
6436*********************************************************************************************************************************/
6437#ifndef IPRT_IN_BUILD_TOOL
6438
6439static RTEXITCODE HelpCreateSelfSignedRsaCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6440{
6441 RT_NOREF_PV(enmLevel);
6442 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
6443 "create-self-signed-rsa-cert [--verbose|--quiet] [--key-bits <count>] [--digest <hash>] [--out-cert=]<certificate-file.pem> [--out-pkey=]<private-key-file.pem>\n");
6444 return RTEXITCODE_SUCCESS;
6445}
6446
6447
6448static RTDIGESTTYPE DigestTypeStringToValue(const char *pszType)
6449{
6450 for (int iType = RTDIGESTTYPE_INVALID + 1; iType < RTDIGESTTYPE_END; iType++)
6451 if (iType != RTDIGESTTYPE_UNKNOWN)
6452 {
6453 const char * const pszName = RTCrDigestTypeToName((RTDIGESTTYPE)iType);
6454 size_t offType = 0;
6455 size_t offName = 0;
6456 for (;;)
6457 {
6458 char chType = RT_C_TO_UPPER(pszType[offType]);
6459 char chName = RT_C_TO_UPPER(pszName[offType]);
6460 if (chType != chName)
6461 {
6462 /* allow 'sha1' as well as 'sha-1' */
6463 if (chName != '-')
6464 break;
6465 chName = pszName[++offName];
6466 chName = RT_C_TO_UPPER(chName);
6467 if (chType != chName)
6468 break;
6469 }
6470 if (chType == '\0')
6471 return (RTDIGESTTYPE)iType;
6472 }
6473 }
6474 return RTDIGESTTYPE_INVALID;
6475}
6476
6477
6478static RTEXITCODE HandleCreateSelfSignedRsaCert(int cArgs, char **papszArgs)
6479{
6480 /*
6481 * Parse arguments.
6482 */
6483 static const RTGETOPTDEF s_aOptions[] =
6484 {
6485 { "--digest", 'd', RTGETOPT_REQ_STRING },
6486 { "--bits", 'b', RTGETOPT_REQ_UINT32 },
6487 { "--key-bits", 'b', RTGETOPT_REQ_UINT32 },
6488 { "--days", 'D', RTGETOPT_REQ_UINT32 },
6489 { "--days", 'D', RTGETOPT_REQ_UINT32 },
6490 { "--out-cert", 'c', RTGETOPT_REQ_UINT32 },
6491 { "--out-certificate", 'c', RTGETOPT_REQ_UINT32 },
6492 { "--out-pkey", 'p', RTGETOPT_REQ_UINT32 },
6493 { "--out-private-key", 'p', RTGETOPT_REQ_UINT32 },
6494 { "--secs", 's', RTGETOPT_REQ_UINT32 },
6495 { "--seconds", 's', RTGETOPT_REQ_UINT32 },
6496 };
6497
6498 RTDIGESTTYPE enmDigestType = RTDIGESTTYPE_SHA384;
6499 uint32_t cKeyBits = 4096;
6500 uint32_t cSecsValidFor = 365 * RT_SEC_1DAY;
6501 uint32_t fKeyUsage = 0;
6502 uint32_t fExtKeyUsage = 0;
6503 const char *pszOutCert = NULL;
6504 const char *pszOutPrivKey = NULL;
6505
6506 RTGETOPTSTATE GetState;
6507 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
6508 AssertRCReturn(rc, RTEXITCODE_FAILURE);
6509 RTGETOPTUNION ValueUnion;
6510 int ch;
6511 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
6512 {
6513 switch (ch)
6514 {
6515 case 'b':
6516 cKeyBits = ValueUnion.u32;
6517 break;
6518
6519 case 'd':
6520 enmDigestType = DigestTypeStringToValue(ValueUnion.psz);
6521 if (enmDigestType == RTDIGESTTYPE_INVALID)
6522 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Unknown digest type: %s", ValueUnion.psz);
6523 break;
6524
6525 case 'D':
6526 cSecsValidFor = ValueUnion.u32 * RT_SEC_1DAY;
6527 if (cSecsValidFor / RT_SEC_1DAY != ValueUnion.u32)
6528 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --days option value is out of range: %u", ValueUnion.u32);
6529 break;
6530
6531 case 'c':
6532 if (pszOutCert)
6533 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --out-cert option can only be used once.");
6534 pszOutCert = ValueUnion.psz;
6535 break;
6536
6537 case 'p':
6538 if (pszOutPrivKey)
6539 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --out-pkey option can only be used once.");
6540 pszOutPrivKey = ValueUnion.psz;
6541 break;
6542
6543 case 's':
6544 cSecsValidFor = ValueUnion.u32;
6545 break;
6546
6547 case VINF_GETOPT_NOT_OPTION:
6548 if (!pszOutCert)
6549 pszOutCert = ValueUnion.psz;
6550 else if (!pszOutPrivKey)
6551 pszOutPrivKey = ValueUnion.psz;
6552 else
6553 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many output files specified: %s", ValueUnion.psz);
6554 break;
6555
6556 case 'V': return HandleVersion(cArgs, papszArgs);
6557 case 'h': return HelpCreateSelfSignedRsaCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
6558 default: return RTGetOptPrintError(ch, &ValueUnion);
6559 }
6560 }
6561 if (!pszOutCert)
6562 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output certificate file name specified.");
6563 if (!pszOutPrivKey)
6564 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output private key file name specified.");
6565
6566 /*
6567 * Do the work.
6568 */
6569 RTERRINFOSTATIC StaticErrInfo;
6570 rc = RTCrX509Certificate_GenerateSelfSignedRsa(enmDigestType, cKeyBits, cSecsValidFor,
6571 fKeyUsage, fExtKeyUsage, NULL /*pvSubjectTodo*/,
6572 pszOutCert, pszOutPrivKey, RTErrInfoInitStatic(&StaticErrInfo));
6573 if (RT_SUCCESS(rc))
6574 {
6575 /*
6576 * Test load it.
6577 */
6578 RTCRX509CERTIFICATE Certificate;
6579 rc = RTCrX509Certificate_ReadFromFile(&Certificate, pszOutCert, RTCRX509CERT_READ_F_PEM_ONLY,
6580 &g_RTAsn1DefaultAllocator, RTErrInfoInitStatic(&StaticErrInfo));
6581 if (RT_FAILURE(rc))
6582 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading the new certificate from %s: %Rrc%#RTeim",
6583 pszOutCert, rc, &StaticErrInfo.Core);
6584 RTCrX509Certificate_Delete(&Certificate);
6585 return RTEXITCODE_SUCCESS;
6586 }
6587
6588 return RTMsgErrorExitFailure("RTCrX509Certificate_GenerateSelfSignedRsa(%d,%u,%u,%s,%s,) failed: %Rrc%#RTeim",
6589 enmDigestType, cKeyBits, cSecsValidFor, pszOutCert, pszOutPrivKey, rc, &StaticErrInfo.Core);
6590}
6591
6592#endif /* !IPRT_IN_BUILD_TOOL */
6593
6594
6595/*
6596 * The 'version' command.
6597 */
6598static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6599{
6600 RT_NOREF_PV(enmLevel);
6601 RTStrmPrintf(pStrm, "version\n");
6602 return RTEXITCODE_SUCCESS;
6603}
6604
6605static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
6606{
6607 RT_NOREF_PV(cArgs); RT_NOREF_PV(papszArgs);
6608#ifndef IN_BLD_PROG /* RTBldCfgVersion or RTBldCfgRevision in build time IPRT lib. */
6609 RTPrintf("%s\n", RTBldCfgVersion());
6610 return RTEXITCODE_SUCCESS;
6611#else
6612 return RTEXITCODE_FAILURE;
6613#endif
6614}
6615
6616
6617
6618/**
6619 * Command mapping.
6620 */
6621static struct
6622{
6623 /** The command. */
6624 const char *pszCmd;
6625 /**
6626 * Handle the command.
6627 * @returns Program exit code.
6628 * @param cArgs Number of arguments.
6629 * @param papszArgs The argument vector, starting with the command name.
6630 */
6631 RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
6632 /**
6633 * Produce help.
6634 * @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
6635 * @param pStrm Where to send help text.
6636 * @param enmLevel The level of the help information.
6637 */
6638 RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
6639}
6640/** Mapping commands to handler and helper functions. */
6641const g_aCommands[] =
6642{
6643 { "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
6644 { "extract-signer-root", HandleExtractSignerRoot, HelpExtractSignerRoot },
6645 { "extract-timestamp-root", HandleExtractTimestampRoot, HelpExtractTimestampRoot },
6646 { "extract-exe-signature", HandleExtractExeSignature, HelpExtractExeSignature },
6647 { "add-nested-exe-signature", HandleAddNestedExeSignature, HelpAddNestedExeSignature },
6648 { "add-nested-cat-signature", HandleAddNestedCatSignature, HelpAddNestedCatSignature },
6649#ifndef IPRT_SIGNTOOL_NO_SIGNING
6650 { "add-timestamp-exe-signature", HandleAddTimestampExeSignature, HelpAddTimestampExeSignature },
6651 { "sign", HandleSign, HelpSign },
6652#endif
6653#ifndef IPRT_IN_BUILD_TOOL
6654 { "verify-exe", HandleVerifyExe, HelpVerifyExe },
6655#endif
6656 { "show-exe", HandleShowExe, HelpShowExe },
6657 { "show-cat", HandleShowCat, HelpShowCat },
6658 { "hash-exe", HandleHashExe, HelpHashExe },
6659 { "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
6660#ifndef IPRT_IN_BUILD_TOOL
6661 { "create-self-signed-rsa-cert", HandleCreateSelfSignedRsaCert, HelpCreateSelfSignedRsaCert },
6662#endif
6663 { "help", HandleHelp, HelpHelp },
6664 { "--help", HandleHelp, NULL },
6665 { "-h", HandleHelp, NULL },
6666 { "version", HandleVersion, HelpVersion },
6667 { "--version", HandleVersion, NULL },
6668 { "-V", HandleVersion, NULL },
6669};
6670
6671
6672/*
6673 * The 'help' command.
6674 */
6675static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
6676{
6677 RT_NOREF_PV(enmLevel);
6678 RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
6679 return RTEXITCODE_SUCCESS;
6680}
6681
6682static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
6683{
6684 PRTSTREAM const pStrm = g_pStdOut;
6685 RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
6686 uint32_t cShowed = 0;
6687 uint32_t cchWidth;
6688 if (RT_FAILURE(RTStrmQueryTerminalWidth(g_pStdOut, &cchWidth)))
6689 cchWidth = 80;
6690
6691 RTStrmPrintf(pStrm,
6692 "Usage: RTSignTool <command> [command-options]\n"
6693 " or: RTSignTool <-V|--version|version>\n"
6694 " or: RTSignTool <-h|--help|help> [command-pattern [..]]\n"
6695 "\n"
6696 );
6697
6698 if (enmLevel == RTSIGNTOOLHELP_USAGE)
6699 RTStrmPrintf(pStrm, "Syntax summary for the RTSignTool commands:\n");
6700
6701 for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
6702 {
6703 if (g_aCommands[iCmd].pfnHelp)
6704 {
6705 bool fShow = false;
6706 if (cArgs <= 1)
6707 fShow = true;
6708 else
6709 for (int iArg = 1; iArg < cArgs; iArg++)
6710 if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
6711 {
6712 fShow = true;
6713 break;
6714 }
6715 if (fShow)
6716 {
6717 if (enmLevel == RTSIGNTOOLHELP_FULL)
6718 RTPrintf("%.*s\n", RT_MIN(cchWidth, 100),
6719 "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
6720 g_aCommands[iCmd].pfnHelp(pStrm, enmLevel);
6721 cShowed++;
6722 }
6723 }
6724 }
6725 return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
6726}
6727
6728
6729
6730int main(int argc, char **argv)
6731{
6732 int rc = RTR3InitExe(argc, &argv, 0);
6733 if (RT_FAILURE(rc))
6734 return RTMsgInitFailure(rc);
6735
6736 /*
6737 * Parse global arguments.
6738 */
6739 int iArg = 1;
6740 /* none presently. */
6741
6742 /*
6743 * Command dispatcher.
6744 */
6745 if (iArg < argc)
6746 {
6747 const char *pszCmd = argv[iArg];
6748 uint32_t i = RT_ELEMENTS(g_aCommands);
6749 while (i-- > 0)
6750 if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
6751 return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
6752 RTMsgError("Unknown command '%s'.", pszCmd);
6753 }
6754 else
6755 RTMsgError("No command given. (try --help)");
6756
6757 return RTEXITCODE_SYNTAX;
6758}
6759
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