VirtualBox

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

Last change on this file since 103914 was 101647, checked in by vboxsync, 13 months ago

IPRT/RTSignTool: Added a --intermediate-certs-from-system/-A option to the extract-signer-root and extract-timestamp-root commands.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 291.5 KB
Line 
1/* $Id: RTSignTool.cpp 101647 2023-10-30 09:34:56Z vboxsync $ */
2/** @file
3 * IPRT - Signing Tool.
4 */
5
6/*
7 * Copyright (C) 2006-2023 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?... ..O...@.0 */
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/**
1589 * Reads and decodes PKCS\#7 signature from the given executable, if it has one.
1590 *
1591 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error message
1592 * on failure.
1593 * @param pThis The structure to initialize.
1594 * @param pszFilename The executable filename.
1595 * @param cVerbosity The verbosity.
1596 * @param enmLdrArch For FAT binaries.
1597 * @param fAllowUnsigned Whether to allow unsigned binaries.
1598 */
1599static RTEXITCODE SignToolPkcs7Exe_InitFromFile(PSIGNTOOLPKCS7EXE pThis, const char *pszFilename, unsigned cVerbosity,
1600 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER, bool fAllowUnsigned = false)
1601{
1602 /*
1603 * Init the return structure.
1604 */
1605 RT_ZERO(*pThis);
1606 pThis->hLdrMod = NIL_RTLDRMOD;
1607 pThis->pszFilename = pszFilename;
1608 pThis->enmType = RTSIGNTOOLFILETYPE_EXE;
1609
1610 /*
1611 * Open the image and check if it's signed.
1612 */
1613 int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, enmLdrArch, &pThis->hLdrMod);
1614 if (RT_SUCCESS(rc))
1615 {
1616 bool fIsSigned = false;
1617 rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_IS_SIGNED, &fIsSigned, sizeof(fIsSigned));
1618 if (RT_SUCCESS(rc) && fIsSigned)
1619 {
1620 /*
1621 * Query the PKCS#7 data (assuming M$ style signing) and hand it to a worker.
1622 */
1623 size_t cbActual = 0;
1624#ifdef DEBUG
1625 size_t cbBuf = 64;
1626#else
1627 size_t cbBuf = _512K;
1628#endif
1629 void *pvBuf = RTMemAllocZ(cbBuf);
1630 if (pvBuf)
1631 {
1632 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbActual);
1633 if (rc == VERR_BUFFER_OVERFLOW)
1634 {
1635 RTMemFree(pvBuf);
1636 cbBuf = cbActual;
1637 pvBuf = RTMemAllocZ(cbActual);
1638 if (pvBuf)
1639 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/,
1640 pvBuf, cbBuf, &cbActual);
1641 else
1642 rc = VERR_NO_MEMORY;
1643 }
1644 }
1645 else
1646 rc = VERR_NO_MEMORY;
1647
1648 pThis->pbBuf = (uint8_t *)pvBuf;
1649 pThis->cbBuf = cbActual;
1650 if (RT_SUCCESS(rc))
1651 {
1652 if (cVerbosity > 2)
1653 RTPrintf("PKCS#7 signature: %u bytes\n", cbActual);
1654 if (cVerbosity > 3)
1655 RTPrintf("%.*Rhxd\n", cbActual, pvBuf);
1656
1657 /*
1658 * Decode it.
1659 */
1660 rc = SignToolPkcs7_Decode(pThis, false /*fCatalog*/);
1661 if (RT_SUCCESS(rc))
1662 return RTEXITCODE_SUCCESS;
1663 }
1664 else
1665 RTMsgError("RTLdrQueryPropEx/RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc\n", pszFilename, rc);
1666 }
1667 else if (RT_SUCCESS(rc))
1668 {
1669 if (!fAllowUnsigned || cVerbosity >= 2)
1670 RTMsgInfo("'%s': not signed\n", pszFilename);
1671 if (fAllowUnsigned)
1672 return RTEXITCODE_SUCCESS;
1673 }
1674 else
1675 RTMsgError("RTLdrQueryProp/RTLDRPROP_IS_SIGNED failed on '%s': %Rrc\n", pszFilename, rc);
1676 }
1677 else
1678 RTMsgError("Error opening executable image '%s': %Rrc", pszFilename, rc);
1679
1680 SignToolPkcs7Exe_Delete(pThis);
1681 return RTEXITCODE_FAILURE;
1682}
1683
1684
1685/**
1686 * Calculates the checksum of an executable.
1687 *
1688 * @returns Success indicator (errors are reported)
1689 * @param pThis The exe file to checksum.
1690 * @param hFile The file handle.
1691 * @param puCheckSum Where to return the checksum.
1692 */
1693static bool SignToolPkcs7Exe_CalcPeCheckSum(PSIGNTOOLPKCS7EXE pThis, RTFILE hFile, uint32_t *puCheckSum)
1694{
1695#ifdef RT_OS_WINDOWS
1696 /*
1697 * Try use IMAGEHLP!MapFileAndCheckSumW first.
1698 */
1699 PRTUTF16 pwszPath;
1700 int rc = RTStrToUtf16(pThis->pszFilename, &pwszPath);
1701 if (RT_SUCCESS(rc))
1702 {
1703 decltype(MapFileAndCheckSumW) *pfnMapFileAndCheckSumW;
1704 pfnMapFileAndCheckSumW = (decltype(MapFileAndCheckSumW) *)RTLdrGetSystemSymbol("IMAGEHLP.DLL", "MapFileAndCheckSumW");
1705 if (pfnMapFileAndCheckSumW)
1706 {
1707 DWORD uOldSum = UINT32_MAX;
1708 DWORD uCheckSum = UINT32_MAX;
1709 DWORD dwRc = pfnMapFileAndCheckSumW(pwszPath, &uOldSum, &uCheckSum);
1710 if (dwRc == CHECKSUM_SUCCESS)
1711 {
1712 *puCheckSum = uCheckSum;
1713 return true;
1714 }
1715 }
1716 }
1717#endif
1718
1719 RT_NOREF(pThis, hFile, puCheckSum);
1720 RTMsgError("Implement check sum calcuation fallback!");
1721 return false;
1722}
1723
1724
1725/**
1726 * Writes the signature to the file.
1727 *
1728 * This has the side-effect of closing the hLdrMod member. So, it can only be
1729 * called once!
1730 *
1731 * Caller must have called SignToolPkcs7_Encode() prior to this function.
1732 *
1733 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE with error
1734 * message on failure.
1735 * @param pThis The file which to write.
1736 * @param cVerbosity The verbosity.
1737 */
1738static RTEXITCODE SignToolPkcs7Exe_WriteSignatureToFile(PSIGNTOOLPKCS7EXE pThis, unsigned cVerbosity)
1739{
1740 AssertReturn(pThis->cbNewBuf && pThis->pbNewBuf, RTEXITCODE_FAILURE);
1741
1742 /*
1743 * Get the file header offset and arch before closing the destination handle.
1744 */
1745 uint32_t offNtHdrs;
1746 int rc = RTLdrQueryProp(pThis->hLdrMod, RTLDRPROP_FILE_OFF_HEADER, &offNtHdrs, sizeof(offNtHdrs));
1747 if (RT_SUCCESS(rc))
1748 {
1749 RTLDRARCH enmLdrArch = RTLdrGetArch(pThis->hLdrMod);
1750 if (enmLdrArch != RTLDRARCH_INVALID)
1751 {
1752 RTLdrClose(pThis->hLdrMod);
1753 pThis->hLdrMod = NIL_RTLDRMOD;
1754 unsigned cbNtHdrs = 0;
1755 switch (enmLdrArch)
1756 {
1757 case RTLDRARCH_AMD64:
1758 cbNtHdrs = sizeof(IMAGE_NT_HEADERS64);
1759 break;
1760 case RTLDRARCH_X86_32:
1761 cbNtHdrs = sizeof(IMAGE_NT_HEADERS32);
1762 break;
1763 default:
1764 RTMsgError("Unknown image arch: %d", enmLdrArch);
1765 }
1766 if (cbNtHdrs > 0)
1767 {
1768 if (cVerbosity > 0)
1769 RTMsgInfo("offNtHdrs=%#x cbNtHdrs=%u\n", offNtHdrs, cbNtHdrs);
1770
1771 /*
1772 * Open the executable file for writing.
1773 */
1774 RTFILE hFile;
1775 rc = RTFileOpen(&hFile, pThis->pszFilename, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1776 if (RT_SUCCESS(rc))
1777 {
1778 /* Read the file header and locate the security directory entry. */
1779 union
1780 {
1781 IMAGE_NT_HEADERS32 NtHdrs32;
1782 IMAGE_NT_HEADERS64 NtHdrs64;
1783 } uBuf;
1784 PIMAGE_DATA_DIRECTORY pSecDir = cbNtHdrs == sizeof(IMAGE_NT_HEADERS64)
1785 ? &uBuf.NtHdrs64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]
1786 : &uBuf.NtHdrs32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
1787
1788 rc = RTFileReadAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1789 if ( RT_SUCCESS(rc)
1790 && uBuf.NtHdrs32.Signature == IMAGE_NT_SIGNATURE)
1791 {
1792 /*
1793 * Drop any old signature by truncating the file.
1794 */
1795 if ( pSecDir->Size > 8
1796 && pSecDir->VirtualAddress > offNtHdrs + sizeof(IMAGE_NT_HEADERS32))
1797 {
1798 rc = RTFileSetSize(hFile, pSecDir->VirtualAddress);
1799 if (RT_FAILURE(rc))
1800 RTMsgError("Error truncating file to %#x bytes: %Rrc", pSecDir->VirtualAddress, rc);
1801 }
1802 else if (pSecDir->Size != 0 && pSecDir->VirtualAddress == 0)
1803 rc = RTMsgErrorRc(VERR_BAD_EXE_FORMAT, "Bad security directory entry: VA=%#x Size=%#x",
1804 pSecDir->VirtualAddress, pSecDir->Size);
1805 if (RT_SUCCESS(rc))
1806 {
1807 /*
1808 * Pad the file with zero up to a WIN_CERTIFICATE_ALIGNMENT boundary.
1809 *
1810 * Since the hash algorithm hashes everything up to the signature data,
1811 * zero padding included, the alignment we do here must match the alignment
1812 * padding that done while calculating the hash.
1813 */
1814 uint32_t const cbWinCert = RT_UOFFSETOF(WIN_CERTIFICATE, bCertificate);
1815 uint64_t offCur = 0;
1816 rc = RTFileQuerySize(hFile, &offCur);
1817 if ( RT_SUCCESS(rc)
1818 && offCur < _2G)
1819 {
1820 if (offCur != RT_ALIGN_64(offCur, WIN_CERTIFICATE_ALIGNMENT))
1821 {
1822 uint32_t const cbNeeded = (uint32_t)(RT_ALIGN_64(offCur, WIN_CERTIFICATE_ALIGNMENT) - offCur);
1823 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbNeeded, NULL);
1824 if (RT_SUCCESS(rc))
1825 offCur += cbNeeded;
1826 }
1827 if (RT_SUCCESS(rc))
1828 {
1829 /*
1830 * Write the header followed by the signature data.
1831 */
1832 uint32_t const cbZeroPad = (uint32_t)(RT_ALIGN_Z(pThis->cbNewBuf, 8) - pThis->cbNewBuf);
1833 pSecDir->VirtualAddress = (uint32_t)offCur;
1834 pSecDir->Size = cbWinCert + (uint32_t)pThis->cbNewBuf + cbZeroPad;
1835 if (cVerbosity >= 2)
1836 RTMsgInfo("Writing %u (%#x) bytes of signature at %#x (%u).\n",
1837 pSecDir->Size, pSecDir->Size, pSecDir->VirtualAddress, pSecDir->VirtualAddress);
1838
1839 WIN_CERTIFICATE WinCert;
1840 WinCert.dwLength = pSecDir->Size;
1841 WinCert.wRevision = WIN_CERT_REVISION_2_0;
1842 WinCert.wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
1843
1844 rc = RTFileWriteAt(hFile, offCur, &WinCert, cbWinCert, NULL);
1845 if (RT_SUCCESS(rc))
1846 {
1847 offCur += cbWinCert;
1848 rc = RTFileWriteAt(hFile, offCur, pThis->pbNewBuf, pThis->cbNewBuf, NULL);
1849 }
1850 if (RT_SUCCESS(rc) && cbZeroPad)
1851 {
1852 offCur += pThis->cbNewBuf;
1853 rc = RTFileWriteAt(hFile, offCur, g_abRTZero4K, cbZeroPad, NULL);
1854 }
1855 if (RT_SUCCESS(rc))
1856 {
1857 /*
1858 * Reset the checksum (sec dir updated already) and rewrite the header.
1859 */
1860 uBuf.NtHdrs32.OptionalHeader.CheckSum = 0;
1861 offCur = offNtHdrs;
1862 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1863 if (RT_SUCCESS(rc))
1864 rc = RTFileFlush(hFile);
1865 if (RT_SUCCESS(rc))
1866 {
1867 /*
1868 * Calc checksum and write out the header again.
1869 */
1870 uint32_t uCheckSum = UINT32_MAX;
1871 if (SignToolPkcs7Exe_CalcPeCheckSum(pThis, hFile, &uCheckSum))
1872 {
1873 uBuf.NtHdrs32.OptionalHeader.CheckSum = uCheckSum;
1874 rc = RTFileWriteAt(hFile, offNtHdrs, &uBuf, cbNtHdrs, NULL);
1875 if (RT_SUCCESS(rc))
1876 rc = RTFileFlush(hFile);
1877 if (RT_SUCCESS(rc))
1878 {
1879 rc = RTFileClose(hFile);
1880 if (RT_SUCCESS(rc))
1881 return RTEXITCODE_SUCCESS;
1882 RTMsgError("RTFileClose failed: %Rrc\n", rc);
1883 return RTEXITCODE_FAILURE;
1884 }
1885 }
1886 }
1887 }
1888 }
1889 if (RT_FAILURE(rc))
1890 RTMsgError("Write error at %#RX64: %Rrc", offCur, rc);
1891 }
1892 else if (RT_SUCCESS(rc))
1893 RTMsgError("File to big: %'RU64 bytes", offCur);
1894 else
1895 RTMsgError("RTFileQuerySize failed: %Rrc", rc);
1896 }
1897 }
1898 else if (RT_SUCCESS(rc))
1899 RTMsgError("Not NT executable header!");
1900 else
1901 RTMsgError("Error reading NT headers (%#x bytes) at %#x: %Rrc", cbNtHdrs, offNtHdrs, rc);
1902 RTFileClose(hFile);
1903 }
1904 else
1905 RTMsgError("Failed to open '%s' for writing: %Rrc", pThis->pszFilename, rc);
1906 }
1907 }
1908 else
1909 RTMsgError("RTLdrGetArch failed!");
1910 }
1911 else
1912 RTMsgError("RTLdrQueryProp/RTLDRPROP_FILE_OFF_HEADER failed: %Rrc", rc);
1913 return RTEXITCODE_FAILURE;
1914}
1915
1916#ifndef IPRT_SIGNTOOL_NO_SIGNING
1917
1918static PRTCRPKCS7ATTRIBUTE SignToolPkcs7_AuthAttribAppend(PRTCRPKCS7ATTRIBUTES pAuthAttribs)
1919{
1920 int32_t iPos = RTCrPkcs7Attributes_Append(pAuthAttribs);
1921 if (iPos >= 0)
1922 return pAuthAttribs->papItems[iPos];
1923 RTMsgError("RTCrPkcs7Attributes_Append failed: %Rrc", iPos);
1924 return NULL;
1925}
1926
1927
1928static RTEXITCODE SignToolPkcs7_AuthAttribsAddSigningTime(PRTCRPKCS7ATTRIBUTES pAuthAttribs, RTTIMESPEC SigningTime)
1929{
1930 /*
1931 * Signing time. For the old-style timestamps, Symantec used ASN.1 UTC TIME.
1932 * start -vv vv=ASN1_TAG_UTC_TIME
1933 * 00000187d6a65fd0/23b0: 0d 01 09 05 31 0f 17 0d-31 36 31 30 30 35 30 37 ....1...16100507
1934 * 00000187d6a65fe0/23c0: 35 30 33 30 5a 30 23 06-09 2a 86 48 86 f7 0d 01 5030Z0#..*.H....
1935 * ^^- end 2016-10-05T07:50:30.000000000Z (161005075030Z)
1936 */
1937 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
1938 if (!pAttr)
1939 return RTEXITCODE_FAILURE;
1940
1941 int rc = RTCrPkcs7Attribute_SetSigningTime(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
1942 if (RT_FAILURE(rc))
1943 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetSigningTime failed: %Rrc", rc);
1944
1945 /* Create the timestamp. */
1946 int32_t iPos = RTAsn1SetOfTimes_Append(pAttr->uValues.pSigningTime);
1947 if (iPos < 0)
1948 return RTMsgErrorExitFailure("RTAsn1SetOfTimes_Append failed: %Rrc", iPos);
1949
1950 PRTASN1TIME pTime = pAttr->uValues.pSigningTime->papItems[iPos];
1951 rc = RTAsn1Time_SetTimeSpec(pTime, pAttr->Allocation.pAllocator, &SigningTime);
1952 if (RT_FAILURE(rc))
1953 return RTMsgErrorExitFailure("RTAsn1Time_SetTimeSpec failed: %Rrc", rc);
1954
1955 return RTEXITCODE_SUCCESS;
1956}
1957
1958
1959static RTEXITCODE SignToolPkcs7_AuthAttribsAddSpcOpusInfo(PRTCRPKCS7ATTRIBUTES pAuthAttribs, void *pvInfo)
1960{
1961 /** @todo The OpusInfo is a structure with an optional SpcString and an
1962 * optional SpcLink (url). The two attributes can be set using the /d and /du
1963 * options of MS signtool.exe, I think. We shouldn't be using them atm. */
1964
1965 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
1966 if (!pAttr)
1967 return RTEXITCODE_FAILURE;
1968
1969 int rc = RTCrPkcs7Attribute_SetMsStatementType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
1970 if (RT_FAILURE(rc))
1971 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetMsStatementType failed: %Rrc", rc);
1972
1973 /* Override the ID. */
1974 rc = RTAsn1ObjId_SetFromString(&pAttr->Type, RTCR_PKCS9_ID_MS_SP_OPUS_INFO, pAuthAttribs->Allocation.pAllocator);
1975 if (RT_FAILURE(rc))
1976 return RTMsgErrorExitFailure("RTAsn1ObjId_SetFromString failed: %Rrc", rc);
1977
1978 /* Add attribute value entry. */
1979 int32_t iPos = RTAsn1SetOfObjIdSeqs_Append(pAttr->uValues.pObjIdSeqs);
1980 if (iPos < 0)
1981 return RTMsgErrorExitFailure("RTAsn1SetOfObjIdSeqs_Append failed: %Rrc", iPos);
1982
1983 RT_NOREF(pvInfo); Assert(!pvInfo);
1984 return RTEXITCODE_SUCCESS;
1985}
1986
1987
1988static RTEXITCODE SignToolPkcs7_AuthAttribsAddMsStatementType(PRTCRPKCS7ATTRIBUTES pAuthAttribs, const char *pszTypeId)
1989{
1990 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
1991 if (!pAttr)
1992 return RTEXITCODE_FAILURE;
1993
1994 int rc = RTCrPkcs7Attribute_SetMsStatementType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
1995 if (RT_FAILURE(rc))
1996 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetMsStatementType failed: %Rrc", rc);
1997
1998 /* Add attribute value entry. */
1999 int32_t iPos = RTAsn1SetOfObjIdSeqs_Append(pAttr->uValues.pObjIdSeqs);
2000 if (iPos < 0)
2001 return RTMsgErrorExitFailure("RTAsn1SetOfObjIdSeqs_Append failed: %Rrc", iPos);
2002 PRTASN1SEQOFOBJIDS pSeqObjIds = pAttr->uValues.pObjIdSeqs->papItems[iPos];
2003
2004 /* Add a object id to the value. */
2005 RTASN1OBJID ObjIdValue;
2006 rc = RTAsn1ObjId_InitFromString(&ObjIdValue, pszTypeId, &g_RTAsn1DefaultAllocator);
2007 if (RT_FAILURE(rc))
2008 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszTypeId, rc);
2009
2010 rc = RTAsn1SeqOfObjIds_InsertEx(pSeqObjIds, 0 /*iPos*/, &ObjIdValue, &g_RTAsn1DefaultAllocator, NULL);
2011 RTAsn1ObjId_Delete(&ObjIdValue);
2012 if (RT_FAILURE(rc))
2013 return RTMsgErrorExitFailure("RTAsn1SeqOfObjIds_InsertEx failed: %Rrc", rc);
2014
2015 return RTEXITCODE_SUCCESS;
2016}
2017
2018
2019static RTEXITCODE SignToolPkcs7_AuthAttribsAddContentType(PRTCRPKCS7ATTRIBUTES pAuthAttribs, const char *pszContentTypeId)
2020{
2021 PRTCRPKCS7ATTRIBUTE pAttr = SignToolPkcs7_AuthAttribAppend(pAuthAttribs);
2022 if (!pAttr)
2023 return RTEXITCODE_FAILURE;
2024
2025 int rc = RTCrPkcs7Attribute_SetContentType(pAttr, NULL, pAuthAttribs->Allocation.pAllocator);
2026 if (RT_FAILURE(rc))
2027 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetContentType failed: %Rrc", rc);
2028
2029 /* Add a object id to the value. */
2030 RTASN1OBJID ObjIdValue;
2031 rc = RTAsn1ObjId_InitFromString(&ObjIdValue, pszContentTypeId, pAuthAttribs->Allocation.pAllocator);
2032 if (RT_FAILURE(rc))
2033 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszContentTypeId, rc);
2034
2035 rc = RTAsn1SetOfObjIds_InsertEx(pAttr->uValues.pObjIds, 0 /*iPos*/, &ObjIdValue, pAuthAttribs->Allocation.pAllocator, NULL);
2036 RTAsn1ObjId_Delete(&ObjIdValue);
2037 if (RT_FAILURE(rc))
2038 return RTMsgErrorExitFailure("RTAsn1SetOfObjIds_InsertEx failed: %Rrc", rc);
2039
2040 return RTEXITCODE_SUCCESS;
2041}
2042
2043
2044static RTEXITCODE SignToolPkcs7_AddAuthAttribsForTimestamp(PRTCRPKCS7ATTRIBUTES pAuthAttribs, TIMESTAMPTYPE enmTimestampType,
2045 RTTIMESPEC SigningTime, PCRTCRX509CERTIFICATE pTimestampCert)
2046{
2047 /*
2048 * Add content type.
2049 */
2050 RTEXITCODE rcExit = SignToolPkcs7_AuthAttribsAddContentType(pAuthAttribs,
2051 enmTimestampType == kTimestampType_Old
2052 ? RTCR_PKCS7_DATA_OID : RTCRTSPTSTINFO_OID);
2053 if (rcExit != RTEXITCODE_SUCCESS)
2054 return rcExit;
2055
2056 /*
2057 * Add signing time.
2058 */
2059 rcExit = SignToolPkcs7_AuthAttribsAddSigningTime(pAuthAttribs, SigningTime);
2060 if (rcExit != RTEXITCODE_SUCCESS)
2061 return rcExit;
2062
2063 /*
2064 * More later if we want to support fTimestampTypeOld = false perhaps?
2065 */
2066 Assert(enmTimestampType == kTimestampType_Old);
2067 RT_NOREF(pTimestampCert);
2068
2069 return RTEXITCODE_SUCCESS;
2070}
2071
2072
2073static RTEXITCODE SignToolPkcs7_AddAuthAttribsForImageOrCatSignature(PRTCRPKCS7ATTRIBUTES pAuthAttribs, RTTIMESPEC SigningTime,
2074 bool fNoSigningTime, const char *pszContentTypeId)
2075{
2076 /*
2077 * Add SpcOpusInfo. No attribute values.
2078 * SEQ start -vv vv- Type ObjId
2079 * 1c60: 0e 03 02 1a 05 00 a0 70-30 10 06 0a 2b 06 01 04 .......p0...+...
2080 * 1c70: 01 82 37 02 01 0c 31 02-30 00 30 19 06 09 2a 86 ..7...1.0.0...*.
2081 * Set Of -^^ ^^- Empty Sequence.
2082 */
2083 RTEXITCODE rcExit = SignToolPkcs7_AuthAttribsAddSpcOpusInfo(pAuthAttribs, NULL /*pvInfo - none*/);
2084 if (rcExit != RTEXITCODE_SUCCESS)
2085 return rcExit;
2086
2087 /*
2088 * Add ContentType = Ms-SpcIndirectDataContext?
2089 * SEQ start -vv vv- Type ObjId
2090 * 1c70: 01 82 37 02 01 0c 31 02-30 00 30 19 06 09 2a 86 ..7...1.0.0...*.
2091 * 1c80: 48 86 f7 0d 01 09 03 31-0c 06 0a 2b 06 01 04 01 H......1...+....
2092 * 1c90: 82 37 02 01 04 ^^- ^^- ObjId
2093 * ^- Set Of
2094 */
2095 rcExit = SignToolPkcs7_AuthAttribsAddContentType(pAuthAttribs, pszContentTypeId);
2096 if (rcExit != RTEXITCODE_SUCCESS)
2097 return rcExit;
2098
2099 /*
2100 * Add Ms-SpcStatementType = Ms-SpcIndividualCodeSigning.
2101 * SEQ start -vv vv- Type ObjId
2102 * 1c90: 82 37 02 01 04 30 1c 06-0a 2b 06 01 04 01 82 37 .7...0...+.....7
2103 * 1ca0: 02 01 0b 31 0e 30 0c 06-0a 2b 06 01 04 01 82 37 ...1.0...+.....7
2104 * 1cb0: 02 01 15 ^^ ^^ ^^- ObjId
2105 * Set Of -^^ ^^- Sequence Of
2106 */
2107 rcExit = SignToolPkcs7_AuthAttribsAddMsStatementType(pAuthAttribs, RTCRSPC_STMT_TYPE_INDIVIDUAL_CODE_SIGNING);
2108 if (rcExit != RTEXITCODE_SUCCESS)
2109 return rcExit;
2110
2111 /*
2112 * Add signing time. We add this, even if signtool.exe, since OpenSSL will always do it otherwise.
2113 */
2114 if (!fNoSigningTime) /** @todo requires disabling the code in do_pkcs7_signed_attrib that adds it when absent */
2115 {
2116 rcExit = SignToolPkcs7_AuthAttribsAddSigningTime(pAuthAttribs, SigningTime);
2117 if (rcExit != RTEXITCODE_SUCCESS)
2118 return rcExit;
2119 }
2120
2121 /** @todo more? Some certificate stuff? */
2122
2123 return RTEXITCODE_SUCCESS;
2124}
2125
2126
2127static RTEXITCODE SignToolPkcs7_AppendCounterSignature(PRTCRPKCS7SIGNERINFO pSignerInfo,
2128 PCRTCRPKCS7SIGNERINFO pCounterSignerInfo, unsigned cVerbosity)
2129{
2130 /* Make sure the UnauthenticatedAttributes member is there. */
2131 RTEXITCODE rcExit = SignToolPkcs7_EnsureUnauthenticatedAttributesPresent(pSignerInfo);
2132 if (rcExit != RTEXITCODE_SUCCESS)
2133 return rcExit;
2134
2135#if 0 /* Windows won't accept multiple timestamps either way. Doing the latter as it makes more sense to me... */
2136 /* Append an entry to UnauthenticatedAttributes. */
2137 uint32_t iPos;
2138 int rc = RTCrPkcs7Attributes_InsertEx(&pSignerInfo->UnauthenticatedAttributes, 0 /*iPosition*/, NULL /*pToClone*/,
2139 &g_RTAsn1DefaultAllocator, &iPos);
2140 if (RT_FAILURE(rc))
2141 return RTMsgErrorExitFailure("RTCrPkcs7Attributes_Append failed: %Rrc", rc);
2142 Assert(iPos < pSignerInfo->UnauthenticatedAttributes.cItems); Assert(iPos == 0);
2143 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2144
2145 if (cVerbosity >= 2)
2146 RTMsgInfo("Adding UnauthenticatedAttribute #%u...", iPos);
2147#else
2148 /* Look up the counter signature attribute, create one if needed. */
2149 int rc;
2150 uint32_t iPos = 0;
2151 PRTCRPKCS7ATTRIBUTE pAttr = NULL;
2152 for (; iPos < pSignerInfo->UnauthenticatedAttributes.cItems; iPos++)
2153 {
2154 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2155 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES)
2156 break;
2157 }
2158 if (iPos >= pSignerInfo->UnauthenticatedAttributes.cItems)
2159 {
2160 /* Append a new entry to UnauthenticatedAttributes. */
2161 rc = RTCrPkcs7Attributes_InsertEx(&pSignerInfo->UnauthenticatedAttributes, 0 /*iPosition*/, NULL /*pToClone*/,
2162 &g_RTAsn1DefaultAllocator, &iPos);
2163 if (RT_FAILURE(rc))
2164 return RTMsgErrorExitFailure("RTCrPkcs7Attributes_Append failed: %Rrc", rc);
2165 Assert(iPos < pSignerInfo->UnauthenticatedAttributes.cItems); Assert(iPos == 0);
2166 pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iPos];
2167
2168 /* Create the attrib and its sub-set of counter signatures. */
2169 rc = RTCrPkcs7Attribute_SetCounterSignatures(pAttr, NULL, pAttr->Allocation.pAllocator);
2170 if (RT_FAILURE(rc))
2171 return RTMsgErrorExitFailure("RTCrPkcs7Attribute_SetCounterSignatures failed: %Rrc", rc);
2172 }
2173
2174 if (cVerbosity >= 2)
2175 RTMsgInfo("Adding UnauthenticatedAttribute #%u.%u...", iPos, pAttr->uValues.pCounterSignatures->cItems);
2176
2177#endif
2178
2179 /* Insert the counter signature. */
2180 rc = RTCrPkcs7SignerInfos_InsertEx(pAttr->uValues.pCounterSignatures, pAttr->uValues.pCounterSignatures->cItems /*iPosition*/,
2181 pCounterSignerInfo, pAttr->Allocation.pAllocator, NULL);
2182 if (RT_FAILURE(rc))
2183 return RTMsgErrorExitFailure("RTCrPkcs7SignerInfos_InsertEx failed: %Rrc", rc);
2184
2185 return RTEXITCODE_SUCCESS;
2186}
2187
2188
2189static RTEXITCODE SignToolPkcs7_AppendCertificate(PRTCRPKCS7SIGNEDDATA pSignedData, PCRTCRX509CERTIFICATE pCertToAppend)
2190{
2191 if (pSignedData->Certificates.cItems == 0 && !RTCrPkcs7SetOfCerts_IsPresent(&pSignedData->Certificates))
2192 return RTMsgErrorExitFailure("PKCS#7 signature includes no certificates! Didn't expect that");
2193
2194 /* Already there? */
2195 PCRTCRX509CERTIFICATE pExisting
2196 = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates, &pCertToAppend->TbsCertificate.Issuer,
2197 &pCertToAppend->TbsCertificate.SerialNumber);
2198 if (!pExisting || RTCrX509Certificate_Compare(pExisting, pCertToAppend) != 0)
2199 {
2200 /* Prepend a RTCRPKCS7CERT entry. */
2201 uint32_t iPos;
2202 int rc = RTCrPkcs7SetOfCerts_InsertEx(&pSignedData->Certificates, 0 /*iPosition*/, NULL /*pToClone*/,
2203 &g_RTAsn1DefaultAllocator, &iPos);
2204 if (RT_FAILURE(rc))
2205 return RTMsgErrorExitFailure("RTCrPkcs7SetOfCerts_Append failed: %Rrc", rc);
2206 PRTCRPKCS7CERT pCertEntry = pSignedData->Certificates.papItems[iPos];
2207
2208 /* Set (clone) the certificate. */
2209 rc = RTCrPkcs7Cert_SetX509Cert(pCertEntry, pCertToAppend, pCertEntry->Allocation.pAllocator);
2210 if (RT_FAILURE(rc))
2211 return RTMsgErrorExitFailure("RTCrPkcs7Cert_X509Cert failed: %Rrc", rc);
2212 }
2213 return RTEXITCODE_SUCCESS;
2214}
2215
2216#ifdef RT_OS_WINDOWS
2217
2218static PCRTUTF16 GetBCryptNameFromCrDigest(RTCRDIGEST hDigest)
2219{
2220 switch (RTCrDigestGetType(hDigest))
2221 {
2222 case RTDIGESTTYPE_MD2: return BCRYPT_MD2_ALGORITHM;
2223 case RTDIGESTTYPE_MD4: return BCRYPT_MD4_ALGORITHM;
2224 case RTDIGESTTYPE_SHA1: return BCRYPT_SHA1_ALGORITHM;
2225 case RTDIGESTTYPE_SHA256: return BCRYPT_SHA256_ALGORITHM;
2226 case RTDIGESTTYPE_SHA384: return BCRYPT_SHA384_ALGORITHM;
2227 case RTDIGESTTYPE_SHA512: return BCRYPT_SHA512_ALGORITHM;
2228 default:
2229 RTMsgError("No BCrypt translation for %s/%d!", RTCrDigestGetAlgorithmOid(hDigest), RTCrDigestGetType(hDigest));
2230 return L"No BCrypt translation";
2231 }
2232}
2233
2234static RTEXITCODE
2235SignToolPkcs7_Pkcs7SignStuffAgainWithReal(const char *pszWhat, SignToolKeyPair *pCertKeyPair, unsigned cVerbosity,
2236 PRTCRPKCS7CONTENTINFO pContentInfo, void **ppvSigned, size_t *pcbSigned)
2237
2238{
2239 RT_NOREF(cVerbosity);
2240
2241 /*
2242 * First remove the fake certificate from the PKCS7 structure and insert the real one.
2243 */
2244 PRTCRPKCS7SIGNEDDATA pSignedData = pContentInfo->u.pSignedData;
2245 unsigned iCert = pSignedData->Certificates.cItems;
2246 unsigned cErased = 0;
2247 while (iCert-- > 0)
2248 {
2249 PCRTCRPKCS7CERT pCert = pSignedData->Certificates.papItems[iCert];
2250 if ( pCert->enmChoice == RTCRPKCS7CERTCHOICE_X509
2251 && RTCrX509Certificate_MatchIssuerAndSerialNumber(pCert->u.pX509Cert,
2252 &pCertKeyPair->pCertificate->TbsCertificate.Issuer,
2253 &pCertKeyPair->pCertificate->TbsCertificate.SerialNumber))
2254 {
2255 RTCrPkcs7SetOfCerts_Erase(&pSignedData->Certificates, iCert);
2256 cErased++;
2257 }
2258 }
2259 if (cErased == 0)
2260 return RTMsgErrorExitFailure("(%s) Failed to find temporary signing certificate in PKCS#7 from OpenSSL: %u certs",
2261 pszWhat, pSignedData->Certificates.cItems);
2262
2263 /* Then insert the real signing certificate. */
2264 PCRTCRX509CERTIFICATE const pRealCertificate = pCertKeyPair->getRealCertificate();
2265 RTEXITCODE rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pRealCertificate);
2266 if (rcExit != RTEXITCODE_SUCCESS)
2267 return rcExit;
2268
2269 /*
2270 * Modify the signer info to reflect the real certificate.
2271 */
2272 PRTCRPKCS7SIGNERINFO pSignerInfo = pSignedData->SignerInfos.papItems[0];
2273 RTCrX509Name_Delete(&pSignerInfo->IssuerAndSerialNumber.Name);
2274 int rc = RTCrX509Name_Clone(&pSignerInfo->IssuerAndSerialNumber.Name,
2275 &pRealCertificate->TbsCertificate.Issuer, &g_RTAsn1DefaultAllocator);
2276 if (RT_FAILURE(rc))
2277 return RTMsgErrorExitFailure("(%s) RTCrX509Name_Clone failed: %Rrc", pszWhat, rc);
2278
2279 RTAsn1Integer_Delete(&pSignerInfo->IssuerAndSerialNumber.SerialNumber);
2280 rc = RTAsn1Integer_Clone(&pSignerInfo->IssuerAndSerialNumber.SerialNumber,
2281 &pRealCertificate->TbsCertificate.SerialNumber, &g_RTAsn1DefaultAllocator);
2282 if (RT_FAILURE(rc))
2283 return RTMsgErrorExitFailure("(%s) RTAsn1Integer_Clone failed: %Rrc", pszWhat, rc);
2284
2285 /* There shouldn't be anything in the authenticated attributes that
2286 we need to modify... */
2287
2288 /*
2289 * Now a create a new signature using the real key. Since we haven't modified
2290 * the authenticated attributes, we can just hash them as-is.
2291 */
2292 /* Create the hash to sign. */
2293 RTCRDIGEST hDigest;
2294 rc = RTCrDigestCreateByObjId(&hDigest, &pSignerInfo->DigestAlgorithm.Algorithm);
2295 if (RT_FAILURE(rc))
2296 return RTMsgErrorExitFailure("(%s) RTCrDigestCreateByObjId failed on '%s': %Rrc",
2297 pszWhat, pSignerInfo->DigestAlgorithm.Algorithm.szObjId, rc);
2298
2299 rcExit = RTEXITCODE_FAILURE;
2300 RTERRINFOSTATIC ErrInfo;
2301 rc = RTCrPkcs7Attributes_HashAttributes(&pSignerInfo->AuthenticatedAttributes, hDigest, RTErrInfoInitStatic(&ErrInfo));
2302 if (RT_SUCCESS(rc))
2303 {
2304 BCRYPT_PKCS1_PADDING_INFO PaddingInfo = { GetBCryptNameFromCrDigest(hDigest) };
2305 DWORD cbSignature = 0;
2306 SECURITY_STATUS rcNCrypt = NCryptSignHash(pCertKeyPair->hNCryptPrivateKey, &PaddingInfo,
2307 (PBYTE)RTCrDigestGetHash(hDigest), RTCrDigestGetHashSize(hDigest),
2308 NULL, 0, &cbSignature, NCRYPT_SILENT_FLAG | BCRYPT_PAD_PKCS1);
2309 if (rcNCrypt == ERROR_SUCCESS)
2310 {
2311 if (cVerbosity)
2312 RTMsgInfo("PaddingInfo: '%ls' cb=%#x, was %#zx\n",
2313 PaddingInfo.pszAlgId, cbSignature, pSignerInfo->EncryptedDigest.Asn1Core.cb);
2314
2315 rc = RTAsn1OctetString_AllocContent(&pSignerInfo->EncryptedDigest, NULL /*pvSrc*/, cbSignature,
2316 &g_RTAsn1DefaultAllocator);
2317 if (RT_SUCCESS(rc))
2318 {
2319 Assert(pSignerInfo->EncryptedDigest.Asn1Core.uData.pv);
2320 rcNCrypt = NCryptSignHash(pCertKeyPair->hNCryptPrivateKey, &PaddingInfo,
2321 (PBYTE)RTCrDigestGetHash(hDigest), RTCrDigestGetHashSize(hDigest),
2322 (PBYTE)pSignerInfo->EncryptedDigest.Asn1Core.uData.pv, cbSignature, &cbSignature,
2323 /*NCRYPT_SILENT_FLAG |*/ BCRYPT_PAD_PKCS1);
2324 if (rcNCrypt == ERROR_SUCCESS)
2325 {
2326 /*
2327 * Now we need to re-encode the whole thing and decode it again.
2328 */
2329 PRTASN1CORE pRoot = RTCrPkcs7ContentInfo_GetAsn1Core(pContentInfo);
2330 uint32_t cbRealSigned;
2331 rc = RTAsn1EncodePrepare(pRoot, RTASN1ENCODE_F_DER, &cbRealSigned, RTErrInfoInitStatic(&ErrInfo));
2332 if (RT_SUCCESS(rc))
2333 {
2334 void *pvRealSigned = RTMemAllocZ(cbRealSigned);
2335 if (pvRealSigned)
2336 {
2337 rc = RTAsn1EncodeToBuffer(pRoot, RTASN1ENCODE_F_DER, pvRealSigned, cbRealSigned,
2338 RTErrInfoInitStatic(&ErrInfo));
2339 if (RT_SUCCESS(rc))
2340 {
2341 /* Decode it */
2342 RTCrPkcs7ContentInfo_Delete(pContentInfo);
2343
2344 RTASN1CURSORPRIMARY PrimaryCursor;
2345 RTAsn1CursorInitPrimary(&PrimaryCursor, pvRealSigned, cbRealSigned, RTErrInfoInitStatic(&ErrInfo),
2346 &g_RTAsn1DefaultAllocator, 0, pszWhat);
2347 rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, pContentInfo, "CI");
2348 if (RT_SUCCESS(rc))
2349 {
2350 Assert(RTCrPkcs7ContentInfo_IsSignedData(pContentInfo));
2351
2352 /* Almost done! Just replace output buffer. */
2353 RTMemFree(*ppvSigned);
2354 *ppvSigned = pvRealSigned;
2355 *pcbSigned = cbRealSigned;
2356 pvRealSigned = NULL;
2357 rcExit = RTEXITCODE_SUCCESS;
2358 }
2359 else
2360 RTMsgError("(%s) RTCrPkcs7ContentInfo_DecodeAsn1 failed: %Rrc%#RTeim",
2361 pszWhat, rc, &ErrInfo.Core);
2362 }
2363 else
2364 RTMsgError("(%s) RTAsn1EncodeToBuffer failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2365
2366 RTMemFree(pvRealSigned);
2367 }
2368 else
2369 RTMsgError("(%s) Failed to allocate %u bytes!", pszWhat, cbRealSigned);
2370 }
2371 else
2372 RTMsgError("(%s) RTAsn1EncodePrepare failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2373 }
2374 else
2375 RTMsgError("(%s) NCryptSignHash/2 failed: %Rwc %#x (%u)", pszWhat, rcNCrypt, rcNCrypt, rcNCrypt);
2376 }
2377 else
2378 RTMsgError("(%s) RTAsn1OctetString_AllocContent(,,%#x) failed: %Rrc", pszWhat, cbSignature, rc);
2379 }
2380 else
2381 RTMsgError("(%s) NCryptSignHash/1 failed: %Rwc %#x (%u)", pszWhat, rcNCrypt, rcNCrypt, rcNCrypt);
2382 }
2383 else
2384 RTMsgError("(%s) RTCrPkcs7Attributes_HashAttributes failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2385 RTCrDigestRelease(hDigest);
2386 return rcExit;
2387}
2388
2389#endif /* RT_OS_WINDOWS */
2390
2391static RTEXITCODE SignToolPkcs7_Pkcs7SignStuffInner(const char *pszWhat, const void *pvToDataToSign, size_t cbToDataToSign,
2392 PCRTCRPKCS7ATTRIBUTES pAuthAttribs, RTCRSTORE hAdditionalCerts,
2393 uint32_t fExtraFlags, RTDIGESTTYPE enmDigestType,
2394 SignToolKeyPair *pCertKeyPair, unsigned cVerbosity,
2395 void **ppvSigned, size_t *pcbSigned, PRTCRPKCS7CONTENTINFO pContentInfo,
2396 PRTCRPKCS7SIGNEDDATA *ppSignedData)
2397{
2398 *ppvSigned = NULL;
2399 if (pcbSigned)
2400 *pcbSigned = 0;
2401 if (ppSignedData)
2402 *ppSignedData = NULL;
2403
2404 /* Figure out how large the signature will be. */
2405 uint32_t const fSignFlags = RTCRPKCS7SIGN_SD_F_USE_V1 | RTCRPKCS7SIGN_SD_F_NO_SMIME_CAP | fExtraFlags;
2406 size_t cbSigned = 1024;
2407 RTERRINFOSTATIC ErrInfo;
2408 int rc = RTCrPkcs7SimpleSignSignedData(fSignFlags, pCertKeyPair->pCertificate, pCertKeyPair->hPrivateKey,
2409 pvToDataToSign, cbToDataToSign,enmDigestType, hAdditionalCerts, pAuthAttribs,
2410 NULL, &cbSigned, RTErrInfoInitStatic(&ErrInfo));
2411 if (rc != VERR_BUFFER_OVERFLOW)
2412 return RTMsgErrorExitFailure("(%s) RTCrPkcs7SimpleSignSignedData failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2413
2414 /* Allocate memory for it and do the actual signing. */
2415 void *pvSigned = RTMemAllocZ(cbSigned);
2416 if (!pvSigned)
2417 return RTMsgErrorExitFailure("(%s) Failed to allocate %#zx bytes for %s signature", pszWhat, cbSigned, pszWhat);
2418 rc = RTCrPkcs7SimpleSignSignedData(fSignFlags, pCertKeyPair->pCertificate, pCertKeyPair->hPrivateKey,
2419 pvToDataToSign, cbToDataToSign, enmDigestType, hAdditionalCerts, pAuthAttribs,
2420 pvSigned, &cbSigned, RTErrInfoInitStatic(&ErrInfo));
2421 if (RT_SUCCESS(rc))
2422 {
2423 if (cVerbosity > 2)
2424 RTMsgInfo("%s signature: %#zx bytes\n%.*Rhxd\n", pszWhat, cbSigned, cbSigned, pvSigned);
2425
2426 /*
2427 * Decode the signature and check that it is SignedData.
2428 */
2429 RTASN1CURSORPRIMARY PrimaryCursor;
2430 RTAsn1CursorInitPrimary(&PrimaryCursor, pvSigned, (uint32_t)cbSigned, RTErrInfoInitStatic(&ErrInfo),
2431 &g_RTAsn1DefaultAllocator, 0, pszWhat);
2432 rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, pContentInfo, "CI");
2433 if (RT_SUCCESS(rc))
2434 {
2435 if (RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
2436 {
2437#ifdef RT_OS_WINDOWS
2438 /*
2439 * If we're using a fake key+cert, we now have to re-do the signing using the real
2440 * key+cert and the windows crypto API. This kludge is necessary because we can't
2441 * typically get that the encoded private key, so it isn't possible to feed it to
2442 * openssl.
2443 */
2444 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2445 if (pCertKeyPair->pCertificateReal)
2446 rcExit = SignToolPkcs7_Pkcs7SignStuffAgainWithReal(pszWhat, pCertKeyPair, cVerbosity, pContentInfo,
2447 &pvSigned, &cbSigned);
2448 if (rcExit == RTEXITCODE_SUCCESS)
2449#endif
2450 {
2451 /*
2452 * Set returns and maybe display the result before returning.
2453 */
2454 *ppvSigned = pvSigned;
2455 if (pcbSigned)
2456 *pcbSigned = cbSigned;
2457 if (ppSignedData)
2458 *ppSignedData = pContentInfo->u.pSignedData;
2459
2460 if (cVerbosity)
2461 {
2462 SHOWEXEPKCS7 ShowExe;
2463 RT_ZERO(ShowExe);
2464 ShowExe.cVerbosity = cVerbosity;
2465 HandleShowExeWorkerPkcs7Display(&ShowExe, pContentInfo->u.pSignedData, 0, pContentInfo);
2466 }
2467 return RTEXITCODE_SUCCESS;
2468 }
2469 }
2470
2471 RTMsgError("(%s) RTCrPkcs7SimpleSignSignedData did not create SignedData: %s",
2472 pszWhat, pContentInfo->ContentType.szObjId);
2473 }
2474 else
2475 RTMsgError("(%s) RTCrPkcs7ContentInfo_DecodeAsn1 failed: %Rrc%#RTeim", pszWhat, rc, &ErrInfo.Core);
2476 RTCrPkcs7ContentInfo_Delete(pContentInfo);
2477 }
2478 RTMemFree(pvSigned);
2479 return RTEXITCODE_FAILURE;
2480}
2481
2482
2483static RTEXITCODE SignToolPkcs7_Pkcs7SignStuff(const char *pszWhat, const void *pvToDataToSign, size_t cbToDataToSign,
2484 PCRTCRPKCS7ATTRIBUTES pAuthAttribs, RTCRSTORE hAdditionalCerts,
2485 uint32_t fExtraFlags, RTDIGESTTYPE enmDigestType, SignToolKeyPair *pCertKeyPair,
2486 unsigned cVerbosity, void **ppvSigned, size_t *pcbSigned,
2487 PRTCRPKCS7CONTENTINFO pContentInfo, PRTCRPKCS7SIGNEDDATA *ppSignedData)
2488{
2489 /*
2490 * Gather all additional certificates before doing the actual work.
2491 */
2492 RTCRSTORE hAllAdditionalCerts = pCertKeyPair->assembleAllAdditionalCertificates(hAdditionalCerts);
2493 if (hAllAdditionalCerts == NIL_RTCRSTORE)
2494 return RTEXITCODE_FAILURE;
2495 RTEXITCODE rcExit = SignToolPkcs7_Pkcs7SignStuffInner(pszWhat, pvToDataToSign, cbToDataToSign, pAuthAttribs,
2496 hAllAdditionalCerts, fExtraFlags, enmDigestType, pCertKeyPair,
2497 cVerbosity, ppvSigned, pcbSigned, pContentInfo, ppSignedData);
2498 RTCrStoreRelease(hAllAdditionalCerts);
2499 return rcExit;
2500}
2501
2502
2503static RTEXITCODE SignToolPkcs7_AddTimestampSignatureEx(PRTCRPKCS7SIGNERINFO pSignerInfo, PRTCRPKCS7SIGNEDDATA pSignedData,
2504 unsigned cVerbosity, bool fReplaceExisting,
2505 RTTIMESPEC SigningTime, SignToolTimestampOpts *pTimestampOpts)
2506{
2507 AssertReturn(!pTimestampOpts->isNewType(), RTMsgErrorExitFailure("New style signatures not supported yet"));
2508
2509 /*
2510 * Create a set of attributes we need to include in the AuthenticatedAttributes
2511 * of the timestamp signature.
2512 */
2513 RTCRPKCS7ATTRIBUTES AuthAttribs;
2514 int rc = RTCrPkcs7Attributes_Init(&AuthAttribs, &g_RTAsn1DefaultAllocator);
2515 if (RT_FAILURE(rc))
2516 return RTMsgErrorExitFailure("RTCrPkcs7SetOfAttributes_Init failed: %Rrc", rc);
2517
2518 RTEXITCODE rcExit = SignToolPkcs7_AddAuthAttribsForTimestamp(&AuthAttribs, pTimestampOpts->m_enmType, SigningTime,
2519 pTimestampOpts->getRealCertificate());
2520 if (rcExit == RTEXITCODE_SUCCESS)
2521 {
2522 /*
2523 * Now create a PKCS#7 signature of the encrypted signature from the selected signer info.
2524 */
2525 void *pvSigned = NULL;
2526 PRTCRPKCS7SIGNEDDATA pTsSignedData = NULL;
2527 RTCRPKCS7CONTENTINFO TsContentInfo;
2528 rcExit = SignToolPkcs7_Pkcs7SignStuffInner("timestamp", pSignerInfo->EncryptedDigest.Asn1Core.uData.pv,
2529 pSignerInfo->EncryptedDigest.Asn1Core.cb, &AuthAttribs,
2530 NIL_RTCRSTORE /*hAdditionalCerts*/, RTCRPKCS7SIGN_SD_F_DEATCHED,
2531 RTDIGESTTYPE_SHA1, pTimestampOpts, cVerbosity,
2532 &pvSigned, NULL /*pcbSigned*/, &TsContentInfo, &pTsSignedData);
2533 if (rcExit == RTEXITCODE_SUCCESS)
2534 {
2535
2536 /*
2537 * If we're replacing existing timestamp signatures, remove old ones now.
2538 */
2539 if ( fReplaceExisting
2540 && RTCrPkcs7Attributes_IsPresent(&pSignerInfo->UnauthenticatedAttributes))
2541 {
2542 uint32_t iItem = pSignerInfo->UnauthenticatedAttributes.cItems;
2543 while (iItem-- > 0)
2544 {
2545 PRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iItem];
2546 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES) /* ASSUMES all counter sigs are timstamps */
2547 {
2548 if (cVerbosity > 1)
2549 RTMsgInfo("Removing counter signature in attribute #%u\n", iItem);
2550 rc = RTCrPkcs7Attributes_Erase(&pSignerInfo->UnauthenticatedAttributes, iItem);
2551 if (RT_FAILURE(rc))
2552 rcExit = RTMsgErrorExitFailure("RTCrPkcs7Attributes_Erase failed on #%u: %Rrc", iItem, rc);
2553 }
2554 }
2555 }
2556
2557 /*
2558 * Add the new one.
2559 */
2560 if (rcExit == RTEXITCODE_SUCCESS)
2561 rcExit = SignToolPkcs7_AppendCounterSignature(pSignerInfo, pTsSignedData->SignerInfos.papItems[0], cVerbosity);
2562
2563 /*
2564 * Make sure the signing certificate is included.
2565 */
2566 if (rcExit == RTEXITCODE_SUCCESS)
2567 {
2568 rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pTimestampOpts->getRealCertificate());
2569
2570 PCRTCRCERTCTX pInterCaCtx = NULL;
2571 while ((pInterCaCtx = pTimestampOpts->findNextIntermediateCert(pInterCaCtx)) != NULL)
2572 if (rcExit == RTEXITCODE_SUCCESS)
2573 rcExit = SignToolPkcs7_AppendCertificate(pSignedData, pInterCaCtx->pCert);
2574 }
2575
2576 /*
2577 * Clean up.
2578 */
2579 RTCrPkcs7ContentInfo_Delete(&TsContentInfo);
2580 RTMemFree(pvSigned);
2581 }
2582 }
2583 RTCrPkcs7Attributes_Delete(&AuthAttribs);
2584 return rcExit;
2585}
2586
2587
2588static RTEXITCODE SignToolPkcs7_AddTimestampSignature(SIGNTOOLPKCS7EXE *pThis, unsigned cVerbosity, unsigned iSignature,
2589 bool fReplaceExisting, RTTIMESPEC SigningTime,
2590 SignToolTimestampOpts *pTimestampOpts)
2591{
2592 /*
2593 * Locate the signature specified by iSignature and add a timestamp to it.
2594 */
2595 PRTCRPKCS7SIGNEDDATA pSignedData = NULL;
2596 PRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(pThis, iSignature, &pSignedData);
2597 if (!pSignerInfo)
2598 return RTMsgErrorExitFailure("No signature #%u in %s", iSignature, pThis->pszFilename);
2599
2600 return SignToolPkcs7_AddTimestampSignatureEx(pSignerInfo, pSignedData, cVerbosity, fReplaceExisting,
2601 SigningTime, pTimestampOpts);
2602}
2603
2604
2605typedef enum SIGNDATATWEAK
2606{
2607 kSignDataTweak_NoTweak = 1,
2608 kSignDataTweak_RootIsParent
2609} SIGNDATATWEAK;
2610
2611static RTEXITCODE SignToolPkcs7_SignData(SIGNTOOLPKCS7 *pThis, PRTASN1CORE pToSignRoot, SIGNDATATWEAK enmTweak,
2612 const char *pszContentTypeId, unsigned cVerbosity, uint32_t fExtraFlags,
2613 RTDIGESTTYPE enmSigType, bool fReplaceExisting, bool fNoSigningTime,
2614 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
2615 RTTIMESPEC SigningTime, size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
2616{
2617 /*
2618 * Encode it.
2619 */
2620 RTERRINFOSTATIC ErrInfo;
2621 uint32_t cbEncoded = 0;
2622 int rc = RTAsn1EncodePrepare(pToSignRoot, RTASN1ENCODE_F_DER, &cbEncoded, RTErrInfoInitStatic(&ErrInfo));
2623 if (RT_FAILURE(rc))
2624 return RTMsgErrorExitFailure("RTAsn1EncodePrepare failed: %Rrc%RTeim", rc, &ErrInfo.Core);
2625
2626 if (cVerbosity >= 4)
2627 RTAsn1Dump(pToSignRoot, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
2628
2629 uint8_t *pbEncoded = (uint8_t *)RTMemTmpAllocZ(cbEncoded );
2630 if (!pbEncoded)
2631 return RTMsgErrorExitFailure("Failed to allocate %#z bytes for encoding data we're signing (%s)",
2632 cbEncoded, pszContentTypeId);
2633
2634 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
2635 rc = RTAsn1EncodeToBuffer(pToSignRoot, RTASN1ENCODE_F_DER, pbEncoded, cbEncoded, RTErrInfoInitStatic(&ErrInfo));
2636 if (RT_SUCCESS(rc))
2637 {
2638 size_t const cbToSign = cbEncoded - (enmTweak == kSignDataTweak_RootIsParent ? pToSignRoot->cbHdr : 0);
2639 void const *pvToSign = pbEncoded + (enmTweak == kSignDataTweak_RootIsParent ? pToSignRoot->cbHdr : 0);
2640
2641 /*
2642 * Create additional authenticated attributes.
2643 */
2644 RTCRPKCS7ATTRIBUTES AuthAttribs;
2645 rc = RTCrPkcs7Attributes_Init(&AuthAttribs, &g_RTAsn1DefaultAllocator);
2646 if (RT_SUCCESS(rc))
2647 {
2648 rcExit = SignToolPkcs7_AddAuthAttribsForImageOrCatSignature(&AuthAttribs, SigningTime, fNoSigningTime,
2649 pszContentTypeId);
2650 if (rcExit == RTEXITCODE_SUCCESS)
2651 {
2652 /*
2653 * Ditch the old signature if so desired.
2654 * (It is okay to do this in the CAT case too, as we've already
2655 * encoded the data and won't touch pToSignRoot any more.)
2656 */
2657 pToSignRoot = NULL; /* (may become invalid if replacing) */
2658 if (fReplaceExisting && pThis->pSignedData)
2659 {
2660 RTCrPkcs7ContentInfo_Delete(&pThis->ContentInfo);
2661 pThis->pSignedData = NULL;
2662 RTMemFree(pThis->pbBuf);
2663 pThis->pbBuf = NULL;
2664 pThis->cbBuf = 0;
2665 }
2666
2667 /*
2668 * Do the actual signing.
2669 */
2670 SIGNTOOLPKCS7 Src = { RTSIGNTOOLFILETYPE_DETECT, NULL, 0, NULL };
2671 PSIGNTOOLPKCS7 pSigDst = !pThis->pSignedData ? pThis : &Src;
2672 rcExit = SignToolPkcs7_Pkcs7SignStuff("image", pvToSign, cbToSign, &AuthAttribs, hAddCerts,
2673 fExtraFlags | RTCRPKCS7SIGN_SD_F_NO_DATA_ENCAP, enmSigType /** @todo ?? */,
2674 pSigningCertKey, cVerbosity,
2675 (void **)&pSigDst->pbBuf, &pSigDst->cbBuf,
2676 &pSigDst->ContentInfo, &pSigDst->pSignedData);
2677 if (rcExit == RTEXITCODE_SUCCESS)
2678 {
2679 /*
2680 * Add the requested timestamp signatures if requested.
2681 */
2682 for (size_t i = 0; rcExit == RTEXITCODE_SUCCESS &&i < cTimestampOpts; i++)
2683 if (paTimestampOpts[i].isComplete())
2684 rcExit = SignToolPkcs7_AddTimestampSignatureEx(pSigDst->pSignedData->SignerInfos.papItems[0],
2685 pSigDst->pSignedData,
2686 cVerbosity, false /*fReplaceExisting*/,
2687 SigningTime, &paTimestampOpts[i]);
2688
2689 /*
2690 * Append the signature to the existing one, if that's what we're doing.
2691 */
2692 if (rcExit == RTEXITCODE_SUCCESS && pSigDst == &Src)
2693 rcExit = SignToolPkcs7_AddNestedSignature(pThis, &Src, cVerbosity, true /*fPrepend*/); /** @todo prepend/append option */
2694
2695 /* cleanup */
2696 if (pSigDst == &Src)
2697 SignToolPkcs7_Delete(&Src);
2698 }
2699
2700 }
2701 RTCrPkcs7Attributes_Delete(&AuthAttribs);
2702 }
2703 else
2704 RTMsgError("RTCrPkcs7SetOfAttributes_Init failed: %Rrc", rc);
2705 }
2706 else
2707 RTMsgError("RTAsn1EncodeToBuffer failed: %Rrc", rc);
2708 RTMemTmpFree(pbEncoded);
2709 return rcExit;
2710}
2711
2712
2713static RTEXITCODE SignToolPkcs7_SpcCompleteWithoutPageHashes(RTCRSPCINDIRECTDATACONTENT *pSpcIndData)
2714{
2715 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2716 PRTCRSPCPEIMAGEDATA const pPeImage = pSpcIndData->Data.uValue.pPeImage;
2717 Assert(pPeImage);
2718
2719 /*
2720 * Set it to File with an empty name.
2721 * RTCRSPCPEIMAGEDATA::Flags -vv
2722 * RTCRSPCPEIMAGEDATA::SeqCore -vv T0 -vv vv- pT2/CtxTag2
2723 * 0040: 04 01 82 37 02 01 0f 30-09 03 01 00 a0 04 a2 02 ...7...0........
2724 * 0050: 80 00 30 21 30 09 06 05-2b 0e 03 02 1a 05 00 04 ..0!0...+.......
2725 * ^^- pUcs2 / empty string
2726 */
2727
2728 /* Create an empty BMP string. */
2729 RTASN1STRING EmptyStr;
2730 int rc = RTAsn1BmpString_Init(&EmptyStr, pAllocator);
2731 if (RT_FAILURE(rc))
2732 return RTMsgErrorExitFailure("RTAsn1BmpString_Init/Ucs2 failed: %Rrc", rc);
2733
2734 /* Create an SPC string and use the above empty string with the Ucs2 setter. */
2735 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
2736 RTCRSPCSTRING SpcString;
2737 rc = RTCrSpcString_Init(&SpcString, pAllocator);
2738 if (RT_SUCCESS(rc))
2739 {
2740 rc = RTCrSpcString_SetUcs2(&SpcString, &EmptyStr, pAllocator);
2741 if (RT_SUCCESS(rc))
2742 {
2743 /* Create a temporary SpcLink with the empty SpcString. */
2744 RTCRSPCLINK SpcLink;
2745 rc = RTCrSpcLink_Init(&SpcLink, pAllocator);
2746 if (RT_SUCCESS(rc))
2747 {
2748 /* Use the setter on the SpcLink object to copy the SpcString to it. */
2749 rc = RTCrSpcLink_SetFile(&SpcLink, &SpcString, pAllocator);
2750 if (RT_SUCCESS(rc))
2751 {
2752 /* Use the setter to copy SpcLink to the PeImage structure. */
2753 rc = RTCrSpcPeImageData_SetFile(pPeImage, &SpcLink, pAllocator);
2754 if (RT_SUCCESS(rc))
2755 rcExit = RTEXITCODE_SUCCESS;
2756 else
2757 RTMsgError("RTCrSpcPeImageData_SetFile failed: %Rrc", rc);
2758 }
2759 else
2760 RTMsgError("RTCrSpcLink_SetFile failed: %Rrc", rc);
2761 RTCrSpcLink_Delete(&SpcLink);
2762 }
2763 else
2764 RTMsgError("RTCrSpcLink_Init failed: %Rrc", rc);
2765 }
2766 else
2767 RTMsgError("RTCrSpcString_SetUcs2 failed: %Rrc", rc);
2768 RTCrSpcString_Delete(&SpcString);
2769 }
2770 else
2771 RTMsgError("RTCrSpcString_Init failed: %Rrc", rc);
2772 RTAsn1BmpString_Delete(&EmptyStr);
2773 return rcExit;
2774}
2775
2776
2777static RTEXITCODE SignToolPkcs7_SpcAddImagePageHashes(SIGNTOOLPKCS7EXE *pThis, RTCRSPCINDIRECTDATACONTENT *pSpcIndData,
2778 RTDIGESTTYPE enmSigType)
2779{
2780 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2781 PRTCRSPCPEIMAGEDATA const pPeImage = pSpcIndData->Data.uValue.pPeImage;
2782 Assert(pPeImage);
2783
2784 /*
2785 * The hashes are stored in the 'Moniker' attribute.
2786 */
2787 /* Create a temporary SpcLink with a default moniker. */
2788 RTCRSPCLINK SpcLink;
2789 int rc = RTCrSpcLink_Init(&SpcLink, pAllocator);
2790 if (RT_FAILURE(rc))
2791 return RTMsgErrorExitFailure("RTCrSpcLink_Init failed: %Rrc", rc);
2792 rc = RTCrSpcLink_SetMoniker(&SpcLink, NULL, pAllocator);
2793 if (RT_SUCCESS(rc))
2794 {
2795 /* Use the setter to copy SpcLink to the PeImage structure. */
2796 rc = RTCrSpcPeImageData_SetFile(pPeImage, &SpcLink, pAllocator);
2797 if (RT_FAILURE(rc))
2798 RTMsgError("RTCrSpcLink_SetFile failed: %Rrc", rc);
2799 }
2800 else
2801 RTMsgError("RTCrSpcLink_SetMoniker failed: %Rrc", rc);
2802 RTCrSpcLink_Delete(&SpcLink);
2803 if (RT_FAILURE(rc))
2804 return RTEXITCODE_FAILURE;
2805
2806 /*
2807 * Now go to work on the moniker. It doesn't have any autogenerated
2808 * setters, so we must do stuff manually.
2809 */
2810 PRTCRSPCSERIALIZEDOBJECT pMoniker = pPeImage->T0.File.u.pMoniker;
2811 RTUUID Uuid;
2812 rc = RTUuidFromStr(&Uuid, RTCRSPCSERIALIZEDOBJECT_UUID_STR);
2813 if (RT_FAILURE(rc))
2814 return RTMsgErrorExitFailure("RTUuidFromStr failed: %Rrc", rc);
2815
2816 rc = RTAsn1OctetString_AllocContent(&pMoniker->Uuid, &Uuid, sizeof(Uuid), pAllocator);
2817 if (RT_FAILURE(rc))
2818 return RTMsgErrorExitFailure("RTAsn1String_InitWithValue/UUID failed: %Rrc", rc);
2819
2820 /* Create a new set of attributes and associate this with the SerializedData member. */
2821 PRTCRSPCSERIALIZEDOBJECTATTRIBUTES pSpcAttribs;
2822 rc = RTAsn1MemAllocZ(&pMoniker->SerializedData.EncapsulatedAllocation,
2823 (void **)&pSpcAttribs, sizeof(*pSpcAttribs));
2824 if (RT_FAILURE(rc))
2825 return RTMsgErrorExitFailure("RTAsn1MemAllocZ/pSpcAttribs failed: %Rrc", rc);
2826 pMoniker->SerializedData.pEncapsulated = RTCrSpcSerializedObjectAttributes_GetAsn1Core(pSpcAttribs);
2827 pMoniker->enmType = RTCRSPCSERIALIZEDOBJECTTYPE_ATTRIBUTES;
2828 pMoniker->u.pData = pSpcAttribs;
2829
2830 rc = RTCrSpcSerializedObjectAttributes_Init(pSpcAttribs, pAllocator);
2831 if (RT_FAILURE(rc))
2832 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttributes_Init failed: %Rrc", rc);
2833
2834 /*
2835 * Add a single attribute to the set that we'll use for page hashes.
2836 */
2837 int32_t iPos = RTCrSpcSerializedObjectAttributes_Append(pSpcAttribs);
2838 if (iPos < 0)
2839 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttributes_Append failed: %Rrc", iPos);
2840 PRTCRSPCSERIALIZEDOBJECTATTRIBUTE pSpcObjAttr = pSpcAttribs->papItems[iPos];
2841
2842 if (enmSigType == RTDIGESTTYPE_SHA1)
2843 rc = RTCrSpcSerializedObjectAttribute_SetV1Hashes(pSpcObjAttr, NULL, pAllocator);
2844 else if (enmSigType == RTDIGESTTYPE_SHA256)
2845 rc = RTCrSpcSerializedObjectAttribute_SetV2Hashes(pSpcObjAttr, NULL, pAllocator);
2846 else
2847 rc = VERR_CR_DIGEST_NOT_SUPPORTED;
2848 if (RT_FAILURE(rc))
2849 return RTMsgErrorExitFailure("RTCrSpcSerializedObjectAttribute_SetV1Hashes/SetV2Hashes failed: %Rrc", rc);
2850 PRTCRSPCSERIALIZEDPAGEHASHES pSpcPageHashes = pSpcObjAttr->u.pPageHashes;
2851 Assert(pSpcPageHashes);
2852
2853 /*
2854 * Now ask the loader for the number of pages in the page hash table
2855 * and calculate its size.
2856 */
2857 uint32_t cPages = 0;
2858 rc = RTLdrQueryPropEx(pThis->hLdrMod, RTLDRPROP_HASHABLE_PAGES, NULL, &cPages, sizeof(cPages), NULL);
2859 if (RT_FAILURE(rc))
2860 return RTMsgErrorExitFailure("RTLdrQueryPropEx/RTLDRPROP_HASHABLE_PAGES failed: %Rrc", rc);
2861
2862 uint32_t const cbHash = RTCrDigestTypeToHashSize(enmSigType);
2863 AssertReturn(cbHash > 0, RTMsgErrorExitFailure("Invalid value: enmSigType=%d", enmSigType));
2864 uint32_t const cbTable = (sizeof(uint32_t) + cbHash) * cPages;
2865
2866 /*
2867 * Allocate memory in the octect string.
2868 */
2869 rc = RTAsn1ContentAllocZ(&pSpcPageHashes->RawData.Asn1Core, cbTable, pAllocator);
2870 if (RT_FAILURE(rc))
2871 return RTMsgErrorExitFailure("RTAsn1ContentAllocZ failed to allocate %#x bytes for page hashes: %Rrc", cbTable, rc);
2872 pSpcPageHashes->pData = (PCRTCRSPCPEIMAGEPAGEHASHES)pSpcPageHashes->RawData.Asn1Core.uData.pu8;
2873
2874 RTLDRPROP enmLdrProp;
2875 switch (enmSigType)
2876 {
2877 case RTDIGESTTYPE_SHA1: enmLdrProp = RTLDRPROP_SHA1_PAGE_HASHES; break;
2878 case RTDIGESTTYPE_SHA256: enmLdrProp = RTLDRPROP_SHA256_PAGE_HASHES; break;
2879 default: AssertFailedReturn(RTMsgErrorExitFailure("Invalid value: enmSigType=%d", enmSigType));
2880
2881 }
2882 rc = RTLdrQueryPropEx(pThis->hLdrMod, enmLdrProp, NULL, (void *)pSpcPageHashes->RawData.Asn1Core.uData.pv, cbTable, NULL);
2883 if (RT_FAILURE(rc))
2884 return RTMsgErrorExitFailure("RTLdrQueryPropEx/RTLDRPROP_SHA?_PAGE_HASHES/%#x failed: %Rrc", cbTable, rc);
2885
2886 return RTEXITCODE_SUCCESS;
2887}
2888
2889
2890static RTEXITCODE SignToolPkcs7_SpcAddImageHash(SIGNTOOLPKCS7EXE *pThis, RTCRSPCINDIRECTDATACONTENT *pSpcIndData,
2891 RTDIGESTTYPE enmSigType)
2892{
2893 uint32_t const cbHash = RTCrDigestTypeToHashSize(enmSigType);
2894 const char * const pszAlgId = RTCrDigestTypeToAlgorithmOid(enmSigType);
2895
2896 /*
2897 * Ask the loader for the hash.
2898 */
2899 uint8_t abHash[RTSHA512_HASH_SIZE];
2900 int rc = RTLdrHashImage(pThis->hLdrMod, enmSigType, abHash, sizeof(abHash));
2901 if (RT_FAILURE(rc))
2902 return RTMsgErrorExitFailure("RTLdrHashImage/%s failed: %Rrc", RTCrDigestTypeToName(enmSigType), rc);
2903
2904 /*
2905 * Set it.
2906 */
2907 /** @todo no setter, this should be okay, though... */
2908 rc = RTAsn1ObjId_InitFromString(&pSpcIndData->DigestInfo.DigestAlgorithm.Algorithm, pszAlgId, &g_RTAsn1DefaultAllocator);
2909 if (RT_FAILURE(rc))
2910 return RTMsgErrorExitFailure("RTAsn1ObjId_InitFromString/%s failed: %Rrc", pszAlgId, rc);
2911 RTAsn1DynType_SetToNull(&pSpcIndData->DigestInfo.DigestAlgorithm.Parameters); /* ASSUMES RSA or similar */
2912
2913 rc = RTAsn1ContentDup(&pSpcIndData->DigestInfo.Digest.Asn1Core, abHash, cbHash, &g_RTAsn1DefaultAllocator);
2914 if (RT_FAILURE(rc))
2915 return RTMsgErrorExitFailure("RTAsn1ContentDup/%#x failed: %Rrc", cbHash, rc);
2916
2917 return RTEXITCODE_SUCCESS;
2918}
2919
2920
2921static RTEXITCODE SignToolPkcs7_AddOrReplaceSignature(SIGNTOOLPKCS7EXE *pThis, unsigned cVerbosity, RTDIGESTTYPE enmSigType,
2922 bool fReplaceExisting, bool fHashPages, bool fNoSigningTime,
2923 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
2924 RTTIMESPEC SigningTime,
2925 size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
2926{
2927 /*
2928 * We must construct the data to be packed into the PKCS#7 signature
2929 * and signed.
2930 */
2931 PCRTASN1ALLOCATORVTABLE const pAllocator = &g_RTAsn1DefaultAllocator;
2932 RTCRSPCINDIRECTDATACONTENT SpcIndData;
2933 int rc = RTCrSpcIndirectDataContent_Init(&SpcIndData, pAllocator);
2934 if (RT_FAILURE(rc))
2935 return RTMsgErrorExitFailure("RTCrSpcIndirectDataContent_Init failed: %Rrc", rc);
2936
2937 /* Set the data to PE image. */
2938 /** @todo Generalize the Type + enmType DYN stuff and generate setters. */
2939 Assert(SpcIndData.Data.enmType == RTCRSPCAAOVTYPE_NOT_PRESENT);
2940 Assert(SpcIndData.Data.uValue.pPeImage == NULL);
2941 RTEXITCODE rcExit;
2942 rc = RTAsn1ObjId_SetFromString(&SpcIndData.Data.Type, RTCRSPCPEIMAGEDATA_OID, pAllocator);
2943 if (RT_SUCCESS(rc))
2944 {
2945 SpcIndData.Data.enmType = RTCRSPCAAOVTYPE_PE_IMAGE_DATA;
2946 rc = RTAsn1MemAllocZ(&SpcIndData.Data.Allocation, (void **)&SpcIndData.Data.uValue.pPeImage,
2947 sizeof(*SpcIndData.Data.uValue.pPeImage));
2948 if (RT_SUCCESS(rc))
2949 {
2950 rc = RTCrSpcPeImageData_Init(SpcIndData.Data.uValue.pPeImage, pAllocator);
2951 if (RT_SUCCESS(rc))
2952 {
2953 /* Old (SHA1) signatures has a Flags member, it's zero bits, though. */
2954 if (enmSigType == RTDIGESTTYPE_SHA1)
2955 {
2956 uint8_t bFlags = 0;
2957 RTASN1BITSTRING Flags;
2958 rc = RTAsn1BitString_InitWithData(&Flags, &bFlags, 0, pAllocator);
2959 if (RT_SUCCESS(rc))
2960 {
2961 rc = RTCrSpcPeImageData_SetFlags(SpcIndData.Data.uValue.pPeImage, &Flags, pAllocator);
2962 RTAsn1BitString_Delete(&Flags);
2963 if (RT_FAILURE(rc))
2964 rcExit = RTMsgErrorExitFailure("RTCrSpcPeImageData_SetFlags failed: %Rrc", rc);
2965 }
2966 else
2967 rcExit = RTMsgErrorExitFailure("RTAsn1BitString_InitWithData failed: %Rrc", rc);
2968 }
2969
2970 /*
2971 * Add the hashes.
2972 */
2973 rcExit = SignToolPkcs7_SpcAddImageHash(pThis, &SpcIndData, enmSigType);
2974 if (rcExit == RTEXITCODE_SUCCESS)
2975 {
2976 if (fHashPages)
2977 rcExit = SignToolPkcs7_SpcAddImagePageHashes(pThis, &SpcIndData, enmSigType);
2978 else
2979 rcExit = SignToolPkcs7_SpcCompleteWithoutPageHashes(&SpcIndData);
2980
2981 /*
2982 * Encode and sign the SPC data, timestamp it, and line it up for adding to the executable.
2983 */
2984 if (rcExit == RTEXITCODE_SUCCESS)
2985 rcExit = SignToolPkcs7_SignData(pThis, RTCrSpcIndirectDataContent_GetAsn1Core(&SpcIndData),
2986 kSignDataTweak_NoTweak, RTCRSPCINDIRECTDATACONTENT_OID, cVerbosity, 0,
2987 enmSigType, fReplaceExisting, fNoSigningTime, pSigningCertKey, hAddCerts,
2988 SigningTime, cTimestampOpts, paTimestampOpts);
2989 }
2990 }
2991 else
2992 rcExit = RTMsgErrorExitFailure("RTCrPkcs7SignerInfos_Init failed: %Rrc", rc);
2993 }
2994 else
2995 rcExit = RTMsgErrorExitFailure("RTAsn1MemAllocZ failed for RTCRSPCPEIMAGEDATA: %Rrc", rc);
2996 }
2997 else
2998 rcExit = RTMsgErrorExitFailure("RTAsn1ObjId_SetWithString/SpcPeImageData failed: %Rrc", rc);
2999
3000 RTCrSpcIndirectDataContent_Delete(&SpcIndData);
3001 return rcExit;
3002}
3003
3004
3005static RTEXITCODE SignToolPkcs7_AddOrReplaceCatSignature(SIGNTOOLPKCS7 *pThis, unsigned cVerbosity, RTDIGESTTYPE enmSigType,
3006 bool fReplaceExisting, bool fNoSigningTime,
3007 SignToolKeyPair *pSigningCertKey, RTCRSTORE hAddCerts,
3008 RTTIMESPEC SigningTime,
3009 size_t cTimestampOpts, SignToolTimestampOpts *paTimestampOpts)
3010{
3011 AssertReturn(pThis->pSignedData, RTMsgErrorExitFailure("pSignedData is NULL!"));
3012
3013 /*
3014 * Figure out what to sign first.
3015 */
3016 uint32_t fExtraFlags = 0;
3017 PRTASN1CORE pToSign = &pThis->pSignedData->ContentInfo.Content.Asn1Core;
3018 const char *pszType = pThis->pSignedData->ContentInfo.ContentType.szObjId;
3019
3020 if (!fReplaceExisting && pThis->pSignedData->SignerInfos.cItems == 0)
3021 fReplaceExisting = true;
3022 if (!fReplaceExisting)
3023 {
3024 pszType = RTCR_PKCS7_DATA_OID;
3025 fExtraFlags |= RTCRPKCS7SIGN_SD_F_DEATCHED;
3026 }
3027
3028 /*
3029 * Do the signing.
3030 */
3031 RTEXITCODE rcExit = SignToolPkcs7_SignData(pThis, pToSign, kSignDataTweak_RootIsParent,
3032 pszType, cVerbosity, fExtraFlags, enmSigType, fReplaceExisting,
3033 fNoSigningTime, pSigningCertKey, hAddCerts,
3034 SigningTime, cTimestampOpts, paTimestampOpts);
3035
3036 /* probably need to clean up stuff related to nested signatures here later... */
3037 return rcExit;
3038}
3039
3040#endif /* !IPRT_SIGNTOOL_NO_SIGNING */
3041
3042
3043/*********************************************************************************************************************************
3044* Option handlers shared by 'sign-exe', 'sign-cat', 'add-timestamp-exe-signature' and others. *
3045*********************************************************************************************************************************/
3046#ifndef IPRT_SIGNTOOL_NO_SIGNING
3047
3048static RTEXITCODE HandleOptAddCert(PRTCRSTORE phStore, const char *pszFile)
3049{
3050 if (*phStore == NIL_RTCRSTORE)
3051 {
3052 int rc = RTCrStoreCreateInMem(phStore, 2);
3053 if (RT_FAILURE(rc))
3054 return RTMsgErrorExitFailure("RTCrStoreCreateInMem(,2) failed: %Rrc", rc);
3055 }
3056 RTERRINFOSTATIC ErrInfo;
3057 int rc = RTCrStoreCertAddFromFile(*phStore, RTCRCERTCTX_F_ADD_IF_NOT_FOUND, pszFile, RTErrInfoInitStatic(&ErrInfo));
3058 if (RT_FAILURE(rc))
3059 return RTMsgErrorExitFailure("Error reading certificate from '%s': %Rrc%#RTeim", pszFile, rc, &ErrInfo.Core);
3060 return RTEXITCODE_SUCCESS;
3061}
3062
3063static RTEXITCODE HandleOptSignatureType(RTDIGESTTYPE *penmSigType, const char *pszType)
3064{
3065 if ( RTStrICmpAscii(pszType, "sha1") == 0
3066 || RTStrICmpAscii(pszType, "sha-1") == 0)
3067 *penmSigType = RTDIGESTTYPE_SHA1;
3068 else if ( RTStrICmpAscii(pszType, "sha256") == 0
3069 || RTStrICmpAscii(pszType, "sha-256") == 0)
3070 *penmSigType = RTDIGESTTYPE_SHA256;
3071 else
3072 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signature type: %s (expected sha1 or sha256)", pszType);
3073 return RTEXITCODE_SUCCESS;
3074}
3075
3076
3077static RTEXITCODE HandleOptTimestampType(SignToolTimestampOpts *pTimestampOpts, const char *pszType)
3078{
3079 if (strcmp(pszType, "old") == 0)
3080 pTimestampOpts->m_enmType = kTimestampType_Old;
3081 else if (strcmp(pszType, "new") == 0)
3082 pTimestampOpts->m_enmType = kTimestampType_New;
3083 else
3084 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown timestamp type: %s", pszType);
3085 return RTEXITCODE_SUCCESS;
3086}
3087
3088static RTEXITCODE HandleOptTimestampOverride(PRTTIMESPEC pSigningTime, const char *pszPartialTs)
3089{
3090 /*
3091 * First try use it as-is.
3092 */
3093 if (RTTimeSpecFromString(pSigningTime, pszPartialTs) != NULL)
3094 return RTEXITCODE_SUCCESS;
3095
3096 /* Check the input against a pattern, making sure we've got something that
3097 makes sense before trying to merge. */
3098 size_t const cchPartialTs = strlen(pszPartialTs);
3099 static char s_szPattern[] = "0000-00-00T00:00:";
3100 if (cchPartialTs > sizeof(s_szPattern) - 1) /* It is not a partial timestamp if we've got the seconds component. */
3101 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp: %s", pszPartialTs);
3102
3103 for (size_t off = 0; off < cchPartialTs; off++)
3104 switch (s_szPattern[off])
3105 {
3106 case '0':
3107 if (!RT_C_IS_DIGIT(pszPartialTs[off]))
3108 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected digit at position %u: %s",
3109 off + 1, pszPartialTs);
3110 break;
3111 case '-':
3112 case ':':
3113 if (pszPartialTs[off] != s_szPattern[off])
3114 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected '%c' at position %u: %s",
3115 s_szPattern[off], off + 1, pszPartialTs);
3116 break;
3117 case 'T':
3118 if ( pszPartialTs[off] != 'T'
3119 && pszPartialTs[off] != 't'
3120 && pszPartialTs[off] != ' ')
3121 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp, expected 'T' or space at position %u: %s",
3122 off + 1, pszPartialTs);
3123 break;
3124 default:
3125 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Internal error");
3126 }
3127
3128 if (RT_C_IS_DIGIT(s_szPattern[cchPartialTs]) && RT_C_IS_DIGIT(s_szPattern[cchPartialTs - 1]))
3129 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Incomplete timstamp component: %s", pszPartialTs);
3130
3131 /*
3132 * Take the current time and merge in the components from pszPartialTs.
3133 */
3134 char szSigningTime[RTTIME_STR_LEN];
3135 RTTIMESPEC Now;
3136 RTTimeSpecToString(RTTimeNow(&Now), szSigningTime, sizeof(szSigningTime));
3137 memcpy(szSigningTime, pszPartialTs, cchPartialTs);
3138 szSigningTime[4+1+2+1+2] = 'T';
3139
3140 /* Fix 29th for non-leap override: */
3141 if (memcmp(&szSigningTime[5], RT_STR_TUPLE("02-29")) == 0)
3142 {
3143 if (!RTTimeIsLeapYear(RTStrToUInt32(szSigningTime)))
3144 szSigningTime[9] = '8';
3145 }
3146 if (RTTimeSpecFromString(pSigningTime, szSigningTime) == NULL)
3147 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Invalid timestamp: %s (%s)", pszPartialTs, szSigningTime);
3148
3149 return RTEXITCODE_SUCCESS;
3150}
3151
3152static RTEXITCODE HandleOptFileType(RTSIGNTOOLFILETYPE *penmFileType, const char *pszType)
3153{
3154 if (strcmp(pszType, "detect") == 0 || strcmp(pszType, "auto") == 0)
3155 *penmFileType = RTSIGNTOOLFILETYPE_DETECT;
3156 else if (strcmp(pszType, "exe") == 0)
3157 *penmFileType = RTSIGNTOOLFILETYPE_EXE;
3158 else if (strcmp(pszType, "cat") == 0)
3159 *penmFileType = RTSIGNTOOLFILETYPE_CAT;
3160 else
3161 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown forced file type: %s", pszType);
3162 return RTEXITCODE_SUCCESS;
3163}
3164
3165#endif /* !IPRT_SIGNTOOL_NO_SIGNING */
3166
3167/**
3168 * Detects the type of files @a pszFile is (by reading from it).
3169 *
3170 * @returns The file type, or RTSIGNTOOLFILETYPE_UNKNOWN (error displayed).
3171 * @param enmForceFileType Usually set to RTSIGNTOOLFILETYPE_DETECT, but if
3172 * not we'll return this without probing the file.
3173 * @param pszFile The name of the file to detect the type of.
3174 */
3175static RTSIGNTOOLFILETYPE DetectFileType(RTSIGNTOOLFILETYPE enmForceFileType, const char *pszFile)
3176{
3177 /*
3178 * Forced?
3179 */
3180 if (enmForceFileType != RTSIGNTOOLFILETYPE_DETECT)
3181 return enmForceFileType;
3182
3183 /*
3184 * Read the start of the file.
3185 */
3186 RTFILE hFile = NIL_RTFILE;
3187 int rc = RTFileOpen(&hFile, pszFile, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
3188 if (RT_FAILURE(rc))
3189 {
3190 RTMsgError("Error opening '%s' for reading: %Rrc", pszFile, rc);
3191 return RTSIGNTOOLFILETYPE_UNKNOWN;
3192 }
3193
3194 union
3195 {
3196 uint8_t ab[256];
3197 uint16_t au16[256/2];
3198 uint32_t au32[256/4];
3199 } uBuf;
3200 RT_ZERO(uBuf);
3201
3202 size_t cbRead = 0;
3203 rc = RTFileRead(hFile, &uBuf, sizeof(uBuf), &cbRead);
3204 if (RT_FAILURE(rc))
3205 RTMsgError("Error reading from '%s': %Rrc", pszFile, rc);
3206
3207 uint64_t cbFile;
3208 int rcSize = RTFileQuerySize(hFile, &cbFile);
3209 if (RT_FAILURE(rcSize))
3210 RTMsgError("Error querying size of '%s': %Rrc", pszFile, rc);
3211
3212 RTFileClose(hFile);
3213 if (RT_FAILURE(rc) || RT_FAILURE(rcSize))
3214 return RTSIGNTOOLFILETYPE_UNKNOWN;
3215
3216 /*
3217 * Try guess the kind of file.
3218 */
3219 /* All the executable magics we know: */
3220 if ( uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_DOS_SIGNATURE)
3221 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_NE_SIGNATURE)
3222 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_LX_SIGNATURE)
3223 || uBuf.au16[0] == RT_H2LE_U16_C(IMAGE_LE_SIGNATURE)
3224 || uBuf.au32[0] == RT_H2LE_U32_C(IMAGE_NT_SIGNATURE)
3225 || uBuf.au32[0] == RT_H2LE_U32_C(IMAGE_ELF_SIGNATURE)
3226 || uBuf.au32[0] == IMAGE_FAT_SIGNATURE
3227 || uBuf.au32[0] == IMAGE_FAT_SIGNATURE_OE
3228 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE
3229 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE_OE
3230 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE
3231 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE_OE)
3232 return RTSIGNTOOLFILETYPE_EXE;
3233
3234 /*
3235 * Catalog files are PKCS#7 SignedData and starts with a ContentInfo, i.e.:
3236 * SEQUENCE {
3237 * contentType OBJECT IDENTIFIER,
3238 * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
3239 * }
3240 *
3241 * We ASSUME that it's DER encoded and doesn't use an indefinite length form
3242 * at the start and that contentType is signedData (1.2.840.113549.1.7.2).
3243 *
3244 * Example of a 10353 (0x2871) byte long file:
3245 * vv-------- contentType -------vv
3246 * 00000000 30 82 28 6D 06 09 2A 86 48 86 F7 0D 01 07 02 A0
3247 * 00000010 82 28 5E 30 82 28 5A 02 01 01 31 0B 30 09 06 05
3248 */
3249 if ( uBuf.ab[0] == (ASN1_TAG_SEQUENCE | ASN1_TAGFLAG_CONSTRUCTED)
3250 && uBuf.ab[1] != 0x80 /* not indefinite form */
3251 && uBuf.ab[1] > 0x30)
3252 {
3253 size_t off = 1;
3254 uint32_t cbRec = uBuf.ab[1];
3255 if (cbRec & 0x80)
3256 {
3257 cbRec &= 0x7f;
3258 off += cbRec;
3259 switch (cbRec)
3260 {
3261 case 1: cbRec = uBuf.ab[2]; break;
3262 case 2: cbRec = RT_MAKE_U16( uBuf.ab[3], uBuf.ab[2]); break;
3263 case 3: cbRec = RT_MAKE_U32_FROM_U8(uBuf.ab[4], uBuf.ab[3], uBuf.ab[2], 0); break;
3264 case 4: cbRec = RT_MAKE_U32_FROM_U8(uBuf.ab[5], uBuf.ab[4], uBuf.ab[3], uBuf.ab[2]); break;
3265 default: cbRec = UINT32_MAX; break;
3266 }
3267 }
3268 if (off <= 5)
3269 {
3270 off++;
3271 if (off + cbRec == cbFile)
3272 {
3273 /* If the contentType is signedData we're going to treat it as a catalog file,
3274 we don't currently much care about the signed content of a cat file. */
3275 static const uint8_t s_abSignedDataOid[] =
3276 { ASN1_TAG_OID, 9 /*length*/, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
3277 if (memcmp(&uBuf.ab[off], s_abSignedDataOid, sizeof(s_abSignedDataOid)) == 0)
3278 return RTSIGNTOOLFILETYPE_CAT;
3279 }
3280 }
3281 }
3282
3283 RTMsgError("Unable to detect type of '%s'", pszFile);
3284 return RTSIGNTOOLFILETYPE_UNKNOWN;
3285}
3286
3287
3288/*********************************************************************************************************************************
3289* The 'extract-exe-signer-cert' command. *
3290*********************************************************************************************************************************/
3291
3292static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
3293{
3294 RT_NOREF_PV(enmLevel);
3295 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
3296 "extract-exe-signer-cert [--ber|--cer|--der] [--signature-index|-i <num>] [--input|--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
3297 return RTEXITCODE_SUCCESS;
3298}
3299
3300static RTEXITCODE WriteCertToFile(PCRTCRX509CERTIFICATE pCert, const char *pszFilename, bool fForce)
3301{
3302 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
3303 RTFILE hFile;
3304 int rc = RTFileOpen(&hFile, pszFilename,
3305 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | (fForce ? RTFILE_O_CREATE_REPLACE : RTFILE_O_CREATE));
3306 if (RT_SUCCESS(rc))
3307 {
3308 uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
3309 rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
3310 cbCert, NULL);
3311 if (RT_SUCCESS(rc))
3312 {
3313 rc = RTFileClose(hFile);
3314 if (RT_SUCCESS(rc))
3315 {
3316 hFile = NIL_RTFILE;
3317 rcExit = RTEXITCODE_SUCCESS;
3318 RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszFilename);
3319 }
3320 else
3321 RTMsgError("RTFileClose failed: %Rrc", rc);
3322 }
3323 else
3324 RTMsgError("RTFileWrite failed: %Rrc", rc);
3325 RTFileClose(hFile);
3326 }
3327 else
3328 RTMsgError("Error opening '%s' for writing: %Rrc", pszFilename, rc);
3329 return rcExit;
3330}
3331
3332
3333static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
3334{
3335 /*
3336 * Parse arguments.
3337 */
3338 static const RTGETOPTDEF s_aOptions[] =
3339 {
3340 { "--ber", 'b', RTGETOPT_REQ_NOTHING },
3341 { "--cer", 'c', RTGETOPT_REQ_NOTHING },
3342 { "--der", 'd', RTGETOPT_REQ_NOTHING },
3343 { "--exe", 'e', RTGETOPT_REQ_STRING },
3344 { "--input", 'e', RTGETOPT_REQ_STRING },
3345 { "--output", 'o', RTGETOPT_REQ_STRING },
3346 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
3347 { "--force", 'f', RTGETOPT_REQ_NOTHING },
3348 };
3349
3350 const char *pszExe = NULL;
3351 const char *pszOut = NULL;
3352 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
3353 unsigned cVerbosity = 0;
3354 uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
3355 uint32_t iSignature = 0;
3356 bool fForce = false;
3357
3358 RTGETOPTSTATE GetState;
3359 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3360 AssertRCReturn(rc, RTEXITCODE_FAILURE);
3361 RTGETOPTUNION ValueUnion;
3362 int ch;
3363 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
3364 {
3365 switch (ch)
3366 {
3367 case 'e': pszExe = ValueUnion.psz; break;
3368 case 'o': pszOut = ValueUnion.psz; break;
3369 case 'b': fCursorFlags = 0; break;
3370 case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
3371 case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
3372 case 'f': fForce = true; break;
3373 case 'i': iSignature = ValueUnion.u32; break;
3374 case 'V': return HandleVersion(cArgs, papszArgs);
3375 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
3376
3377 case VINF_GETOPT_NOT_OPTION:
3378 if (!pszExe)
3379 pszExe = ValueUnion.psz;
3380 else if (!pszOut)
3381 pszOut = ValueUnion.psz;
3382 else
3383 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
3384 break;
3385
3386 default:
3387 return RTGetOptPrintError(ch, &ValueUnion);
3388 }
3389 }
3390 if (!pszExe)
3391 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
3392 if (!pszOut)
3393 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
3394 if (!fForce && RTPathExists(pszOut))
3395 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
3396
3397 /*
3398 * Do it.
3399 */
3400 /* Read & decode the PKCS#7 signature. */
3401 SIGNTOOLPKCS7EXE This;
3402 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
3403 if (rcExit == RTEXITCODE_SUCCESS)
3404 {
3405 /* Find the signing certificate (ASSUMING that the certificate used is shipped in the set of certificates). */
3406 PRTCRPKCS7SIGNEDDATA pSignedData;
3407 PCRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(&This, iSignature, &pSignedData);
3408 rcExit = RTEXITCODE_FAILURE;
3409 if (pSignerInfo)
3410 {
3411 PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSignedData->SignerInfos.papItems[0]->IssuerAndSerialNumber;
3412 PCRTCRX509CERTIFICATE pCert;
3413 pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
3414 &pISN->Name, &pISN->SerialNumber);
3415 if (pCert)
3416 {
3417 /*
3418 * Write it out.
3419 */
3420 rcExit = WriteCertToFile(pCert, pszOut, fForce);
3421 }
3422 else
3423 RTMsgError("Certificate not found.");
3424 }
3425 else
3426 RTMsgError("Could not locate signature #%u!", iSignature);
3427
3428 /* Delete the signature data. */
3429 SignToolPkcs7Exe_Delete(&This);
3430 }
3431 return rcExit;
3432}
3433
3434
3435/*********************************************************************************************************************************
3436* The 'extract-signer-root' & 'extract-timestamp-root' commands. *
3437*********************************************************************************************************************************/
3438class BaseExtractState
3439{
3440public:
3441 const char *pszFile;
3442 const char *pszOut;
3443 RTLDRARCH enmLdrArch;
3444 unsigned cVerbosity;
3445 uint32_t iSignature;
3446 bool fForce;
3447 /** Timestamp or main signature. */
3448 bool const fTimestamp;
3449
3450 BaseExtractState(bool a_fTimestamp)
3451 : pszFile(NULL)
3452 , pszOut(NULL)
3453 , enmLdrArch(RTLDRARCH_WHATEVER)
3454 , cVerbosity(0)
3455 , iSignature(0)
3456 , fForce(false)
3457 , fTimestamp(a_fTimestamp)
3458 {
3459 }
3460};
3461
3462class RootExtractState : public BaseExtractState
3463{
3464public:
3465 CryptoStore RootStore;
3466 CryptoStore AdditionalStore;
3467
3468 RootExtractState(bool a_fTimestamp)
3469 : BaseExtractState(a_fTimestamp)
3470 , RootStore()
3471 , AdditionalStore()
3472 { }
3473
3474 /**
3475 * Creates the two stores, filling the root one with trusted CAs and
3476 * certificates found on the system or in the user's account.
3477 */
3478 bool init(void)
3479 {
3480 int rc = RTCrStoreCreateInMem(&this->RootStore.m_hStore, 0);
3481 if (RT_SUCCESS(rc))
3482 {
3483 rc = RTCrStoreCreateInMem(&this->AdditionalStore.m_hStore, 0);
3484 if (RT_SUCCESS(rc))
3485 return true;
3486 }
3487 RTMsgError("RTCrStoreCreateInMem failed: %Rrc", rc);
3488 return false;
3489 }
3490};
3491
3492
3493/**
3494 * Locates the target signature and certificate collection.
3495 */
3496static PRTCRPKCS7SIGNERINFO BaseExtractFindSignerInfo(SIGNTOOLPKCS7 *pThis, BaseExtractState *pState,
3497 PRTCRPKCS7SIGNEDDATA *ppSignedData, PCRTCRPKCS7SETOFCERTS *ppCerts)
3498{
3499 *ppSignedData = NULL;
3500 *ppCerts = NULL;
3501
3502 /*
3503 * Locate the target signature.
3504 */
3505 PRTCRPKCS7SIGNEDDATA pSignedData = NULL;
3506 PRTCRPKCS7SIGNERINFO pSignerInfo = SignToolPkcs7_FindNestedSignatureByIndex(pThis, pState->iSignature, &pSignedData);
3507 if (pSignerInfo)
3508 {
3509 /*
3510 * If the target is the timestamp we have to locate the relevant
3511 * timestamp signature and adjust the return values.
3512 */
3513 if (pState->fTimestamp)
3514 {
3515 for (uint32_t iItem = 0; iItem < pSignerInfo->UnauthenticatedAttributes.cItems; iItem++)
3516 {
3517 PCRTCRPKCS7ATTRIBUTE pAttr = pSignerInfo->UnauthenticatedAttributes.papItems[iItem];
3518 if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_COUNTER_SIGNATURES)
3519 {
3520 /* ASSUME that all counter signatures are timestamping. */
3521 if (pAttr->uValues.pCounterSignatures->cItems > 0)
3522 {
3523 *ppSignedData = pSignedData;
3524 *ppCerts = &pSignedData->Certificates;
3525 return pAttr->uValues.pCounterSignatures->papItems[0];
3526 }
3527 RTMsgWarning("Timestamp signature attribute is empty!");
3528 }
3529 else if (pAttr->enmType == RTCRPKCS7ATTRIBUTETYPE_MS_TIMESTAMP)
3530 {
3531 /* ASSUME that all valid timestamp signatures for now, pick the first. */
3532 if (pAttr->uValues.pContentInfos->cItems > 0)
3533 {
3534 PCRTCRPKCS7CONTENTINFO pContentInfo = pAttr->uValues.pContentInfos->papItems[0];
3535 if (RTAsn1ObjId_CompareWithString(&pContentInfo->ContentType, RTCR_PKCS7_SIGNED_DATA_OID) == 0)
3536 {
3537 pSignedData = pContentInfo->u.pSignedData;
3538 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCRTSPTSTINFO_OID) == 0)
3539 {
3540 if (pSignedData->SignerInfos.cItems > 0)
3541 {
3542 *ppSignedData = pSignedData;
3543 *ppCerts = &pSignedData->Certificates;
3544 return pSignedData->SignerInfos.papItems[0];
3545 }
3546 RTMsgWarning("Timestamp signature has no signers!");
3547 }
3548 else
3549 RTMsgWarning("Timestamp signature contains wrong content (%s)!",
3550 pSignedData->ContentInfo.ContentType.szObjId);
3551 }
3552 else
3553 RTMsgWarning("Timestamp signature is not SignedData but %s!", pContentInfo->ContentType.szObjId);
3554 }
3555 else
3556 RTMsgWarning("Timestamp signature attribute is empty!");
3557 }
3558 }
3559 RTMsgError("Cound not find a timestamp signature associated with signature #%u!", pState->iSignature);
3560 pSignerInfo = NULL;
3561 }
3562 else
3563 {
3564 *ppSignedData = pSignedData;
3565 *ppCerts = &pSignedData->Certificates;
3566 }
3567 }
3568 else
3569 RTMsgError("Could not locate signature #%u!", pState->iSignature);
3570 return pSignerInfo;
3571}
3572
3573
3574/** @callback_method_impl{FNRTDUMPPRINTFV} */
3575static DECLCALLBACK(void) DumpToStdOutPrintfV(void *pvUser, const char *pszFormat, va_list va)
3576{
3577 RT_NOREF(pvUser);
3578 RTPrintfV(pszFormat, va);
3579}
3580
3581
3582static RTEXITCODE RootExtractWorker2(SIGNTOOLPKCS7 *pThis, RootExtractState *pState, PRTERRINFOSTATIC pStaticErrInfo)
3583{
3584 /*
3585 * Locate the target signature.
3586 */
3587 PRTCRPKCS7SIGNEDDATA pSignedData;
3588 PCRTCRPKCS7SETOFCERTS pCerts;
3589 PCRTCRPKCS7SIGNERINFO pSignerInfo = BaseExtractFindSignerInfo(pThis,pState, &pSignedData, &pCerts);
3590 if (!pSignerInfo)
3591 return RTMsgErrorExitFailure("Could not locate signature #%u!", pState->iSignature);
3592
3593 /* The next bit is modelled on first half of rtCrPkcs7VerifySignerInfo. */
3594
3595 /*
3596 * Locate the signing certificate.
3597 */
3598 PCRTCRCERTCTX pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(pState->RootStore.m_hStore,
3599 &pSignerInfo->IssuerAndSerialNumber.Name,
3600 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3601 if (!pSignerCertCtx)
3602 pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(pState->AdditionalStore.m_hStore,
3603 &pSignerInfo->IssuerAndSerialNumber.Name,
3604 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3605
3606 PCRTCRX509CERTIFICATE pSignerCert;
3607 if (pSignerCertCtx)
3608 pSignerCert = pSignerCertCtx->pCert;
3609 else
3610 {
3611 pSignerCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(pCerts,
3612 &pSignerInfo->IssuerAndSerialNumber.Name,
3613 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
3614 if (!pSignerCert)
3615 return RTMsgErrorExitFailure("Certificate not found: serial=%.*Rhxs",
3616 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.cb,
3617 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.uData.pv);
3618 }
3619
3620 /*
3621 * Now we build paths so we can get to the root certificate.
3622 */
3623 RTCRX509CERTPATHS hCertPaths;
3624 int rc = RTCrX509CertPathsCreate(&hCertPaths, pSignerCert);
3625 if (RT_FAILURE(rc))
3626 return RTMsgErrorExitFailure("RTCrX509CertPathsCreate failed: %Rrc", rc);
3627
3628 /* Configure: */
3629 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
3630 rc = RTCrX509CertPathsSetTrustedStore(hCertPaths, pState->RootStore.m_hStore);
3631 if (RT_SUCCESS(rc))
3632 {
3633 rc = RTCrX509CertPathsSetUntrustedStore(hCertPaths, pState->AdditionalStore.m_hStore);
3634 if (RT_SUCCESS(rc))
3635 {
3636 rc = RTCrX509CertPathsSetUntrustedSet(hCertPaths, pCerts);
3637 if (RT_SUCCESS(rc))
3638 {
3639 /* We don't technically need this, I think. */
3640 rc = RTCrX509CertPathsSetTrustAnchorChecks(hCertPaths, true /*fEnable*/);
3641 if (RT_SUCCESS(rc))
3642 {
3643 /* Seems we might need this for the sha-1 certs and such. */
3644 RTCrX509CertPathsSetValidTimeSpec(hCertPaths, NULL);
3645
3646 /* Build the paths: */
3647 rc = RTCrX509CertPathsBuild(hCertPaths, RTErrInfoInitStatic(pStaticErrInfo));
3648 if (RT_SUCCESS(rc))
3649 {
3650 uint32_t const cPaths = RTCrX509CertPathsGetPathCount(hCertPaths);
3651
3652 /* Validate the paths: */
3653 uint32_t cValidPaths = 0;
3654 rc = RTCrX509CertPathsValidateAll(hCertPaths, &cValidPaths, RTErrInfoInitStatic(pStaticErrInfo));
3655 if (RT_SUCCESS(rc))
3656 {
3657 if (pState->cVerbosity > 0)
3658 RTMsgInfo("%u of %u paths are valid", cValidPaths, cPaths);
3659 if (pState->cVerbosity > 1)
3660 RTCrX509CertPathsDumpAll(hCertPaths, pState->cVerbosity, DumpToStdOutPrintfV, NULL);
3661
3662 /*
3663 * Now, pick the first valid path with a real certificate at the end.
3664 */
3665 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
3666 {
3667 PCRTCRX509CERTIFICATE pRootCert = NULL;
3668 PCRTCRX509NAME pSubject = NULL;
3669 bool fTrusted = false;
3670 int rcVerify = -1;
3671 rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/,
3672 &pSubject, NULL, &pRootCert, NULL /*ppCertCtx*/, &rcVerify);
3673 if (RT_SUCCESS(rc))
3674 {
3675 if (fTrusted && RT_SUCCESS(rcVerify) && pRootCert)
3676 {
3677 /*
3678 * Now copy out the certificate.
3679 */
3680 rcExit = WriteCertToFile(pRootCert, pState->pszOut, pState->fForce);
3681 break;
3682 }
3683 }
3684 else
3685 {
3686 RTMsgError("RTCrX509CertPathsQueryPathInfo failed: %Rrc", rc);
3687 break;
3688 }
3689 }
3690 }
3691 else
3692 {
3693 RTMsgError("RTCrX509CertPathsValidateAll failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
3694 RTCrX509CertPathsDumpAll(hCertPaths, pState->cVerbosity, DumpToStdOutPrintfV, NULL);
3695 }
3696 }
3697 else
3698 RTMsgError("RTCrX509CertPathsBuild failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
3699 }
3700 else
3701 RTMsgError("RTCrX509CertPathsSetTrustAnchorChecks failed: %Rrc", rc);
3702 }
3703 else
3704 RTMsgError("RTCrX509CertPathsSetUntrustedSet failed: %Rrc", rc);
3705 }
3706 else
3707 RTMsgError("RTCrX509CertPathsSetUntrustedStore failed: %Rrc", rc);
3708 }
3709 else
3710 RTMsgError("RTCrX509CertPathsSetTrustedStore failed: %Rrc", rc);
3711
3712 uint32_t cRefs = RTCrX509CertPathsRelease(hCertPaths);
3713 Assert(cRefs == 0); RT_NOREF(cRefs);
3714
3715 return rcExit;
3716}
3717
3718
3719static RTEXITCODE RootExtractWorker(RootExtractState *pState, PRTERRINFOSTATIC pStaticErrInfo)
3720{
3721 /*
3722 * Check that all we need is there and whether the output file exists.
3723 */
3724 if (!pState->pszFile)
3725 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
3726 if (!pState->pszOut)
3727 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
3728 if (!pState->fForce && RTPathExists(pState->pszOut))
3729 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pState->pszOut);
3730
3731 /*
3732 * Detect the type of file we're dealing with, do type specific setup and
3733 * call common worker to do the rest.
3734 */
3735 RTEXITCODE rcExit;
3736 RTSIGNTOOLFILETYPE enmFileType = DetectFileType(RTSIGNTOOLFILETYPE_DETECT, pState->pszFile);
3737 if (enmFileType == RTSIGNTOOLFILETYPE_EXE)
3738 {
3739 SIGNTOOLPKCS7EXE Exe;
3740 rcExit = SignToolPkcs7Exe_InitFromFile(&Exe, pState->pszFile, pState->cVerbosity, pState->enmLdrArch);
3741 if (rcExit == RTEXITCODE_SUCCESS)
3742 {
3743 rcExit = RootExtractWorker2(&Exe, pState, pStaticErrInfo);
3744 SignToolPkcs7Exe_Delete(&Exe);
3745 }
3746 }
3747 else if (enmFileType == RTSIGNTOOLFILETYPE_CAT)
3748 {
3749 SIGNTOOLPKCS7 Cat;
3750 rcExit = SignToolPkcs7_InitFromFile(&Cat, pState->pszFile, pState->cVerbosity);
3751 if (rcExit == RTEXITCODE_SUCCESS)
3752 {
3753 rcExit = RootExtractWorker2(&Cat, pState, pStaticErrInfo);
3754 SignToolPkcs7_Delete(&Cat);
3755 }
3756 }
3757 else
3758 rcExit = RTEXITCODE_FAILURE;
3759 return rcExit;
3760}
3761
3762
3763static RTEXITCODE HelpExtractRootCommon(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel, bool fTimestamp)
3764{
3765 RT_NOREF_PV(enmLevel);
3766 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
3767 "extract-%s-root [-v|--verbose] [-q|--quiet] [--signature-index|-i <num>] [--root <root-cert.der>] "
3768 "[--self-signed-roots-from-system] [--additional <supp-cert.der>] [--intermediate-certs-from-system] "
3769 "[--input] <signed-file> [-f|--force] [--output|-o] <outfile.cer>\n",
3770 fTimestamp ? "timestamp" : "signer");
3771 if (enmLevel == RTSIGNTOOLHELP_FULL)
3772 {
3773 RTStrmWrappedPrintf(pStrm, 0,
3774 "\n"
3775 "Extracts the root certificate of the %sgiven "
3776 "signature. If there are more than one valid certificate path, the first one with "
3777 "a full certificate will be picked.\n",
3778 fTimestamp ? "first timestamp associated with the " : "");
3779 RTStrmWrappedPrintf(pStrm, 0,
3780 "\n"
3781 "Options:\n"
3782 " -v, --verbose, -q, --quite\n"
3783 " Controls the noise level. The '-v' options are accumlative while '-q' is absolute.\n"
3784 " Default: -q\n"
3785 " -i <num>, --signature-index <num>\n"
3786 " Zero-based index of the signature to extract the root for.\n"
3787 " Default: -i 0\n"
3788 " -r <root-cert.file>, --root <root-cert.file>\n"
3789 " Use the certificate(s) in the specified file as a trusted root(s). "
3790 "The file format can be PEM or DER.\n"
3791 " -R, --self-signed-roots-from-system\n"
3792 " Use all self-signed trusted root certificates found on the system and associated with the "
3793 "current user as trusted roots. This is limited to self-signed certificates, so that we get "
3794 "a full chain even if a non-end-entity certificate is present in any of those system stores for "
3795 "some reason.\n"
3796 " -a <supp-cert.file>, --additional <supp-cert.file>\n"
3797 " Use the certificate(s) in the specified file as a untrusted intermediate certificates. "
3798 "The file format can be PEM or DER.\n"
3799 " -A, --intermediate-certs-from-system\n"
3800 " Use all certificates found on the system and associated with the current user as intermediate "
3801 "certification authorities.\n"
3802 " --input <signed-file>\n"
3803 " Signed executable or security cabinet file to examine. The '--input' option bit is optional "
3804 "and there to allow more flexible parameter ordering.\n"
3805 " -f, --force\n"
3806 " Overwrite existing output file. The default is not to overwriting any existing file.\n"
3807 " -o <outfile.cer> --output <outfile.cer>\n"
3808 " The name of the output file. Again the '-o|--output' bit is optional and only for flexibility.\n"
3809 );
3810 }
3811 return RTEXITCODE_SUCCESS;
3812}
3813
3814
3815static RTEXITCODE HandleExtractRootCommon(int cArgs, char **papszArgs, bool fTimestamp)
3816{
3817 /*
3818 * Parse arguments.
3819 */
3820 static const RTGETOPTDEF s_aOptions[] =
3821 {
3822 { "--root", 'r', RTGETOPT_REQ_STRING },
3823 { "--self-signed-roots-from-system", 'R', RTGETOPT_REQ_NOTHING },
3824 { "--additional", 'a', RTGETOPT_REQ_STRING },
3825 { "--intermediate-certs-from-system",'A', RTGETOPT_REQ_NOTHING },
3826 { "--add", 'a', RTGETOPT_REQ_STRING },
3827 { "--input", 'I', RTGETOPT_REQ_STRING },
3828 { "--output", 'o', RTGETOPT_REQ_STRING },
3829 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
3830 { "--force", 'f', RTGETOPT_REQ_NOTHING },
3831 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
3832 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
3833 };
3834 RTERRINFOSTATIC StaticErrInfo;
3835 RootExtractState State(fTimestamp);
3836 if (!State.init())
3837 return RTEXITCODE_FAILURE;
3838 RTGETOPTSTATE GetState;
3839 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3840 AssertRCReturn(rc, RTEXITCODE_FAILURE);
3841 RTGETOPTUNION ValueUnion;
3842 int ch;
3843 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
3844 {
3845 switch (ch)
3846 {
3847 case 'a':
3848 if (!State.AdditionalStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
3849 return RTEXITCODE_FAILURE;
3850 break;
3851
3852 case 'A':
3853 if (!State.AdditionalStore.addIntermediateCertsFromSystem(&StaticErrInfo))
3854 return RTEXITCODE_FAILURE;
3855 break;
3856
3857 case 'r':
3858 if (!State.RootStore.addFromFile(ValueUnion.psz, &StaticErrInfo))
3859 return RTEXITCODE_FAILURE;
3860 break;
3861
3862 case 'R':
3863 if (!State.RootStore.addSelfSignedRootsFromSystem(&StaticErrInfo))
3864 return RTEXITCODE_FAILURE;
3865 break;
3866
3867 case 'I': State.pszFile = ValueUnion.psz; break;
3868 case 'o': State.pszOut = ValueUnion.psz; break;
3869 case 'f': State.fForce = true; break;
3870 case 'i': State.iSignature = ValueUnion.u32; break;
3871 case 'v': State.cVerbosity++; break;
3872 case 'q': State.cVerbosity = 0; break;
3873 case 'V': return HandleVersion(cArgs, papszArgs);
3874 case 'h': return HelpExtractRootCommon(g_pStdOut, RTSIGNTOOLHELP_FULL, fTimestamp);
3875
3876 case VINF_GETOPT_NOT_OPTION:
3877 if (!State.pszFile)
3878 State.pszFile = ValueUnion.psz;
3879 else if (!State.pszOut)
3880 State.pszOut = ValueUnion.psz;
3881 else
3882 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
3883 break;
3884
3885 default:
3886 return RTGetOptPrintError(ch, &ValueUnion);
3887 }
3888 }
3889 return RootExtractWorker(&State, &StaticErrInfo);
3890}
3891
3892
3893static RTEXITCODE HelpExtractSignerRoot(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
3894{
3895 return HelpExtractRootCommon(pStrm, enmLevel, false /*fTimestamp*/);
3896}
3897
3898
3899static RTEXITCODE HandleExtractSignerRoot(int cArgs, char **papszArgs)
3900{
3901 return HandleExtractRootCommon(cArgs, papszArgs, false /*fTimestamp*/ );
3902}
3903
3904
3905static RTEXITCODE HelpExtractTimestampRoot(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
3906{
3907 return HelpExtractRootCommon(pStrm, enmLevel, true /*fTimestamp*/);
3908}
3909
3910
3911static RTEXITCODE HandleExtractTimestampRoot(int cArgs, char **papszArgs)
3912{
3913 return HandleExtractRootCommon(cArgs, papszArgs, true /*fTimestamp*/ );
3914}
3915
3916
3917/*********************************************************************************************************************************
3918* The 'extract-exe-signature' command. *
3919*********************************************************************************************************************************/
3920
3921static RTEXITCODE HelpExtractExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
3922{
3923 RT_NOREF_PV(enmLevel);
3924 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
3925 "extract-exe-signerature [--input|--exe|-e] <exe> [--output|-o] <outfile.pkcs7>\n");
3926 return RTEXITCODE_SUCCESS;
3927}
3928
3929static RTEXITCODE HandleExtractExeSignature(int cArgs, char **papszArgs)
3930{
3931 /*
3932 * Parse arguments.
3933 */
3934 static const RTGETOPTDEF s_aOptions[] =
3935 {
3936 { "--exe", 'e', RTGETOPT_REQ_STRING },
3937 { "--input", 'e', RTGETOPT_REQ_STRING },
3938 { "--output", 'o', RTGETOPT_REQ_STRING },
3939 { "--force", 'f', RTGETOPT_REQ_NOTHING },
3940 };
3941
3942 const char *pszExe = NULL;
3943 const char *pszOut = NULL;
3944 RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
3945 unsigned cVerbosity = 0;
3946 bool fForce = false;
3947
3948 RTGETOPTSTATE GetState;
3949 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3950 AssertRCReturn(rc, RTEXITCODE_FAILURE);
3951 RTGETOPTUNION ValueUnion;
3952 int ch;
3953 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
3954 {
3955 switch (ch)
3956 {
3957 case 'e': pszExe = ValueUnion.psz; break;
3958 case 'o': pszOut = ValueUnion.psz; break;
3959 case 'f': fForce = true; break;
3960 case 'V': return HandleVersion(cArgs, papszArgs);
3961 case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
3962
3963 case VINF_GETOPT_NOT_OPTION:
3964 if (!pszExe)
3965 pszExe = ValueUnion.psz;
3966 else if (!pszOut)
3967 pszOut = ValueUnion.psz;
3968 else
3969 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
3970 break;
3971
3972 default:
3973 return RTGetOptPrintError(ch, &ValueUnion);
3974 }
3975 }
3976 if (!pszExe)
3977 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
3978 if (!pszOut)
3979 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
3980 if (!fForce && RTPathExists(pszOut))
3981 return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
3982
3983 /*
3984 * Do it.
3985 */
3986 /* Read & decode the PKCS#7 signature. */
3987 SIGNTOOLPKCS7EXE This;
3988 RTEXITCODE rcExit = SignToolPkcs7Exe_InitFromFile(&This, pszExe, cVerbosity, enmLdrArch);
3989 if (rcExit == RTEXITCODE_SUCCESS)
3990 {
3991 /*
3992 * Write out the PKCS#7 signature.
3993 */
3994 RTFILE hFile;
3995 rc = RTFileOpen(&hFile, pszOut,
3996 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | (fForce ? RTFILE_O_CREATE_REPLACE : RTFILE_O_CREATE));
3997 if (RT_SUCCESS(rc))
3998 {
3999 rc = RTFileWrite(hFile, This.pbBuf, This.cbBuf, NULL);
4000 if (RT_SUCCESS(rc))
4001 {
4002 rc = RTFileClose(hFile);
4003 if (RT_SUCCESS(rc))
4004 {
4005 hFile = NIL_RTFILE;
4006 RTMsgInfo("Successfully wrote %u bytes to '%s'", This.cbBuf, pszOut);
4007 rcExit = RTEXITCODE_SUCCESS;
4008 }
4009 else
4010 RTMsgError("RTFileClose failed: %Rrc", rc);
4011 }
4012 else
4013 RTMsgError("RTFileWrite failed: %Rrc", rc);
4014 RTFileClose(hFile);
4015 }
4016 else
4017 RTMsgError("Error opening '%s' for writing: %Rrc", pszOut, rc);
4018
4019 /* Delete the signature data. */
4020 SignToolPkcs7Exe_Delete(&This);
4021 }
4022 return rcExit;
4023}
4024
4025
4026/*********************************************************************************************************************************
4027* The 'add-nested-exe-signature' command. *
4028*********************************************************************************************************************************/
4029
4030static RTEXITCODE HelpAddNestedExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4031{
4032 RT_NOREF_PV(enmLevel);
4033 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4034 "add-nested-exe-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-exe> <source-exe>\n");
4035 if (enmLevel == RTSIGNTOOLHELP_FULL)
4036 RTStrmWrappedPrintf(pStrm, 0,
4037 "\n"
4038 "The --debug option allows the source-exe to be omitted in order to test the "
4039 "encoding and PE file modification.\n"
4040 "\n"
4041 "The --prepend option puts the nested signature first rather than appending it "
4042 "to the end of of the nested signature set. Windows reads nested signatures in "
4043 "reverse order, so --prepend will logically putting it last.\n");
4044 return RTEXITCODE_SUCCESS;
4045}
4046
4047
4048static RTEXITCODE HandleAddNestedExeSignature(int cArgs, char **papszArgs)
4049{
4050 /*
4051 * Parse arguments.
4052 */
4053 static const RTGETOPTDEF s_aOptions[] =
4054 {
4055 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
4056 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4057 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
4058 };
4059
4060 const char *pszDst = NULL;
4061 const char *pszSrc = NULL;
4062 unsigned cVerbosity = 0;
4063 bool fDebug = false;
4064 bool fPrepend = false;
4065
4066 RTGETOPTSTATE GetState;
4067 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4068 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4069 RTGETOPTUNION ValueUnion;
4070 int ch;
4071 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4072 {
4073 switch (ch)
4074 {
4075 case 'v': cVerbosity++; break;
4076 case 'd': fDebug = pszSrc == NULL; break;
4077 case 'p': fPrepend = true; break;
4078 case 'V': return HandleVersion(cArgs, papszArgs);
4079 case 'h': return HelpAddNestedExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4080
4081 case VINF_GETOPT_NOT_OPTION:
4082 if (!pszDst)
4083 pszDst = ValueUnion.psz;
4084 else if (!pszSrc)
4085 {
4086 pszSrc = ValueUnion.psz;
4087 fDebug = false;
4088 }
4089 else
4090 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4091 break;
4092
4093 default:
4094 return RTGetOptPrintError(ch, &ValueUnion);
4095 }
4096 }
4097 if (!pszDst)
4098 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination executable given.");
4099 if (!pszSrc && !fDebug)
4100 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source executable file given.");
4101
4102 /*
4103 * Do it.
4104 */
4105 /* Read & decode the source PKCS#7 signature. */
4106 SIGNTOOLPKCS7EXE Src;
4107 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7Exe_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
4108 if (rcExit == RTEXITCODE_SUCCESS)
4109 {
4110 /* Ditto for the destination PKCS#7 signature. */
4111 SIGNTOOLPKCS7EXE Dst;
4112 rcExit = SignToolPkcs7Exe_InitFromFile(&Dst, pszDst, cVerbosity);
4113 if (rcExit == RTEXITCODE_SUCCESS)
4114 {
4115 /* Do the signature manipulation. */
4116 if (pszSrc)
4117 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
4118 if (rcExit == RTEXITCODE_SUCCESS)
4119 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
4120
4121 /* Update the destination executable file. */
4122 if (rcExit == RTEXITCODE_SUCCESS)
4123 rcExit = SignToolPkcs7Exe_WriteSignatureToFile(&Dst, cVerbosity);
4124
4125 SignToolPkcs7Exe_Delete(&Dst);
4126 }
4127 if (pszSrc)
4128 SignToolPkcs7Exe_Delete(&Src);
4129 }
4130
4131 return rcExit;
4132}
4133
4134
4135/*********************************************************************************************************************************
4136* The 'add-nested-cat-signature' command. *
4137*********************************************************************************************************************************/
4138
4139static RTEXITCODE HelpAddNestedCatSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4140{
4141 RT_NOREF_PV(enmLevel);
4142 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4143 "add-nested-cat-signature [-v|--verbose] [-d|--debug] [-p|--prepend] <destination-cat> <source-cat>\n");
4144 if (enmLevel == RTSIGNTOOLHELP_FULL)
4145 RTStrmWrappedPrintf(pStrm, 0,
4146 "\n"
4147 "The --debug option allows the source-cat to be omitted in order to test the "
4148 "ASN.1 re-encoding of the destination catalog file.\n"
4149 "\n"
4150 "The --prepend option puts the nested signature first rather than appending it "
4151 "to the end of of the nested signature set. Windows reads nested signatures in "
4152 "reverse order, so --prepend will logically putting it last.\n");
4153 return RTEXITCODE_SUCCESS;
4154}
4155
4156
4157static RTEXITCODE HandleAddNestedCatSignature(int cArgs, char **papszArgs)
4158{
4159 /*
4160 * Parse arguments.
4161 */
4162 static const RTGETOPTDEF s_aOptions[] =
4163 {
4164 { "--prepend", 'p', RTGETOPT_REQ_NOTHING },
4165 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4166 { "--debug", 'd', RTGETOPT_REQ_NOTHING },
4167 };
4168
4169 const char *pszDst = NULL;
4170 const char *pszSrc = NULL;
4171 unsigned cVerbosity = 0;
4172 bool fDebug = false;
4173 bool fPrepend = false;
4174
4175 RTGETOPTSTATE GetState;
4176 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4177 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4178 RTGETOPTUNION ValueUnion;
4179 int ch;
4180 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4181 {
4182 switch (ch)
4183 {
4184 case 'v': cVerbosity++; break;
4185 case 'd': fDebug = pszSrc == NULL; break;
4186 case 'p': fPrepend = true; break;
4187 case 'V': return HandleVersion(cArgs, papszArgs);
4188 case 'h': return HelpAddNestedCatSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4189
4190 case VINF_GETOPT_NOT_OPTION:
4191 if (!pszDst)
4192 pszDst = ValueUnion.psz;
4193 else if (!pszSrc)
4194 {
4195 pszSrc = ValueUnion.psz;
4196 fDebug = false;
4197 }
4198 else
4199 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
4200 break;
4201
4202 default:
4203 return RTGetOptPrintError(ch, &ValueUnion);
4204 }
4205 }
4206 if (!pszDst)
4207 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No destination catalog file given.");
4208 if (!pszSrc && !fDebug)
4209 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No source catalog file given.");
4210
4211 /*
4212 * Do it.
4213 */
4214 /* Read & decode the source PKCS#7 signature. */
4215 SIGNTOOLPKCS7 Src;
4216 RTEXITCODE rcExit = pszSrc ? SignToolPkcs7_InitFromFile(&Src, pszSrc, cVerbosity) : RTEXITCODE_SUCCESS;
4217 if (rcExit == RTEXITCODE_SUCCESS)
4218 {
4219 /* Ditto for the destination PKCS#7 signature. */
4220 SIGNTOOLPKCS7EXE Dst;
4221 rcExit = SignToolPkcs7_InitFromFile(&Dst, pszDst, cVerbosity);
4222 if (rcExit == RTEXITCODE_SUCCESS)
4223 {
4224 /* Do the signature manipulation. */
4225 if (pszSrc)
4226 rcExit = SignToolPkcs7_AddNestedSignature(&Dst, &Src, cVerbosity, fPrepend);
4227 if (rcExit == RTEXITCODE_SUCCESS)
4228 rcExit = SignToolPkcs7_Encode(&Dst, cVerbosity);
4229
4230 /* Update the destination executable file. */
4231 if (rcExit == RTEXITCODE_SUCCESS)
4232 rcExit = SignToolPkcs7_WriteSignatureToFile(&Dst, pszDst, cVerbosity);
4233
4234 SignToolPkcs7_Delete(&Dst);
4235 }
4236 if (pszSrc)
4237 SignToolPkcs7_Delete(&Src);
4238 }
4239
4240 return rcExit;
4241}
4242
4243
4244/*********************************************************************************************************************************
4245* The 'add-timestamp-exe-signature' command. *
4246*********************************************************************************************************************************/
4247#ifndef IPRT_SIGNTOOL_NO_SIGNING
4248
4249static RTEXITCODE HelpAddTimestampExeSignature(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4250{
4251 RT_NOREF_PV(enmLevel);
4252
4253 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4254 "add-timestamp-exe-signature [-v|--verbose] [--signature-index|-i <num>] "
4255 OPT_CERT_KEY_SYNOPSIS("--timestamp-", "")
4256 "[--timestamp-type old|new] "
4257 "[--timestamp-override <partial-isots>] "
4258 "[--replace-existing|-r] "
4259 "<exe>\n");
4260 if (enmLevel == RTSIGNTOOLHELP_FULL)
4261 RTStrmWrappedPrintf(pStrm, 0,
4262 "This is mainly to test timestamp code.\n"
4263 "\n"
4264 "The --timestamp-override option can take a partial or full ISO timestamp. It is merged "
4265 "with the current time if partial.\n"
4266 "\n");
4267 return RTEXITCODE_SUCCESS;
4268}
4269
4270static RTEXITCODE HandleAddTimestampExeSignature(int cArgs, char **papszArgs)
4271{
4272 /*
4273 * Parse arguments.
4274 */
4275 static const RTGETOPTDEF s_aOptions[] =
4276 {
4277 { "--signature-index", 'i', RTGETOPT_REQ_UINT32 },
4278 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "", 1000),
4279 { "--timestamp-type", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4280 { "--timestamp-override", OPT_TIMESTAMP_OVERRIDE, RTGETOPT_REQ_STRING },
4281 { "--replace-existing", 'r', RTGETOPT_REQ_NOTHING },
4282 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4283 };
4284
4285 unsigned cVerbosity = 0;
4286 unsigned iSignature = 0;
4287 bool fReplaceExisting = false;
4288 SignToolTimestampOpts TimestampOpts("timestamp");
4289 RTTIMESPEC SigningTime;
4290 RTTimeNow(&SigningTime);
4291
4292 RTGETOPTSTATE GetState;
4293 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4294 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4295
4296 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
4297 RTGETOPTUNION ValueUnion;
4298 int ch;
4299 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4300 {
4301 RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
4302 switch (ch)
4303 {
4304 OPT_CERT_KEY_SWITCH_CASES(TimestampOpts, 1000, ch, ValueUnion, rcExit2);
4305 case 'i': iSignature = ValueUnion.u32; break;
4306 case OPT_TIMESTAMP_TYPE: rcExit2 = HandleOptTimestampType(&TimestampOpts, ValueUnion.psz); break;
4307 case OPT_TIMESTAMP_OVERRIDE: rcExit2 = HandleOptTimestampOverride(&SigningTime, ValueUnion.psz); break;
4308 case 'r': fReplaceExisting = true; break;
4309 case 'v': cVerbosity++; break;
4310 case 'V': return HandleVersion(cArgs, papszArgs);
4311 case 'h': return HelpAddTimestampExeSignature(g_pStdOut, RTSIGNTOOLHELP_FULL);
4312
4313 case VINF_GETOPT_NOT_OPTION:
4314 /* Do final certificate and key option processing (first file only). */
4315 rcExit2 = TimestampOpts.finalizeOptions(cVerbosity);
4316 if (rcExit2 == RTEXITCODE_SUCCESS)
4317 {
4318 /* Do the work: */
4319 SIGNTOOLPKCS7EXE Exe;
4320 rcExit2 = SignToolPkcs7Exe_InitFromFile(&Exe, ValueUnion.psz, cVerbosity);
4321 if (rcExit2 == RTEXITCODE_SUCCESS)
4322 {
4323 rcExit2 = SignToolPkcs7_AddTimestampSignature(&Exe, cVerbosity, iSignature, fReplaceExisting,
4324 SigningTime, &TimestampOpts);
4325 if (rcExit2 == RTEXITCODE_SUCCESS)
4326 rcExit2 = SignToolPkcs7_Encode(&Exe, cVerbosity);
4327 if (rcExit2 == RTEXITCODE_SUCCESS)
4328 rcExit2 = SignToolPkcs7Exe_WriteSignatureToFile(&Exe, cVerbosity);
4329 SignToolPkcs7Exe_Delete(&Exe);
4330 }
4331 if (rcExit2 != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
4332 rcExit = rcExit2;
4333 rcExit2 = RTEXITCODE_SUCCESS;
4334 }
4335 break;
4336
4337 default:
4338 return RTGetOptPrintError(ch, &ValueUnion);
4339 }
4340
4341 if (rcExit2 != RTEXITCODE_SUCCESS)
4342 {
4343 rcExit = rcExit2;
4344 break;
4345 }
4346 }
4347 return rcExit;
4348}
4349
4350#endif /*!IPRT_SIGNTOOL_NO_SIGNING */
4351
4352
4353/*********************************************************************************************************************************
4354* The 'sign-exe' command. *
4355*********************************************************************************************************************************/
4356#ifndef IPRT_SIGNTOOL_NO_SIGNING
4357
4358static RTEXITCODE HelpSign(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
4359{
4360 RT_NOREF_PV(enmLevel);
4361
4362 RTStrmWrappedPrintf(pStrm, RTSTRMWRAPPED_F_HANGING_INDENT,
4363 "sign [-v|--verbose] "
4364 "[--file-type exe|cat] "
4365 "[--type|/fd sha1|sha256] "
4366 "[--hash-pages|/ph] "
4367 "[--no-hash-pages|/nph] "
4368 "[--append/as] "
4369 "[--no-signing-time] "
4370 "[--add-cert <file>] "
4371 "[--timestamp-type old|new] "
4372 "[--timestamp-override <partial-isots>] "
4373 "[--verbose|/debug|-v] "
4374 OPT_CERT_KEY_SYNOPSIS("--", "")
4375 OPT_CERT_KEY_SYNOPSIS("--timestamp-", "")
4376 //OPT_CERT_KEY_SYNOPSIS("--timestamp-", "-2") - doesn't work, windows only uses one. Check again with new-style signatures
4377 "<exe>\n");
4378 if (enmLevel == RTSIGNTOOLHELP_FULL)
4379 RTStrmWrappedPrintf(pStrm, 0,
4380 "\n"
4381 "Create a new code signature for an executable or catalog.\n"
4382 "\n"
4383 "Options:\n"
4384 " --append, /as\n"
4385 " Append the signature if one already exists. The default is to replace any existing signature.\n"
4386 " --type sha1|sha256, /fd sha1|sha256\n"
4387 " Signature type, SHA-1 or SHA-256.\n"
4388 " --hash-pages, /ph, --no-page-hashes, /nph\n"
4389 " Enables or disables page hashing. Ignored for catalog files. Default: --no-page-hashes\n"
4390 " --add-cert <file>, /ac <file>\n"
4391 " Adds (first) certificate from the file to the signature. Both PEM and DER (binary) encodings "
4392 "are accepted. Repeat to add more certiifcates.\n"
4393 " --timestamp-override <partial-iso-timestamp>\n"
4394 " This specifies the signing time as a ISO timestamp. Partial timestamps are merged with the "
4395 "current time. This is applied to any timestamp signature as well as the signingTime attribute of "
4396 "main signature. Higher resolution than seconds is not supported. Default: Current time.\n"
4397 " --no-signing-time\n"
4398 " Don't set the signing time on the main signature, only on the timestamp one. Unfortunately, "
4399 "this doesn't work without modifying OpenSSL a little.\n"
4400 " --timestamp-type old|new\n"
4401 " Selects the timstamp type. 'old' is the old style /t <url> stuff from signtool.exe. "
4402 "'new' means a RTC-3161 timstamp - currently not implemented. Default: old\n"
4403 //" --timestamp-type-2 old|new\n"
4404 //" Same as --timestamp-type but for the 2nd timstamp signature.\n"
4405 "\n"
4406 //"Certificate and Key Options (--timestamp-cert-name[-2] etc for timestamps):\n"
4407 "Certificate and Key Options (--timestamp-cert-name etc for timestamps):\n"
4408 " --cert-subject <partial name>, /n <partial name>\n"
4409 " Locate the main signature signing certificate and key, unless anything else is given, "
4410 "by the given name substring. Overrides any previous --cert-sha1 and --cert-file options.\n"
4411 " --cert-sha1 <hex bytes>, /sha1 <hex bytes>\n"
4412 " Locate the main signature signing certificate and key, unless anything else is given, "
4413 "by the given thumbprint. The hex bytes can be space separated, colon separated, just "
4414 "bunched together, or a mix of these. This overrids any previous --cert-name and --cert-file "
4415 "options.\n"
4416 " --cert-store <name>, /s <store>\n"
4417 " Certificate store to search when using --cert-name or --cert-sha1. Default: MY\n"
4418 " --cert-machine-store, /sm\n"
4419 " Use the machine store rather the ones of the current user.\n"
4420 " --cert-file <file>, /f <file>\n"
4421 " Load the certificate and key, unless anything else is given, from given file. Both PEM and "
4422 "DER (binary) encodings are supported. Keys file can be RSA or PKCS#12 formatted.\n"
4423 " --key-file <file>\n"
4424 " Load the private key from the given file. Support RSA and PKCS#12 formatted files.\n"
4425 " --key-password <password>, /p <password>\n"
4426 " Password to use to decrypt a PKCS#12 password file.\n"
4427 " --key-password-file <file>|stdin\n"
4428 " Load password to decrypt the password file from the given file or from stdin.\n"
4429 " --key-name <name>, /kc <name>\n"
4430 " The private key container name. Not implemented.\n"
4431 " --key-provider <name>, /csp <name>\n"
4432 " The name of the crypto provider where the private key conatiner specified via --key-name "
4433 "can be found.\n"
4434 );
4435
4436 return RTEXITCODE_SUCCESS;
4437}
4438
4439
4440static RTEXITCODE HandleSign(int cArgs, char **papszArgs)
4441{
4442 /*
4443 * Parse arguments.
4444 */
4445 static const RTGETOPTDEF s_aOptions[] =
4446 {
4447 { "--append", 'A', RTGETOPT_REQ_NOTHING },
4448 { "/as", 'A', RTGETOPT_REQ_NOTHING },
4449 { "/a", OPT_IGNORED, RTGETOPT_REQ_NOTHING }, /* select best cert automatically */
4450 { "--type", 't', RTGETOPT_REQ_STRING },
4451 { "/fd", 't', RTGETOPT_REQ_STRING },
4452 { "--hash-pages", OPT_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4453 { "/ph", OPT_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4454 { "--no-hash-pages", OPT_NO_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4455 { "/nph", OPT_NO_HASH_PAGES, RTGETOPT_REQ_NOTHING },
4456 { "--add-cert", OPT_ADD_CERT, RTGETOPT_REQ_STRING },
4457 { "/ac", OPT_ADD_CERT, RTGETOPT_REQ_STRING },
4458 { "--description", 'd', RTGETOPT_REQ_STRING },
4459 { "--desc", 'd', RTGETOPT_REQ_STRING },
4460 { "/d", 'd', RTGETOPT_REQ_STRING },
4461 { "--description-url", 'D', RTGETOPT_REQ_STRING },
4462 { "--desc-url", 'D', RTGETOPT_REQ_STRING },
4463 { "/du", 'D', RTGETOPT_REQ_STRING },
4464 { "--no-signing-time", OPT_NO_SIGNING_TIME, RTGETOPT_REQ_NOTHING },
4465 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--", "", 1000),
4466 OPT_CERT_KEY_GETOPTDEF_COMPAT_ENTRIES( 1000),
4467 OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "", 1020),
4468 //OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "-1", 1020),
4469 //OPT_CERT_KEY_GETOPTDEF_ENTRIES("--timestamp-", "-2", 1040), - disabled as windows cannot make use of it. Try again when
4470 // new-style timestamp signatures has been implemented. Otherwise, just add two primary signatures with the two
4471 // different timestamps certificates / hashes / whatever.
4472 { "--timestamp-type", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4473 { "--timestamp-type-1", OPT_TIMESTAMP_TYPE, RTGETOPT_REQ_STRING },
4474 { "--timestamp-type-2", OPT_TIMESTAMP_TYPE_2, RTGETOPT_REQ_STRING },
4475 { "--timestamp-override", OPT_TIMESTAMP_OVERRIDE, RTGETOPT_REQ_STRING },
4476 { "--file-type", OPT_FILE_TYPE, RTGETOPT_REQ_STRING },
4477 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
4478 { "/v", 'v', RTGETOPT_REQ_NOTHING },
4479 { "/debug", 'v', RTGETOPT_REQ_NOTHING },
4480 };
4481
4482 unsigned cVerbosity = 0;
4483 RTDIGESTTYPE enmSigType = RTDIGESTTYPE_SHA1;
4484 bool fReplaceExisting = true;
4485 bool fHashPages = false;
4486 bool fNoSigningTime = false;
4487 RTSIGNTOOLFILETYPE enmForceFileType = RTSIGNTOOLFILETYPE_DETECT;
4488 SignToolKeyPair SigningCertKey("signing", true);
4489 CryptoStore AddCerts;
4490 const char *pszDescription = NULL; /** @todo implement putting descriptions into the OpusInfo stuff. */
4491 const char *pszDescriptionUrl = NULL;
4492 SignToolTimestampOpts aTimestampOpts[2] = { SignToolTimestampOpts("timestamp"), SignToolTimestampOpts("timestamp#2") };
4493 RTTIMESPEC SigningTime;
4494 RTTimeNow(&SigningTime);
4495
4496 RTGETOPTSTATE GetState;
4497 int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4498 AssertRCReturn(rc, RTEXITCODE_FAILURE);
4499
4500 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
4501 RTGETOPTUNION ValueUnion;
4502 int ch;
4503 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
4504 {
4505 RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
4506 switch (ch)
4507 {
4508 OPT_CERT_KEY_SWITCH_CASES(SigningCertKey, 1000, ch, ValueUnion, rcExit2);
4509 OPT_CERT_KEY_SWITCH_CASES(aTimestampOpts[0], 1020, ch, ValueUnion, rcExit2);
4510 OPT_CERT_KEY_SWITCH_CASES(aTimestampOpts[1], 1040, ch, ValueUnion, rcExit2);
4511 case 't': rcExit2 = HandleOptSignatureType(&enmSigType, ValueUnion.psz); break;
4512 case 'A': fReplaceExisting = false; break;
4513 case 'd': pszDescription = ValueUnion.psz; break;
4514 case 'D': pszDescriptionUrl = ValueUnion.psz; break;
4515 case OPT_HASH_PAGES: fHashPages = true; break;
4516 case OPT_NO_HASH_PAGES: fHashPages = false; break;
4517 case OPT_NO_SIGNING_TIME: fNoSigningTime = true; break;
4518 case OPT_ADD_CERT: rcExit2 = HandleOptAddCert(&AddCerts.m_hStore, ValueUnion.psz); break;
4519 case OPT_TIMESTAMP_TYPE: rcExit2 = HandleOptTimestampType(&aTimestampOpts[0], ValueUnion.psz); break;
4520 case OPT_TIMESTAMP_TYPE_2: rcExit2 = HandleOptTimestampType(&aTimestampOpts[1], ValueUnion.psz); break;
4521 case OPT_TIMESTAMP_OVERRIDE: rcExit2 = HandleOptTimestampOverride(&SigningTime, ValueUnion.psz); break;
4522 case OPT_FILE_TYPE: rcExit2 = HandleOptFileType(&enmForceFileType, ValueUnion.psz); break;
4523 case OPT_IGNORED: break;
4524 case 'v': cVerbosity++; break;
4525 case 'V': return HandleVersion(cArgs, papszArgs);
4526 case 'h': return HelpSign(g_pStdOut, RTSIGNTOOLHELP_FULL);
4527
4528 case VINF_GETOPT_NOT_OPTION:
4529 /*
4530 * Do final certificate and key option processing (first file only).
4531 */
4532 rcExit2 = SigningCertKey.finalizeOptions(cVerbosity);
4533 for (unsigned i = 0; rcExit2 == RTEXITCODE_SUCCESS && i < RT_ELEMENTS(aTimestampOpts); i++)
4534 rcExit2 = aTimestampOpts[i].finalizeOptions(cVerbosity);
4535 if (rcExit2 == RTEXITCODE_SUCCESS)
4536 {
4537 /*
4538 * Detect file type.
4539 */
4540 RTSIGNTOOLFILETYPE enmFileType = DetectFileType(enmForceFileType, ValueUnion.psz);
4541 if (enmFileType == RTSIGNTOOLFILETYPE_EXE)
4542 {
4543 /*
4544 * Sign executable image.
4545 */
4546 SIGNTOOLPKCS7EXE Exe;
4547 rcExit2 = SignToolPkcs7Exe_InitFromFile(&Exe, ValueUnion.psz, cVerbosity,
4548 RTLDRARCH_WHATEVER, true /*fAllowUnsigned*/);
4549 if (rcExit2 == RTEXITCODE_SUCCESS)
4550 {
4551 rcExit2 = SignToolPkcs7_AddOrReplaceSignature(&Exe, cVerbosity, enmSigType, fReplaceExisting,
4552 fHashPages, fNoSigningTime, &SigningCertKey,
4553 AddCerts.m_hStore, SigningTime,
4554 RT_ELEMENTS(aTimestampOpts), aTimestampOpts);
4555 if (rcExit2 == RTEXITCODE_SUCCESS)
4556 rcExit2 = SignToolPkcs7_Encode(&Exe, cVerbosity);
4557 if (rcExit2 == RTEXITCODE_SUCCESS)
4558 rcExit2 = SignToolPkcs7Exe_WriteSignatureToFile(&Exe, cVerbosity);
4559 SignToolPkcs7Exe_Delete(&Exe);
4560 }
4561 }
4562 else if (enmFileType == RTSIGNTOOLFILETYPE_CAT)
4563 {
4564 /*
4565 * Sign catalog file.
4566 */
4567 SIGNTOOLPKCS7 Cat;
4568 rcExit2 = SignToolPkcs7_InitFromFile(&Cat, ValueUnion.psz, cVerbosity);
4569 if (rcExit2 == RTEXITCODE_SUCCESS)
4570 {
4571 rcExit2 = SignToolPkcs7_AddOrReplaceCatSignature(&Cat, cVerbosity, enmSigType, fReplaceExisting,
4572 fNoSigningTime, &SigningCertKey,
4573 AddCerts.m_hStore, SigningTime,
4574 RT_ELEMENTS(aTimestampOpts), aTimestampOpts);
457