VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/Installer/Loader/VBoxWindowsAdditions.cpp

最後變更 在這個檔案是 107861,由 vboxsync 提交於 8 週 前

Add/Nt/Installer: Pick right NSIS installer from the loader stub. [build fix]

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 50.3 KB
 
1/* $Id: VBoxWindowsAdditions.cpp 107861 2025-01-20 18:13:12Z vboxsync $ */
2/** @file
3 * VBoxWindowsAdditions - The Windows Guest Additions Loader.
4 *
5 * This is STUB which select whether to install 32-bit or 64-bit additions.
6 */
7
8/*
9 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
10 *
11 * This file is part of VirtualBox base platform packages, as
12 * available from https://www.alldomusa.eu.org.
13 *
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation, in version 3 of the
17 * License.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, see <https://www.gnu.org/licenses>.
26 *
27 * SPDX-License-Identifier: GPL-3.0-only
28 */
29
30
31/*********************************************************************************************************************************
32* Header Files *
33*********************************************************************************************************************************/
34#define UNICODE /* For resource related macros. */
35#include <iprt/cdefs.h>
36#include <iprt/win/windows.h>
37#include <Wintrust.h>
38#include <Softpub.h>
39#ifndef ERROR_ELEVATION_REQUIRED /* Windows Vista and later. */
40# define ERROR_ELEVATION_REQUIRED 740
41#endif
42
43#include <iprt/string.h>
44#include <iprt/utf16.h>
45
46#include "NoCrtOutput.h"
47
48#ifdef VBOX_SIGNING_MODE
49# include "BuildCerts.h"
50# include "TimestampRootCerts.h"
51#endif
52
53#ifdef VBOX_SIGNING_MODE
54# if 1 /* Whether to use IPRT or Windows to verify the executable signatures. */
55# include <iprt/err.h>
56# include <iprt/initterm.h>
57# include <iprt/ldr.h>
58# include <iprt/message.h>
59# include <iprt/stream.h>
60# include <iprt/crypto/pkcs7.h>
61# include <iprt/crypto/store.h>
62# endif
63#endif
64
65
66/*********************************************************************************************************************************
67* Structures and Typedefs *
68*********************************************************************************************************************************/
69typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
70typedef BOOL (WINAPI *PFNISWOW64PROCESS2)(HANDLE, USHORT *, USHORT *);
71
72
73#ifdef VBOX_SIGNING_MODE
74# if 1 /* Whether to use IPRT or Windows to verify the executable signatures. */
75/* This section is borrowed from RTSignTool.cpp */
76
77class CryptoStore
78{
79public:
80 RTCRSTORE m_hStore;
81
82 CryptoStore()
83 : m_hStore(NIL_RTCRSTORE)
84 {
85 }
86
87 ~CryptoStore()
88 {
89 if (m_hStore != NIL_RTCRSTORE)
90 {
91 uint32_t cRefs = RTCrStoreRelease(m_hStore);
92 Assert(cRefs == 0); RT_NOREF(cRefs);
93 m_hStore = NIL_RTCRSTORE;
94 }
95 }
96
97 /**
98 * Adds one or more certificates from the given file.
99 *
100 * @returns boolean success indicator.
101 */
102 bool addFromFile(const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
103 {
104 int rc = RTCrStoreCertAddFromFile(this->m_hStore, RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR,
105 pszFilename, RTErrInfoInitStatic(pStaticErrInfo));
106 if (RT_SUCCESS(rc))
107 {
108 if (RTErrInfoIsSet(&pStaticErrInfo->Core))
109 RTMsgWarning("Warnings loading certificate '%s': %s", pszFilename, pStaticErrInfo->Core.pszMsg);
110 return true;
111 }
112 RTMsgError("Error loading certificate '%s': %Rrc%#RTeim", pszFilename, rc, &pStaticErrInfo->Core);
113 return false;
114 }
115
116 /**
117 * Adds trusted self-signed certificates from the system.
118 *
119 * @returns boolean success indicator.
120 * @note The selection is self-signed rather than CAs here so that test signing
121 * certificates will be included.
122 */
123 bool addSelfSignedRootsFromSystem(PRTERRINFOSTATIC pStaticErrInfo)
124 {
125 CryptoStore Tmp;
126 int rc = RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts(&Tmp.m_hStore, RTErrInfoInitStatic(pStaticErrInfo));
127 if (RT_SUCCESS(rc))
128 {
129 RTCRSTORECERTSEARCH Search;
130 rc = RTCrStoreCertFindAll(Tmp.m_hStore, &Search);
131 if (RT_SUCCESS(rc))
132 {
133 PCRTCRCERTCTX pCertCtx;
134 while ((pCertCtx = RTCrStoreCertSearchNext(Tmp.m_hStore, &Search)) != NULL)
135 {
136 /* Add it if it's a full fledged self-signed certificate, otherwise just skip: */
137 if ( pCertCtx->pCert
138 && RTCrX509Certificate_IsSelfSigned(pCertCtx->pCert))
139 {
140 int rc2 = RTCrStoreCertAddEncoded(this->m_hStore,
141 pCertCtx->fFlags | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
142 pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL);
143 if (RT_FAILURE(rc2))
144 RTMsgWarning("RTCrStoreCertAddEncoded failed for a certificate: %Rrc", rc2);
145 }
146 RTCrCertCtxRelease(pCertCtx);
147 }
148
149 int rc2 = RTCrStoreCertSearchDestroy(Tmp.m_hStore, &Search);
150 AssertRC(rc2);
151 return true;
152 }
153 RTMsgError("RTCrStoreCertFindAll failed: %Rrc", rc);
154 }
155 else
156 RTMsgError("RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts failed: %Rrc%#RTeim", rc, &pStaticErrInfo->Core);
157 return false;
158 }
159
160 /**
161 * Adds trusted self-signed certificates from the system.
162 *
163 * @returns boolean success indicator.
164 */
165 bool addIntermediateCertsFromSystem(PRTERRINFOSTATIC pStaticErrInfo)
166 {
167 bool fRc = true;
168 RTCRSTOREID const s_aenmStoreIds[] = { RTCRSTOREID_SYSTEM_INTERMEDIATE_CAS, RTCRSTOREID_USER_INTERMEDIATE_CAS };
169 for (size_t i = 0; i < RT_ELEMENTS(s_aenmStoreIds); i++)
170 {
171 CryptoStore Tmp;
172 int rc = RTCrStoreCreateSnapshotById(&Tmp.m_hStore, s_aenmStoreIds[i], RTErrInfoInitStatic(pStaticErrInfo));
173 if (RT_SUCCESS(rc))
174 {
175 RTCRSTORECERTSEARCH Search;
176 rc = RTCrStoreCertFindAll(Tmp.m_hStore, &Search);
177 if (RT_SUCCESS(rc))
178 {
179 PCRTCRCERTCTX pCertCtx;
180 while ((pCertCtx = RTCrStoreCertSearchNext(Tmp.m_hStore, &Search)) != NULL)
181 {
182 /* Skip selfsigned certs as they're useless as intermediate certs (IIRC). */
183 if ( pCertCtx->pCert
184 && !RTCrX509Certificate_IsSelfSigned(pCertCtx->pCert))
185 {
186 int rc2 = RTCrStoreCertAddEncoded(this->m_hStore,
187 pCertCtx->fFlags | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
188 pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL);
189 if (RT_FAILURE(rc2))
190 RTMsgWarning("RTCrStoreCertAddEncoded failed for a certificate: %Rrc", rc2);
191 }
192 RTCrCertCtxRelease(pCertCtx);
193 }
194
195 int rc2 = RTCrStoreCertSearchDestroy(Tmp.m_hStore, &Search);
196 AssertRC(rc2);
197 }
198 else
199 {
200 RTMsgError("RTCrStoreCertFindAll/%d failed: %Rrc", s_aenmStoreIds[i], rc);
201 fRc = false;
202 }
203 }
204 else
205 {
206 RTMsgError("RTCrStoreCreateSnapshotById/%d failed: %Rrc%#RTeim", s_aenmStoreIds[i], rc, &pStaticErrInfo->Core);
207 fRc = false;
208 }
209 }
210 return fRc;
211 }
212
213};
214
215typedef struct VERIFYEXESTATE
216{
217 CryptoStore RootStore;
218 CryptoStore KernelRootStore;
219 CryptoStore AdditionalStore;
220 bool fKernel;
221 int cVerbose;
222 enum { kSignType_Windows, kSignType_OSX } enmSignType;
223 RTLDRARCH enmLdrArch;
224 uint32_t cBad;
225 uint32_t cOkay;
226 uint32_t cTrustedCerts;
227 const char *pszFilename;
228 RTTIMESPEC ValidationTime;
229
230 VERIFYEXESTATE()
231 : fKernel(false)
232 , cVerbose(0)
233 , enmSignType(kSignType_Windows)
234 , enmLdrArch(RTLDRARCH_WHATEVER)
235 , cBad(0)
236 , cOkay(0)
237 , cTrustedCerts(0)
238 , pszFilename(NULL)
239 {
240 RTTimeSpecSetSeconds(&ValidationTime, 0);
241 }
242} VERIFYEXESTATE;
243
244/**
245 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
246 * Standard code signing. Use this for Microsoft SPC.}
247 */
248static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
249 void *pvUser, PRTERRINFO pErrInfo)
250{
251 VERIFYEXESTATE * const pState = (VERIFYEXESTATE *)pvUser;
252
253 /* We don't set RTCRPKCS7VERIFY_SD_F_TRUST_ALL_CERTS, so it won't be NIL! */
254 Assert(hCertPaths != NIL_RTCRX509CERTPATHS);
255
256# if 0 /* for debugging */
257 uint32_t const cPaths = RTCrX509CertPathsGetPathCount(hCertPaths);
258 RTMsgInfo("%s Path%s (pCert=%p hCertPaths=%p fFlags=%#x cPath=%d):",
259 fFlags & RTCRPKCS7VCC_F_TIMESTAMP ? "Timestamp" : "Signature", cPaths == 1 ? "" : "s",
260 pCert, hCertPaths, fFlags, cPaths);
261 for (uint32_t iPath = 0; iPath < cPaths; iPath++)
262 {
263 RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
264 *pErrInfo->pszMsg = '\0';
265 }
266# endif
267
268 /*
269 * Standard code signing capabilites required.
270 *
271 * Note! You may have to fix your test signing cert / releax this one to pass this.
272 */
273 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
274 if (RT_SUCCESS(rc))
275 {
276 /*
277 * Check if the signing certificate is a trusted one, i.e. one of the
278 * build certificates.
279 */
280 if (!(fFlags & RTCRPKCS7VCC_F_TIMESTAMP))
281 if (RTCrX509CertPathsGetPathCount(hCertPaths) == 1)
282 if (RTCrX509CertPathsGetPathLength(hCertPaths, 0) == 1)
283 {
284 RTMsgInfo("Signed by trusted certificate.\n");
285 pState->cTrustedCerts++;
286 }
287 }
288 else
289 RTMsgError("RTCrPkcs7VerifyCertCallbackCodeSigning(,,%#x,,) failed: %Rrc%#RTeim", fFlags, pErrInfo);
290 return rc;
291}
292
293/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
294static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, PCRTLDRSIGNATUREINFO pInfo, PRTERRINFO pErrInfo, void *pvUser)
295{
296 VERIFYEXESTATE * const pState = (VERIFYEXESTATE *)pvUser;
297 RT_NOREF_PV(hLdrMod);
298
299 switch (pInfo->enmType)
300 {
301 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
302 {
303 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pInfo->pvSignature;
304
305 if (pState->cVerbose > 0)
306 RTMsgInfo("Verifying '%s' signature #%u ...\n", pState->pszFilename, pInfo->iSignature + 1);
307
308# if 0
309 /*
310 * Dump the signed data if so requested and it's the first one, assuming that
311 * additional signatures in contained wihtin the same ContentInfo structure.
312 */
313 if (pState->cVerbose > 1 && pInfo->iSignature == 0)
314 RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
315# endif
316
317 /*
318 * We'll try different alternative timestamps here.
319 */
320 struct { RTTIMESPEC TimeSpec; const char *pszDesc; } aTimes[3];
321 unsigned cTimes = 0;
322
323 /* The specified timestamp. */
324 if (RTTimeSpecGetSeconds(&pState->ValidationTime) != 0)
325 {
326 aTimes[cTimes].TimeSpec = pState->ValidationTime;
327 aTimes[cTimes].pszDesc = "validation time";
328 cTimes++;
329 }
330
331 /* Linking timestamp: */
332 uint64_t uLinkingTime = 0;
333 int rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &uLinkingTime, sizeof(uLinkingTime));
334 if (RT_SUCCESS(rc))
335 {
336 RTTimeSpecSetSeconds(&aTimes[cTimes].TimeSpec, uLinkingTime);
337 aTimes[cTimes].pszDesc = "at link time";
338 cTimes++;
339 }
340 else if (rc != VERR_NOT_FOUND)
341 RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pState->pszFilename, rc);
342
343 /* Now: */
344 RTTimeNow(&aTimes[cTimes].TimeSpec);
345 aTimes[cTimes].pszDesc = "now";
346 cTimes++;
347
348 /*
349 * Do the actual verification.
350 */
351 Assert(!pInfo->pvExternalData);
352 for (unsigned iTime = 0; iTime < cTimes; iTime++)
353 {
354 RTTIMESPEC TimeSpec = aTimes[iTime].TimeSpec;
355 rc = RTCrPkcs7VerifySignedData(pContentInfo,
356 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
357 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
358 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT
359 | RTCRPKCS7VERIFY_SD_F_CHECK_TRUST_ANCHORS
360 | RTCRPKCS7VERIFY_SD_F_UPDATE_VALIDATION_TIME,
361 pState->AdditionalStore.m_hStore, pState->RootStore.m_hStore,
362 &TimeSpec, VerifyExecCertVerifyCallback, pState, pErrInfo);
363 if (RT_SUCCESS(rc))
364 {
365 Assert(rc == VINF_SUCCESS || rc == VINF_CR_DIGEST_DEPRECATED);
366 const char * const pszNote = rc == VINF_CR_DIGEST_DEPRECATED ? " (deprecated digest)" : "";
367 const char * const pszTime = iTime == 0
368 && RTTimeSpecCompare(&TimeSpec, &aTimes[iTime].TimeSpec) != 0
369 ? "at signing time" : aTimes[iTime].pszDesc;
370 if (pInfo->cSignatures == 1)
371 RTMsgInfo("'%s' is valid %s%s.\n", pState->pszFilename, pszTime, pszNote);
372 else
373 RTMsgInfo("'%s' signature #%u is valid %s%s.\n",
374 pState->pszFilename, pInfo->iSignature + 1, pszTime, pszNote);
375 pState->cOkay++;
376 return VINF_SUCCESS;
377 }
378 if (rc != VERR_CR_X509_CPV_NOT_VALID_AT_TIME)
379 {
380 if (pInfo->cSignatures == 1)
381 RTMsgError("%s: Failed to verify signature: %Rrc%#RTeim\n", pState->pszFilename, rc, pErrInfo);
382 else
383 RTMsgError("%s: Failed to verify signature #%u: %Rrc%#RTeim\n",
384 pState->pszFilename, pInfo->iSignature + 1, rc, pErrInfo);
385 pState->cBad++;
386 return VINF_SUCCESS;
387 }
388 }
389
390 if (pInfo->cSignatures == 1)
391 RTMsgError("%s: Signature is not valid at present or link time.\n", pState->pszFilename);
392 else
393 RTMsgError("%s: Signature #%u is not valid at present or link time.\n",
394 pState->pszFilename, pInfo->iSignature + 1);
395 pState->cBad++;
396 return VINF_SUCCESS;
397 }
398
399 default:
400 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", pInfo->enmType);
401 }
402}
403
404/**
405 * Uses IPRT functionality to check that the executable is signed with a
406 * certiicate known to us.
407 *
408 * @returns 0 on success, non-zero exit code on failure.
409 */
410static int CheckFileSignatureIprt(wchar_t const *pwszExePath)
411{
412 RTR3InitExeNoArguments(RTR3INIT_FLAGS_STANDALONE_APP);
413 RTMsgInfo("Signing checking of '%ls'...\n", pwszExePath);
414
415 /* Initialize the state. */
416 VERIFYEXESTATE State;
417 int rc = RTCrStoreCreateInMem(&State.RootStore.m_hStore, 0);
418 if (RT_SUCCESS(rc))
419 rc = RTCrStoreCreateInMem(&State.KernelRootStore.m_hStore, 0);
420 if (RT_SUCCESS(rc))
421 rc = RTCrStoreCreateInMem(&State.AdditionalStore.m_hStore, 0);
422 if (RT_FAILURE(rc))
423 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
424
425 /* Add the build certificates to the root store. */
426 RTERRINFOSTATIC StaticErrInfo;
427 for (uint32_t i = 0; i < g_cBuildCerts; i++)
428 {
429 rc = RTCrStoreCertAddEncoded(State.RootStore.m_hStore, RTCRCERTCTX_F_ENC_X509_DER,
430 g_aBuildCerts[i].pbCert, g_aBuildCerts[i].cbCert, RTErrInfoInitStatic(&StaticErrInfo));
431 if (RT_FAILURE(rc))
432 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to add build cert #%u to root store: %Rrc%#RTeim",
433 i, rc, &StaticErrInfo.Core);
434 }
435 uint32_t i = g_cTimestampRootCerts; /* avoids warning if g_cTimestampRootCerts is 0. */
436 while (i-- > 0)
437 {
438 rc = RTCrStoreCertAddEncoded(State.RootStore.m_hStore, RTCRCERTCTX_F_ENC_X509_DER,
439 g_aTimestampRootCerts[i].pbCert, g_aTimestampRootCerts[i].cbCert,
440 RTErrInfoInitStatic(&StaticErrInfo));
441 if (RT_FAILURE(rc))
442 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to add build timestamp root cert #%u to root store: %Rrc%#RTeim",
443 i, rc, &StaticErrInfo.Core);
444 }
445
446 /*
447 * Open the executable image and verify it.
448 */
449 char *pszExePath = NULL;
450 rc = RTUtf16ToUtf8(pwszExePath, &pszExePath);
451 AssertRCReturn(rc, RTEXITCODE_FAILURE);
452 RTLDRMOD hLdrMod;
453 rc = RTLdrOpen(pszExePath, RTLDR_O_FOR_VALIDATION, RTLDRARCH_WHATEVER, &hLdrMod);
454 if (RT_SUCCESS(rc))
455 {
456 State.pszFilename = pszExePath;
457
458 rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, &State, RTErrInfoInitStatic(&StaticErrInfo));
459 if (RT_FAILURE(rc))
460 RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc%#RTeim\n", pszExePath, rc, &StaticErrInfo.Core);
461
462 RTStrFree(pszExePath);
463 RTLdrClose(hLdrMod);
464
465 if (RT_FAILURE(rc))
466 return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
467 if (State.cOkay > 0)
468 {
469 if (State.cTrustedCerts > 0)
470 return RTEXITCODE_SUCCESS;
471 RTMsgError("None of the build certificates were used for signing '%ls'!", pwszExePath);
472 }
473 return RTEXITCODE_FAILURE;
474 }
475 RTStrFree(pszExePath);
476 return RTEXITCODE_FAILURE;
477}
478
479# else /* Using Windows APIs */
480
481/**
482 * Checks the file signatures of both this stub program and the actual installer
483 * binary, making sure they use the same certificate as at build time and that
484 * the signature verifies correctly.
485 *
486 * @returns 0 on success, non-zero exit code on failure.
487 */
488static int CheckFileSignatures(wchar_t const *pwszExePath, HANDLE hFileExe, wchar_t const *pwszSelfPath, HANDLE hFileSelf)
489{
490 /*
491 * Check the OS version (bypassing shims).
492 *
493 * The RtlGetVersion API was added in windows 2000, so it's precense is a
494 * provides a minimum OS version indicator already.
495 */
496 LONG (__stdcall *pfnRtlGetVersion)(OSVERSIONINFOEXW *);
497 *(FARPROC *)&pfnRtlGetVersion = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion");
498 if (!pfnRtlGetVersion)
499 {
500 /* double check it. */
501 DWORD const dwVersion = GetVersion();
502 if ((dwVersion & 0xff) < 5)
503 return 0;
504 return ErrorMsgRcSUS(40, "RtlGetVersion not present while Windows version is 5.0 or higher (", dwVersion, ")");
505 }
506 OSVERSIONINFOEXW WinOsInfoEx = { sizeof(WinOsInfoEx) };
507 NTSTATUS const rcNt = pfnRtlGetVersion(&WinOsInfoEx);
508 if (!RT_SUCCESS(rcNt))
509 return ErrorMsgRcSU(41, "RtlGetVersion failed: ", rcNt);
510
511 /* Skip both of these checks if pre-XP. */
512 if ( (WinOsInfoEx.dwMajorVersion == 5 && WinOsInfoEx.dwMinorVersion < 1)
513 || WinOsInfoEx.dwMajorVersion < 4)
514 return 0;
515
516 /*
517 * We need to find the system32 directory to load the WinVerifyTrust API.
518 */
519 static wchar_t const s_wszSlashWinTrustDll[] = L"\\Wintrust.dll";
520
521 /* Call GetSystemWindowsDirectoryW/GetSystemDirectoryW. */
522 wchar_t wszSysDll[MAX_PATH + sizeof(s_wszSlashWinTrustDll)] = { 0 };
523 UINT const cwcSystem32 = GetSystemDirectoryW(wszSysDll, MAX_PATH);
524 if (!cwcSystem32 || cwcSystem32 >= MAX_PATH)
525 return ErrorMsgRc(42, "GetSystemDirectoryW failed");
526
527 /* Load it: */
528 memcpy(&wszSysDll[cwcSystem32], s_wszSlashWinTrustDll, sizeof(s_wszSlashWinTrustDll));
529 DWORD fLoadFlags = LOAD_LIBRARY_SEARCH_SYSTEM32;
530 HMODULE hModWinTrustDll = LoadLibraryExW(wszSysDll, NULL, fLoadFlags);
531 if (!hModWinTrustDll && GetLastError() == ERROR_INVALID_PARAMETER)
532 {
533 fLoadFlags = 0;
534 hModWinTrustDll = LoadLibraryExW(wszSysDll, NULL, fLoadFlags);
535 }
536 if (!hModWinTrustDll)
537 return ErrorMsgRcSWSU(43, "Failed to load '", wszSysDll, "': ", GetLastError());
538
539 /* Resolve API: */
540 decltype(WinVerifyTrust) * const pfnWinVerifyTrust
541 = (decltype(WinVerifyTrust) *)GetProcAddress(hModWinTrustDll, "WinVerifyTrust");
542 if (!pfnWinVerifyTrust)
543 return ErrorMsgRc(44, "WinVerifyTrust not found");
544
545 /*
546 * We also need the Crypt32.dll for CryptQueryObject and CryptMsgGetParam.
547 */
548 /* Load it: */
549 static wchar_t const s_wszSlashCrypt32Dll[] = L"\\Crypt32.dll";
550 AssertCompile(sizeof(s_wszSlashCrypt32Dll) <= sizeof(s_wszSlashWinTrustDll));
551 memcpy(&wszSysDll[cwcSystem32], s_wszSlashCrypt32Dll, sizeof(s_wszSlashCrypt32Dll));
552 HMODULE const hModCrypt32Dll = LoadLibraryExW(wszSysDll, NULL, fLoadFlags);
553 if (!hModCrypt32Dll)
554 return ErrorMsgRcSWSU(45, "Failed to load '", wszSysDll, "': ", GetLastError());
555
556 /* Resolve APIs: */
557 decltype(CryptQueryObject) * const pfnCryptQueryObject
558 = (decltype(CryptQueryObject) *)GetProcAddress(hModCrypt32Dll, "CryptQueryObject");
559 if (!pfnCryptQueryObject)
560 return ErrorMsgRc(46, "CryptQueryObject not found");
561
562 decltype(CryptMsgClose) * const pfnCryptMsgClose
563 = (decltype(CryptMsgClose) *)GetProcAddress(hModCrypt32Dll, "CryptMsgClose");
564 if (!pfnCryptQueryObject)
565 return ErrorMsgRc(47, "CryptMsgClose not found");
566
567 decltype(CryptMsgGetParam) * const pfnCryptMsgGetParam
568 = (decltype(CryptMsgGetParam) *)GetProcAddress(hModCrypt32Dll, "CryptMsgGetParam");
569 if (!pfnCryptQueryObject)
570 return ErrorMsgRc(48, "CryptMsgGetParam not found");
571
572 /*
573 * We'll verify the primary signer certificate first as that's something that
574 * should work even if SHA-256 isn't supported by the Windows crypto code.
575 */
576 struct
577 {
578 HANDLE hFile;
579 wchar_t const *pwszFile;
580
581 DWORD fEncoding;
582 DWORD dwContentType;
583 DWORD dwFormatType;
584 HCERTSTORE hCertStore;
585 HCRYPTMSG hMsg;
586
587 DWORD cbCert;
588 uint8_t *pbCert;
589 } aExes[] =
590 {
591 { hFileSelf, pwszSelfPath, 0, 0, 0, NULL, NULL, 0, NULL },
592 { hFileExe, pwszExePath, 0, 0, 0, NULL, NULL, 0, NULL },
593 };
594
595 HANDLE const hHeap = GetProcessHeap();
596 int rcExit = 0;
597 for (unsigned i = 0; i < RT_ELEMENTS(aExes) && rcExit == 0; i++)
598 {
599 if (!pfnCryptQueryObject(CERT_QUERY_OBJECT_FILE,
600 aExes[i].pwszFile,
601 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
602 CERT_QUERY_FORMAT_FLAG_BINARY,
603 0 /*fFlags*/,
604 &aExes[i].fEncoding,
605 &aExes[i].dwContentType,
606 &aExes[i].dwFormatType,
607 &aExes[i].hCertStore,
608 &aExes[i].hMsg,
609 NULL /*ppvContext*/))
610 rcExit = ErrorMsgRcSWSU(50 + i*4, "CryptQueryObject/FILE on '", aExes[i].pwszFile, "': ", GetLastError());
611/** @todo this isn't getting us what we want. It's just accessing the
612 * certificates shipped with the signature. Sigh. */
613 else if (!pfnCryptMsgGetParam(aExes[i].hMsg, CMSG_CERT_PARAM, 0, NULL, &aExes[i].cbCert))
614 rcExit = ErrorMsgRcSWSU(51 + i*4, "CryptMsgGetParam/CMSG_CERT_PARAM/size failed on '",
615 aExes[i].pwszFile, "': ", GetLastError());
616 else
617 {
618 DWORD const cbCert = aExes[i].cbCert;
619 aExes[i].pbCert = (uint8_t *)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, cbCert);
620 if (!aExes[i].pbCert)
621 rcExit = ErrorMsgRcSUS(52 + i*4, "Out of memory (", cbCert, " bytes) for signing certificate information");
622 else if (!pfnCryptMsgGetParam(aExes[i].hMsg, CMSG_CERT_PARAM, 0, aExes[i].pbCert, &aExes[i].cbCert))
623 rcExit = ErrorMsgRcSWSU(53 + i*4, "CryptMsgGetParam/CMSG_CERT_PARAM failed on '", aExes[i].pwszFile, "': ",
624 GetLastError());
625 }
626 }
627
628 if (rcExit == 0)
629 {
630 /* Do the two match? */
631 if ( aExes[0].cbCert != aExes[1].cbCert
632 || memcmp(aExes[0].pbCert, aExes[1].pbCert, aExes[0].cbCert) != 0)
633 rcExit = ErrorMsgRcSWS(58, "The certificate used to sign '", pwszExePath, "' does not match.");
634 /* The two match, now do they match the one we're expecting to use? */
635 else if ( aExes[0].cbCert != g_cbBuildCert
636 || memcmp(aExes[0].pbCert, g_abBuildCert, g_cbBuildCert) != 0)
637 rcExit = ErrorMsgRcSWS(59, "The signing certificate of '", pwszExePath, "' differs from the build certificate");
638 /* else: it all looks fine */
639 }
640
641 /* cleanup */
642 for (unsigned i = 0; i < RT_ELEMENTS(aExes); i++)
643 {
644 if (aExes[i].pbCert)
645 {
646 HeapFree(hHeap, 0, aExes[i].pbCert);
647 aExes[i].pbCert = NULL;
648 }
649 if (aExes[i].hMsg)
650 {
651 pfnCryptMsgClose(aExes[i].hMsg);
652 aExes[i].hMsg = NULL;
653 }
654 }
655 if (rcExit != 0)
656 return rcExit;
657
658 /*
659 * ASSUMING we're using SHA-256 for signing, we do a windows OS cutoff at Windows 7.
660 * For Windows Vista and older we skip this step.
661 */
662 if ( (WinOsInfoEx.dwMajorVersion == 6 && WinOsInfoEx.dwMinorVersion == 0)
663 || WinOsInfoEx.dwMajorVersion < 6)
664 return 0;
665
666 /*
667 * Construct input WinVerifyTrust parameters and call it on each of the executables in turn.
668 * This code was borrowed from SUPHardNt.
669 */
670 for (unsigned i = 0; i < RT_ELEMENTS(aExes); i++)
671 {
672 WINTRUST_FILE_INFO FileInfo = { 0 };
673 FileInfo.cbStruct = sizeof(FileInfo);
674 FileInfo.pcwszFilePath = aExes[i].pwszFile;
675 FileInfo.hFile = aExes[i].hFile;
676
677 GUID PolicyActionGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
678
679 WINTRUST_DATA TrustData = { 0 };
680 TrustData.cbStruct = sizeof(TrustData);
681 TrustData.fdwRevocationChecks = WTD_REVOKE_NONE; /* Keep simple for now. */
682 TrustData.dwStateAction = WTD_STATEACTION_VERIFY;
683 TrustData.dwUIChoice = WTD_UI_NONE;
684 TrustData.dwProvFlags = 0;
685 if (WinOsInfoEx.dwMajorVersion >= 6)
686 TrustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
687 else
688 TrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
689 TrustData.dwUnionChoice = WTD_CHOICE_FILE;
690 TrustData.pFile = &FileInfo;
691
692 HRESULT hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
693 if (hrc != S_OK)
694 {
695 /* Translate the eror constant */
696 const char *pszErrConst = NULL;
697 switch (hrc)
698 {
699 case TRUST_E_SYSTEM_ERROR: pszErrConst = "TRUST_E_SYSTEM_ERROR"; break;
700 case TRUST_E_NO_SIGNER_CERT: pszErrConst = "TRUST_E_NO_SIGNER_CERT"; break;
701 case TRUST_E_COUNTER_SIGNER: pszErrConst = "TRUST_E_COUNTER_SIGNER"; break;
702 case TRUST_E_CERT_SIGNATURE: pszErrConst = "TRUST_E_CERT_SIGNATURE"; break;
703 case TRUST_E_TIME_STAMP: pszErrConst = "TRUST_E_TIME_STAMP"; break;
704 case TRUST_E_BAD_DIGEST: pszErrConst = "TRUST_E_BAD_DIGEST"; break;
705 case TRUST_E_BASIC_CONSTRAINTS: pszErrConst = "TRUST_E_BASIC_CONSTRAINTS"; break;
706 case TRUST_E_FINANCIAL_CRITERIA: pszErrConst = "TRUST_E_FINANCIAL_CRITERIA"; break;
707 case TRUST_E_PROVIDER_UNKNOWN: pszErrConst = "TRUST_E_PROVIDER_UNKNOWN"; break;
708 case TRUST_E_ACTION_UNKNOWN: pszErrConst = "TRUST_E_ACTION_UNKNOWN"; break;
709 case TRUST_E_SUBJECT_FORM_UNKNOWN: pszErrConst = "TRUST_E_SUBJECT_FORM_UNKNOWN"; break;
710 case TRUST_E_SUBJECT_NOT_TRUSTED: pszErrConst = "TRUST_E_SUBJECT_NOT_TRUSTED"; break;
711 case TRUST_E_NOSIGNATURE: pszErrConst = "TRUST_E_NOSIGNATURE"; break;
712 case TRUST_E_FAIL: pszErrConst = "TRUST_E_FAIL"; break;
713 case TRUST_E_EXPLICIT_DISTRUST: pszErrConst = "TRUST_E_EXPLICIT_DISTRUST"; break;
714 case CERT_E_EXPIRED: pszErrConst = "CERT_E_EXPIRED"; break;
715 case CERT_E_VALIDITYPERIODNESTING: pszErrConst = "CERT_E_VALIDITYPERIODNESTING"; break;
716 case CERT_E_ROLE: pszErrConst = "CERT_E_ROLE"; break;
717 case CERT_E_PATHLENCONST: pszErrConst = "CERT_E_PATHLENCONST"; break;
718 case CERT_E_CRITICAL: pszErrConst = "CERT_E_CRITICAL"; break;
719 case CERT_E_PURPOSE: pszErrConst = "CERT_E_PURPOSE"; break;
720 case CERT_E_ISSUERCHAINING: pszErrConst = "CERT_E_ISSUERCHAINING"; break;
721 case CERT_E_MALFORMED: pszErrConst = "CERT_E_MALFORMED"; break;
722 case CERT_E_UNTRUSTEDROOT: pszErrConst = "CERT_E_UNTRUSTEDROOT"; break;
723 case CERT_E_CHAINING: pszErrConst = "CERT_E_CHAINING"; break;
724 case CERT_E_REVOKED: pszErrConst = "CERT_E_REVOKED"; break;
725 case CERT_E_UNTRUSTEDTESTROOT: pszErrConst = "CERT_E_UNTRUSTEDTESTROOT"; break;
726 case CERT_E_REVOCATION_FAILURE: pszErrConst = "CERT_E_REVOCATION_FAILURE"; break;
727 case CERT_E_CN_NO_MATCH: pszErrConst = "CERT_E_CN_NO_MATCH"; break;
728 case CERT_E_WRONG_USAGE: pszErrConst = "CERT_E_WRONG_USAGE"; break;
729 case CERT_E_UNTRUSTEDCA: pszErrConst = "CERT_E_UNTRUSTEDCA"; break;
730 case CERT_E_INVALID_POLICY: pszErrConst = "CERT_E_INVALID_POLICY"; break;
731 case CERT_E_INVALID_NAME: pszErrConst = "CERT_E_INVALID_NAME"; break;
732 case CRYPT_E_FILE_ERROR: pszErrConst = "CRYPT_E_FILE_ERROR"; break;
733 case CRYPT_E_REVOKED: pszErrConst = "CRYPT_E_REVOKED"; break;
734 }
735 if (pszErrConst)
736 rcExit = ErrorMsgRcSWSS(60 + i, "WinVerifyTrust failed on '", pwszExePath, "': ", pszErrConst);
737 else
738 rcExit = ErrorMsgRcSWSX(60 + i, "WinVerifyTrust failed on '", pwszExePath, "': ", hrc);
739 }
740
741 /* clean up state data. */
742 TrustData.dwStateAction = WTD_STATEACTION_CLOSE;
743 FileInfo.hFile = NULL;
744 hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
745 }
746
747 return rcExit;
748}
749
750# endif /* Using Windows APIs. */
751#endif /* VBOX_SIGNING_MODE */
752
753/**
754 * strstr for haystacks w/o null termination.
755 */
756static const char *MyStrStrN(const char *pchHaystack, size_t cbHaystack, const char *pszNeedle)
757{
758 size_t const cchNeedle = strlen(pszNeedle);
759 char const chFirst = *pszNeedle;
760 if (cbHaystack >= cchNeedle)
761 {
762 cbHaystack -= cchNeedle - 1;
763 while (cbHaystack > 0)
764 {
765 const char *pchHit = (const char *)memchr(pchHaystack, chFirst, cbHaystack);
766 if (pchHit)
767 {
768 if (memcmp(pchHit, pszNeedle, cchNeedle) == 0)
769 return pchHit;
770 pchHit++;
771 cbHaystack -= pchHit - pchHaystack;
772 pchHaystack = pchHit;
773 }
774 else
775 break;
776 }
777 }
778 return NULL;
779}
780
781/**
782 * Check that the executable file is "related" the one for the current process.
783 */
784static int CheckThatFileIsRelated(wchar_t const *pwszExePath, wchar_t const *pwszSelfPath)
785{
786 /*
787 * Start by checking version info.
788 */
789 /*
790 * Query the version info for the files:
791 */
792 DWORD const cbExeVerInfo = GetFileVersionInfoSizeW(pwszExePath, NULL);
793 if (!cbExeVerInfo)
794 return ErrorMsgRcSWSU(20, "GetFileVersionInfoSizeW failed on '", pwszExePath, "': ", GetLastError());
795
796 DWORD const cbSelfVerInfo = GetFileVersionInfoSizeW(pwszSelfPath, NULL);
797 if (!cbSelfVerInfo)
798 return ErrorMsgRcSWSU(21, "GetFileVersionInfoSizeW failed on '", pwszSelfPath, "': ", GetLastError());
799
800 HANDLE const hHeap = GetProcessHeap();
801 DWORD const cbBothVerInfo = RT_ALIGN_32(cbExeVerInfo, 64) + RT_ALIGN_32(cbSelfVerInfo, 64);
802 void * const pvExeVerInfo = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, cbBothVerInfo);
803 void * const pvSelfVerInfo = (uint8_t *)pvExeVerInfo + RT_ALIGN_32(cbExeVerInfo, 64);
804 if (!pvExeVerInfo)
805 return ErrorMsgRcSUS(22, "Out of memory (", cbBothVerInfo, " bytes) for version info");
806
807 int rcExit = 0;
808 if (!GetFileVersionInfoW(pwszExePath, 0, cbExeVerInfo, pvExeVerInfo))
809 rcExit = ErrorMsgRcSWSU(23, "GetFileVersionInfoW failed on '", pwszExePath, "': ", GetLastError());
810 else if (!GetFileVersionInfoW(pwszSelfPath, 0, cbSelfVerInfo, pvSelfVerInfo))
811 rcExit = ErrorMsgRcSWSU(24, "GetFileVersionInfoW failed on '", pwszSelfPath, "': ", GetLastError());
812
813 /*
814 * Compare the product and company strings, which should be identical.
815 */
816 static struct
817 {
818 wchar_t const *pwszQueryItem;
819 const char *pszQueryErrorMsg1;
820 const char *pszCompareErrorMsg1;
821 } const s_aIdenticalItems[] =
822 {
823 { L"\\StringFileInfo\\040904b0\\ProductName", "VerQueryValueW/ProductName failed on '", "Product string of '" },
824 { L"\\StringFileInfo\\040904b0\\CompanyName", "VerQueryValueW/CompanyName failed on '", "Company string of '" },
825 };
826
827 for (unsigned i = 0; i < RT_ELEMENTS(s_aIdenticalItems) && rcExit == 0; i++)
828 {
829 void *pvExeInfoItem = NULL;
830 UINT cbExeInfoItem = 0;
831 void *pvSelfInfoItem = NULL;
832 UINT cbSelfInfoItem = 0;
833 if (!VerQueryValueW(pvExeVerInfo, s_aIdenticalItems[i].pwszQueryItem, &pvExeInfoItem, &cbExeInfoItem))
834 rcExit = ErrorMsgRcSWSU(25 + i*3, s_aIdenticalItems[i].pszQueryErrorMsg1 , pwszExePath, "': ", GetLastError());
835 else if (!VerQueryValueW(pvSelfVerInfo, s_aIdenticalItems[i].pwszQueryItem, &pvSelfInfoItem, &cbSelfInfoItem))
836 rcExit = ErrorMsgRcSWSU(26 + i*3, s_aIdenticalItems[i].pszQueryErrorMsg1, pwszSelfPath, "': ", GetLastError());
837 else if ( cbExeInfoItem != cbSelfInfoItem
838 || memcmp(pvExeInfoItem, pvSelfInfoItem, cbSelfInfoItem) != 0)
839 rcExit = ErrorMsgRcSWS(27 + i*3, s_aIdenticalItems[i].pszCompareErrorMsg1, pwszExePath, "' does not match");
840 }
841
842 HeapFree(hHeap, 0, pvExeVerInfo);
843
844 /*
845 * Check that the file has a manifest that looks like it may belong to
846 * an NSIS installer.
847 */
848 if (rcExit == 0)
849 {
850 HMODULE hMod = LoadLibraryExW(pwszExePath, NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
851 if (!hMod && GetLastError() == ERROR_INVALID_PARAMETER)
852 hMod = LoadLibraryExW(pwszExePath, NULL, LOAD_LIBRARY_AS_DATAFILE);
853 if (hMod)
854 {
855 HRSRC const hRsrcMt = FindResourceExW(hMod, RT_MANIFEST, MAKEINTRESOURCEW(1),
856 MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
857 if (hRsrcMt)
858 {
859 DWORD const cbManifest = SizeofResource(hMod, hRsrcMt);
860 HGLOBAL const hGlobalMt = LoadResource(hMod, hRsrcMt);
861 if (hGlobalMt)
862 {
863 const char * const pchManifest = (const char *)LockResource(hGlobalMt);
864 if (pchManifest)
865 {
866 /* Just look for a few strings we expect to always find the manifest. */
867 if (!MyStrStrN(pchManifest, cbManifest, "Nullsoft.NSIS.exehead"))
868 rcExit = 36;
869 else if (!MyStrStrN(pchManifest, cbManifest, "requestedPrivileges"))
870 rcExit = 37;
871 else if (!MyStrStrN(pchManifest, cbManifest, "highestAvailable"))
872 rcExit = 38;
873 if (rcExit)
874 rcExit = ErrorMsgRcSWSU(rcExit, "Manifest check of '", pwszExePath, "' failed: ", rcExit);
875 }
876 else
877 rcExit = ErrorMsgRc(35, "LockResource/Manifest failed");
878 }
879 else
880 rcExit = ErrorMsgRcSU(34, "LoadResource/Manifest failed: ", GetLastError());
881 }
882 else
883 rcExit = ErrorMsgRcSU(33, "FindResourceExW/Manifest failed: ", GetLastError());
884 }
885 else
886 rcExit = ErrorMsgRcSWSU(32, "LoadLibraryExW of '", pwszExePath, "' as datafile failed: ", GetLastError());
887 }
888
889 return rcExit;
890}
891
892static BOOL IsWow64(void)
893{
894 BOOL fIsWow64 = FALSE;
895 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
896 LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandleW(L"kernel32"), "IsWow64Process");
897 if (fnIsWow64Process != NULL)
898 {
899 if (!fnIsWow64Process(GetCurrentProcess(), &fIsWow64))
900 {
901 ErrorMsgLastErr("Unable to determine the process type!");
902
903 /* Error in retrieving process type - assume that we're running on 32bit. */
904 fIsWow64 = FALSE;
905 }
906 }
907 return fIsWow64;
908}
909
910/**
911 * Detects the native host platform and returns the appropriate installer
912 * executable suffix for it.
913 *
914 * @returns Architecture stuff string.
915 */
916static const wchar_t *GetNativeArchInstallerSuffix(void)
917{
918 HMODULE const hModKernel32 = GetModuleHandleW(L"kernel32.dll");
919 PFNISWOW64PROCESS2 pfnIsWow64Process2 = (PFNISWOW64PROCESS2)GetProcAddress(hModKernel32, "IsWow64Process2");
920 if (pfnIsWow64Process2)
921 {
922 USHORT usWowMachine = IMAGE_FILE_MACHINE_UNKNOWN;
923 USHORT usHostMachine = IMAGE_FILE_MACHINE_UNKNOWN;
924 if (pfnIsWow64Process2(GetCurrentProcess(), &usWowMachine, &usHostMachine))
925 {
926 if (usHostMachine == IMAGE_FILE_MACHINE_AMD64)
927 return L"-amd64.exe";
928 if (usHostMachine == IMAGE_FILE_MACHINE_ARM64)
929 return L"-arm64.exe";
930 if (usHostMachine == IMAGE_FILE_MACHINE_I386)
931 return L"-x86.exe";
932 ErrorMsgSU("IsWow64Process2 return unknown host machine value: ", usHostMachine);
933 }
934 else
935 ErrorMsgLastErr("Unable to determine the process type! (#2)");
936 }
937 else
938 {
939 PFNISWOW64PROCESS pfnIsWow64Process = (PFNISWOW64PROCESS)GetProcAddress(hModKernel32, "IsWow64Process");
940 if (pfnIsWow64Process)
941 {
942 BOOL fIsWow64 = TRUE;
943 if (pfnIsWow64Process(GetCurrentProcess(), &fIsWow64))
944 {
945 if (fIsWow64)
946 return L"-amd64.exe";
947 }
948 else
949 ErrorMsgLastErr("Unable to determine the process type!");
950 }
951 }
952
953#ifdef RT_ARCH_X86
954 return L"-x86.exe";
955#elif defined(RT_ARCH_AMD64)
956 return L"-amd64.exe";
957#elif defined(RT_ARCH_ARM64)
958 return L"-arm64.exe";
959#else
960# error "port me"
961#endif
962}
963
964static int WaitForProcess2(HANDLE hProcess)
965{
966 /*
967 * Wait for the process, make sure the deal with messages.
968 */
969 for (;;)
970 {
971 DWORD dwRc = MsgWaitForMultipleObjects(1, &hProcess, FALSE, 5000/*ms*/, QS_ALLEVENTS);
972
973 MSG Msg;
974 while (PeekMessageW(&Msg, NULL, 0, 0, PM_REMOVE))
975 {
976 TranslateMessage(&Msg);
977 DispatchMessageW(&Msg);
978 }
979
980 if (dwRc == WAIT_OBJECT_0)
981 break;
982 if ( dwRc != WAIT_TIMEOUT
983 && dwRc != WAIT_OBJECT_0 + 1)
984 {
985 ErrorMsgLastErrSUR("MsgWaitForMultipleObjects failed: ", dwRc);
986 break;
987 }
988 }
989
990 /*
991 * Collect the process info.
992 */
993 DWORD dwExitCode;
994 if (GetExitCodeProcess(hProcess, &dwExitCode))
995 return (int)dwExitCode;
996 return ErrorMsgRcLastErr(16, "GetExitCodeProcess failed");
997}
998
999static int WaitForProcess(HANDLE hProcess)
1000{
1001 DWORD WaitRc = WaitForSingleObjectEx(hProcess, INFINITE, TRUE);
1002 while ( WaitRc == WAIT_IO_COMPLETION
1003 || WaitRc == WAIT_TIMEOUT)
1004 WaitRc = WaitForSingleObjectEx(hProcess, INFINITE, TRUE);
1005 if (WaitRc == WAIT_OBJECT_0)
1006 {
1007 DWORD dwExitCode;
1008 if (GetExitCodeProcess(hProcess, &dwExitCode))
1009 return (int)dwExitCode;
1010 return ErrorMsgRcLastErr(16, "GetExitCodeProcess failed");
1011 }
1012 return ErrorMsgRcLastErrSUR(16, "MsgWaitForMultipleObjects failed: ", WaitRc);
1013}
1014
1015#ifndef IPRT_NO_CRT
1016int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1017#else
1018int main()
1019#endif
1020{
1021#ifndef IPRT_NO_CRT
1022 RT_NOREF(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
1023#endif
1024
1025 /*
1026 * Gather the parameters of the real installer program.
1027 */
1028 SetLastError(NO_ERROR);
1029 WCHAR wszCurDir[MAX_PATH] = { 0 };
1030 DWORD cwcCurDir = GetCurrentDirectoryW(sizeof(wszCurDir), wszCurDir);
1031 if (cwcCurDir == 0 || cwcCurDir >= sizeof(wszCurDir))
1032 return ErrorMsgRcLastErrSUR(12, "GetCurrentDirectoryW failed: ", cwcCurDir);
1033
1034 SetLastError(NO_ERROR);
1035 WCHAR wszExePath[MAX_PATH] = { 0 };
1036 size_t cwcExePath = GetModuleFileNameW(NULL, wszExePath, sizeof(wszExePath));
1037 if (cwcExePath == 0 || cwcExePath >= sizeof(wszExePath))
1038 return ErrorMsgRcLastErrSUR(13, "GetModuleFileNameW failed: ", cwcExePath);
1039
1040 WCHAR wszSelfPath[MAX_PATH];
1041 memcpy(wszSelfPath, wszExePath, sizeof(wszSelfPath));
1042
1043 /*
1044 * Strip the extension off the module name and construct the arch specific
1045 * one of the real installer program.
1046 */
1047 size_t off = cwcExePath - 1;
1048 while ( off > 0
1049 && ( wszExePath[off] != '/'
1050 && wszExePath[off] != '\\'
1051 && wszExePath[off] != ':'))
1052 {
1053 if (wszExePath[off] == '.')
1054 {
1055 wszExePath[off] = '\0';
1056 cwcExePath = off;
1057 break;
1058 }
1059 off--;
1060 }
1061
1062 WCHAR const * const pwszSuff = GetNativeArchInstallerSuffix();
1063 int rc = RTUtf16Copy(&wszExePath[cwcExePath], RT_ELEMENTS(wszExePath) - cwcExePath, pwszSuff);
1064 if (RT_FAILURE(rc))
1065 return ErrorMsgRc(14, "Real installer name is too long!");
1066 cwcExePath += RTUtf16Len(&wszExePath[cwcExePath]);
1067
1068 /*
1069 * Replace the first argument of the argument list.
1070 */
1071 PWCHAR pwszNewCmdLine = NULL;
1072 LPCWSTR pwszOrgCmdLine = GetCommandLineW();
1073 if (pwszOrgCmdLine) /* Dunno if this can be NULL, but whatever. */
1074 {
1075 /* Skip the first argument in the original. */
1076 /** @todo Is there some ISBLANK or ISSPACE macro/function in Win32 that we could
1077 * use here, if it's correct wrt. command line conventions? */
1078 WCHAR wch;
1079 while ((wch = *pwszOrgCmdLine) == L' ' || wch == L'\t')
1080 pwszOrgCmdLine++;
1081 if (wch == L'"')
1082 {
1083 pwszOrgCmdLine++;
1084 while ((wch = *pwszOrgCmdLine) != L'\0')
1085 {
1086 pwszOrgCmdLine++;
1087 if (wch == L'"')
1088 break;
1089 }
1090 }
1091 else
1092 {
1093 while ((wch = *pwszOrgCmdLine) != L'\0')
1094 {
1095 pwszOrgCmdLine++;
1096 if (wch == L' ' || wch == L'\t')
1097 break;
1098 }
1099 }
1100 while ((wch = *pwszOrgCmdLine) == L' ' || wch == L'\t')
1101 pwszOrgCmdLine++;
1102
1103 /* Join up "wszExePath" with the remainder of the original command line. */
1104 size_t cwcOrgCmdLine = RTUtf16Len(pwszOrgCmdLine);
1105 size_t cwcNewCmdLine = 1 + cwcExePath + 1 + 1 + cwcOrgCmdLine + 1;
1106 PWCHAR pwsz = pwszNewCmdLine = (PWCHAR)LocalAlloc(LPTR, cwcNewCmdLine * sizeof(WCHAR));
1107 if (!pwsz)
1108 return ErrorMsgRcSUS(15, "Out of memory (", cwcNewCmdLine * sizeof(WCHAR), " bytes)");
1109 *pwsz++ = L'"';
1110 memcpy(pwsz, wszExePath, cwcExePath * sizeof(pwsz[0]));
1111 pwsz += cwcExePath;
1112 *pwsz++ = L'"';
1113 if (cwcOrgCmdLine)
1114 {
1115 *pwsz++ = L' ';
1116 memcpy(pwsz, pwszOrgCmdLine, cwcOrgCmdLine * sizeof(pwsz[0]));
1117 }
1118 else
1119 {
1120 *pwsz = L'\0';
1121 pwszOrgCmdLine = NULL;
1122 }
1123 }
1124
1125 /*
1126 * Open the executable for this process.
1127 */
1128 HANDLE hFileSelf = CreateFileW(wszSelfPath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecAttr*/, OPEN_EXISTING,
1129 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1130 if (hFileSelf == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER)
1131 hFileSelf = CreateFileW(wszSelfPath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecAttr*/, OPEN_EXISTING,
1132 FILE_ATTRIBUTE_NORMAL, NULL);
1133 if (hFileSelf == INVALID_HANDLE_VALUE)
1134 {
1135 if (GetLastError() == ERROR_FILE_NOT_FOUND)
1136 return ErrorMsgRcSW(17, "File not found: ", wszSelfPath);
1137 return ErrorMsgRcSWSU(17, "Error opening '", wszSelfPath, "' for reading: ", GetLastError());
1138 }
1139
1140
1141 /*
1142 * Open the file we're about to execute.
1143 */
1144 HANDLE hFileExe = CreateFileW(wszExePath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecAttr*/, OPEN_EXISTING,
1145 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1146 if (hFileExe == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER)
1147 hFileExe = CreateFileW(wszExePath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecAttr*/, OPEN_EXISTING,
1148 FILE_ATTRIBUTE_NORMAL, NULL);
1149 if (hFileExe == INVALID_HANDLE_VALUE)
1150 {
1151 if (GetLastError() == ERROR_FILE_NOT_FOUND)
1152 return ErrorMsgRcSW(18, "File not found: ", wszExePath);
1153 return ErrorMsgRcSWSU(18, "Error opening '", wszExePath, "' for reading: ", GetLastError());
1154 }
1155
1156 /*
1157 * Check that the file we're about to launch is related to us and safe to start.
1158 */
1159 int rcExit = CheckThatFileIsRelated(wszExePath, wszSelfPath);
1160 if (rcExit != 0)
1161 return rcExit;
1162
1163#ifdef VBOX_SIGNING_MODE
1164# if 1 /* Use the IPRT code as it it will work on all windows versions without trouble.
1165 Added some 800KB to the executable, but so what. */
1166 rcExit = CheckFileSignatureIprt(wszExePath);
1167# else
1168 rcExit = CheckFileSignatures(wszExePath, hFileExe, wszSelfPath, hFileSelf);
1169# endif
1170 if (rcExit != 0)
1171 return rcExit;
1172#endif
1173
1174 /*
1175 * Start the process.
1176 */
1177 STARTUPINFOW StartupInfo = { sizeof(StartupInfo), 0 };
1178 PROCESS_INFORMATION ProcInfo = { 0 };
1179 SetLastError(740);
1180 BOOL fOk = CreateProcessW(wszExePath,
1181 pwszNewCmdLine,
1182 NULL /*pProcessAttributes*/,
1183 NULL /*pThreadAttributes*/,
1184 TRUE /*fInheritHandles*/,
1185 0 /*dwCreationFlags*/,
1186 NULL /*pEnvironment*/,
1187 NULL /*pCurrentDirectory*/,
1188 &StartupInfo,
1189 &ProcInfo);
1190 if (fOk)
1191 {
1192 /* Wait for the process to finish. */
1193 CloseHandle(ProcInfo.hThread);
1194 rcExit = WaitForProcess(ProcInfo.hProcess);
1195 CloseHandle(ProcInfo.hProcess);
1196 }
1197 else if (GetLastError() == ERROR_ELEVATION_REQUIRED)
1198 {
1199 /*
1200 * Elevation is required. That can be accomplished via ShellExecuteEx
1201 * and the runas atom.
1202 */
1203 MSG Msg;
1204 PeekMessage(&Msg, NULL, 0, 0, PM_NOREMOVE);
1205 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1206
1207 SHELLEXECUTEINFOW ShExecInfo = { 0 };
1208 ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
1209 ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
1210 ShExecInfo.hwnd = NULL;
1211 ShExecInfo.lpVerb = L"runas" ;
1212 ShExecInfo.lpFile = wszExePath;
1213 ShExecInfo.lpParameters = pwszOrgCmdLine; /* pass only args here!!! */
1214 ShExecInfo.lpDirectory = wszCurDir;
1215 ShExecInfo.nShow = SW_NORMAL;
1216 ShExecInfo.hProcess = INVALID_HANDLE_VALUE;
1217 if (ShellExecuteExW(&ShExecInfo))
1218 {
1219 if (ShExecInfo.hProcess != INVALID_HANDLE_VALUE)
1220 {
1221 rcExit = WaitForProcess2(ShExecInfo.hProcess);
1222 CloseHandle(ShExecInfo.hProcess);
1223 }
1224 else
1225 rcExit = ErrorMsgRc(1, "ShellExecuteExW did not return a valid process handle!");
1226 }
1227 else
1228 rcExit = ErrorMsgRcLastErrSWSR(9, "Failed to execute '", wszExePath, "' via ShellExecuteExW!");
1229 }
1230 else
1231 rcExit = ErrorMsgRcLastErrSWSR(8, "Failed to execute '", wszExePath, "' via CreateProcessW!");
1232
1233 if (pwszNewCmdLine)
1234 LocalFree(pwszNewCmdLine);
1235
1236 return rcExit;
1237}
1238
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette