shim.c 70 KB
Newer Older
Matthew Garrett's avatar
Matthew Garrett committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/*
 * shim - trivial UEFI first-stage bootloader
 *
 * Copyright 2012 Red Hat, Inc <mjg@redhat.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Significant portions of this code are derived from Tianocore
 * (http://tianocore.sf.net) and are Copyright 2009-2012 Intel
 * Corporation.
 */

36
#include "shim.h"
37 38 39 40 41 42 43 44 45

#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/ocsp.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
46 47
#include <openssl/x509.h>
#include <openssl/x509v3.h>
48 49 50 51
#include <openssl/rsa.h>
#include <openssl/dso.h>

#include <Library/BaseCryptLib.h>
52

53
#include <stdint.h>
54 55

#define OID_EKU_MODSIGN "1.3.6.1.4.1.2312.16.1.2"
Matthew Garrett's avatar
Matthew Garrett committed
56

Matthew Garrett's avatar
Matthew Garrett committed
57
static EFI_SYSTEM_TABLE *systab;
58
static EFI_HANDLE global_image_handle;
Matthew Garrett's avatar
Matthew Garrett committed
59

60 61 62
static CHAR16 *second_stage;
static void *load_options;
static UINT32 load_options_size;
63

Matthew Garrett's avatar
Matthew Garrett committed
64 65 66
/*
 * The vendor certificate used for validating the second stage loader
 */
67 68 69 70 71 72 73 74 75 76 77
extern struct {
	UINT32 vendor_cert_size;
	UINT32 vendor_dbx_size;
	UINT32 vendor_cert_offset;
	UINT32 vendor_dbx_offset;
} cert_table;

UINT32 vendor_cert_size;
UINT32 vendor_dbx_size;
UINT8 *vendor_cert;
UINT8 *vendor_dbx;
Matthew Garrett's avatar
Matthew Garrett committed
78

79 80 81 82 83 84
/*
 * indicator of how an image has been verified
 */
verification_method_t verification_method;
int loader_is_participating;

85 86
#define EFI_IMAGE_SECURITY_DATABASE_GUID { 0xd719b2cb, 0x3d3a, 0x4596, { 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f }}

87
UINT8 user_insecure_mode;
88
UINT8 ignore_db;
89

90 91 92 93 94 95
typedef enum {
	DATA_FOUND,
	DATA_NOT_FOUND,
	VAR_NOT_FOUND
} CHECK_STATUS;

96 97 98 99 100
typedef struct {
	UINT32 MokSize;
	UINT8 *Mok;
} MokListNode;

Matthew Garrett's avatar
Matthew Garrett committed
101 102 103
/*
 * Perform basic bounds checking of the intra-image pointers
 */
104
static void *ImageAddress (void *image, uint64_t size, uint64_t address)
Matthew Garrett's avatar
Matthew Garrett committed
105
{
106
	/* ensure our local pointer isn't bigger than our size */
Matthew Garrett's avatar
Matthew Garrett committed
107 108
	if (address > size)
		return NULL;
Matthew Garrett's avatar
Matthew Garrett committed
109

110 111 112 113 114
	/* Insure our math won't overflow */
	if (UINT64_MAX - address < (uint64_t)(intptr_t)image)
		return NULL;

	/* return the absolute pointer */
Matthew Garrett's avatar
Matthew Garrett committed
115 116
	return image + address;
}
Matthew Garrett's avatar
Matthew Garrett committed
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
/* here's a chart:
 *		i686	x86_64	aarch64
 *  64-on-64:	nyet	yes	yes
 *  64-on-32:	nyet	yes	nyet
 *  32-on-32:	yes	yes	no
 */
static int
allow_64_bit(void)
{
#if defined(__x86_64__) || defined(__aarch64__)
	return 1;
#elif defined(__i386__) || defined(__i686__)
	/* Right now blindly assuming the kernel will correctly detect this
	 * and /halt the system/ if you're not really on a 64-bit cpu */
	if (in_protocol)
		return 1;
	return 0;
#else /* assuming everything else is 32-bit... */
	return 0;
#endif
}

static int
allow_32_bit(void)
{
#if defined(__x86_64__)
#if defined(ALLOW_32BIT_KERNEL_ON_X64)
	if (in_protocol)
		return 1;
	return 0;
#else
	return 0;
#endif
#elif defined(__i386__) || defined(__i686__)
	return 1;
#elif defined(__arch64__)
	return 0;
#else /* assuming everything else is 32-bit... */
	return 1;
#endif
}

static int
image_is_64_bit(EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr)
{
	/* .Magic is the same offset in all cases */
	if (PEHdr->Pe32Plus.OptionalHeader.Magic
			== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC)
		return 1;
	return 0;
}

static const UINT16 machine_type =
#if defined(__x86_64__)
	IMAGE_FILE_MACHINE_X64;
#elif defined(__aarch64__)
	IMAGE_FILE_MACHINE_ARM64;
#elif defined(__arm__)
	IMAGE_FILE_MACHINE_ARMTHUMB_MIXED;
#elif defined(__i386__) || defined(__i486__) || defined(__i686__)
	IMAGE_FILE_MACHINE_I386;
#elif defined(__ia64__)
	IMAGE_FILE_MACHINE_IA64;
#else
#error this architecture is not supported by shim
#endif

static int
image_is_loadable(EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr)
{
	/* If the machine type doesn't match the binary, bail, unless
	 * we're in an allowed 64-on-32 scenario */
	if (PEHdr->Pe32.FileHeader.Machine != machine_type) {
		if (!(machine_type == IMAGE_FILE_MACHINE_I386 &&
		      PEHdr->Pe32.FileHeader.Machine == IMAGE_FILE_MACHINE_X64 &&
		      allow_64_bit())) {
			return 0;
		}
	}

	/* If it's not a header type we recognize at all, bail */
	switch (PEHdr->Pe32Plus.OptionalHeader.Magic) {
	case EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC:
	case EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC:
		break;
	default:
		return 0;
	}

	/* and now just check for general 64-vs-32 compatibility */
	if (image_is_64_bit(PEHdr)) {
		if (allow_64_bit())
			return 1;
	} else {
		if (allow_32_bit())
			return 1;
	}
	return 0;
}

Matthew Garrett's avatar
Matthew Garrett committed
218 219 220
/*
 * Perform the actual relocation
 */
Matthew Garrett's avatar
Matthew Garrett committed
221
static EFI_STATUS relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT *context,
222
				 EFI_IMAGE_SECTION_HEADER *Section,
223
				 void *orig, void *data)
Matthew Garrett's avatar
Matthew Garrett committed
224 225 226 227
{
	EFI_IMAGE_BASE_RELOCATION *RelocBase, *RelocBaseEnd;
	UINT64 Adjust;
	UINT16 *Reloc, *RelocEnd;
228
	char *Fixup, *FixupBase;
Matthew Garrett's avatar
Matthew Garrett committed
229 230 231 232
	UINT16 *Fixup16;
	UINT32 *Fixup32;
	UINT64 *Fixup64;
	int size = context->ImageSize;
233
	void *ImageEnd = (char *)orig + size;
234
	int n = 0;
Matthew Garrett's avatar
Matthew Garrett committed
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	/* Alright, so here's how this works:
	 *
	 * context->RelocDir gives us two things:
	 * - the VA the table of base relocation blocks are (maybe) to be
	 *   mapped at (RelocDir->VirtualAddress)
	 * - the virtual size (RelocDir->Size)
	 *
	 * The .reloc section (Section here) gives us some other things:
	 * - the name! kind of. (Section->Name)
	 * - the virtual size (Section->VirtualSize), which should be the same
	 *   as RelocDir->Size
	 * - the virtual address (Section->VirtualAddress)
	 * - the file section size (Section->SizeOfRawData), which is
	 *   a multiple of OptHdr->FileAlignment.  Only useful for image
	 *   validation, not really useful for iteration bounds.
	 * - the file address (Section->PointerToRawData)
	 * - a bunch of stuff we don't use that's 0 in our binaries usually
	 * - Flags (Section->Characteristics)
	 *
	 * and then the thing that's actually at the file address is an array
	 * of EFI_IMAGE_BASE_RELOCATION structs with some values packed behind
	 * them.  The SizeOfBlock field of this structure includes the
	 * structure itself, and adding it to that structure's address will
	 * yield the next entry in the array.
	 */
	RelocBase = ImageAddress(orig, size, Section->PointerToRawData);
	/* RelocBaseEnd here is the address of the first entry /past/ the
	 * table.  */
	RelocBaseEnd = ImageAddress(orig, size, Section->PointerToRawData +
						Section->Misc.VirtualSize);

	if (!RelocBase && !RelocBaseEnd)
		return EFI_SUCCESS;
Matthew Garrett's avatar
Matthew Garrett committed
269

Matthew Garrett's avatar
Matthew Garrett committed
270
	if (!RelocBase || !RelocBaseEnd) {
271
		perror(L"Reloc table overflows binary\n");
Matthew Garrett's avatar
Matthew Garrett committed
272
		return EFI_UNSUPPORTED;
Matthew Garrett's avatar
Matthew Garrett committed
273 274
	}

275
	Adjust = (UINTN)data - context->ImageAddress;
Matthew Garrett's avatar
Matthew Garrett committed
276

277 278 279
	if (Adjust == 0)
		return EFI_SUCCESS;

Matthew Garrett's avatar
Matthew Garrett committed
280 281
	while (RelocBase < RelocBaseEnd) {
		Reloc = (UINT16 *) ((char *) RelocBase + sizeof (EFI_IMAGE_BASE_RELOCATION));
Matthew Garrett's avatar
Matthew Garrett committed
282

283 284 285 286 287 288 289 290
		if (RelocBase->SizeOfBlock == 0) {
			perror(L"Reloc %d block size 0 is invalid\n", n);
			return EFI_UNSUPPORTED;
		} else if (RelocBase->SizeOfBlock > context->RelocDir->Size) {
			perror(L"Reloc %d block size %d greater than reloc dir"
					"size %d, which is invalid\n", n,
					RelocBase->SizeOfBlock,
					context->RelocDir->Size);
291 292 293 294
			return EFI_UNSUPPORTED;
		}

		RelocEnd = (UINT16 *) ((char *) RelocBase + RelocBase->SizeOfBlock);
295
		if ((void *)RelocEnd < orig || (void *)RelocEnd > ImageEnd) {
296
			perror(L"Reloc %d entry overflows binary\n", n);
Matthew Garrett's avatar
Matthew Garrett committed
297
			return EFI_UNSUPPORTED;
Matthew Garrett's avatar
Matthew Garrett committed
298 299
		}

Matthew Garrett's avatar
Matthew Garrett committed
300
		FixupBase = ImageAddress(data, size, RelocBase->VirtualAddress);
Matthew Garrett's avatar
Matthew Garrett committed
301
		if (!FixupBase) {
302
			perror(L"Reloc %d Invalid fixupbase\n", n);
Matthew Garrett's avatar
Matthew Garrett committed
303
			return EFI_UNSUPPORTED;
Matthew Garrett's avatar
Matthew Garrett committed
304 305
		}

Matthew Garrett's avatar
Matthew Garrett committed
306 307 308 309 310
		while (Reloc < RelocEnd) {
			Fixup = FixupBase + (*Reloc & 0xFFF);
			switch ((*Reloc) >> 12) {
			case EFI_IMAGE_REL_BASED_ABSOLUTE:
				break;
Matthew Garrett's avatar
Matthew Garrett committed
311

Matthew Garrett's avatar
Matthew Garrett committed
312 313 314 315
			case EFI_IMAGE_REL_BASED_HIGH:
				Fixup16   = (UINT16 *) Fixup;
				*Fixup16 = (UINT16) (*Fixup16 + ((UINT16) ((UINT32) Adjust >> 16)));
				break;
Matthew Garrett's avatar
Matthew Garrett committed
316

Matthew Garrett's avatar
Matthew Garrett committed
317 318 319 320
			case EFI_IMAGE_REL_BASED_LOW:
				Fixup16   = (UINT16 *) Fixup;
				*Fixup16  = (UINT16) (*Fixup16 + (UINT16) Adjust);
				break;
Matthew Garrett's avatar
Matthew Garrett committed
321

Matthew Garrett's avatar
Matthew Garrett committed
322 323 324 325
			case EFI_IMAGE_REL_BASED_HIGHLOW:
				Fixup32   = (UINT32 *) Fixup;
				*Fixup32  = *Fixup32 + (UINT32) Adjust;
				break;
Matthew Garrett's avatar
Matthew Garrett committed
326

Matthew Garrett's avatar
Matthew Garrett committed
327 328 329 330
			case EFI_IMAGE_REL_BASED_DIR64:
				Fixup64 = (UINT64 *) Fixup;
				*Fixup64 = *Fixup64 + (UINT64) Adjust;
				break;
Matthew Garrett's avatar
Matthew Garrett committed
331

Matthew Garrett's avatar
Matthew Garrett committed
332
			default:
333
				perror(L"Reloc %d Unknown relocation\n", n);
Matthew Garrett's avatar
Matthew Garrett committed
334 335 336
				return EFI_UNSUPPORTED;
			}
			Reloc += 1;
337
		}
Matthew Garrett's avatar
Matthew Garrett committed
338
		RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;
339
		n++;
Matthew Garrett's avatar
Matthew Garrett committed
340
	}
Matthew Garrett's avatar
Matthew Garrett committed
341 342 343 344

	return EFI_SUCCESS;
}

345 346 347 348 349 350 351 352
static void
drain_openssl_errors(void)
{
	unsigned long err = -1;
	while (err != 0)
		err = ERR_get_error();
}

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
static BOOLEAN verify_x509(UINT8 *Cert, UINTN CertSize)
{
	UINTN length;

	if (!Cert || CertSize < 4)
		return FALSE;

	/*
	 * A DER encoding x509 certificate starts with SEQUENCE(0x30),
	 * the number of length bytes, and the number of value bytes.
	 * The size of a x509 certificate is usually between 127 bytes
	 * and 64KB. For convenience, assume the number of value bytes
	 * is 2, i.e. the second byte is 0x82.
	 */
	if (Cert[0] != 0x30 || Cert[1] != 0x82)
		return FALSE;

	length = Cert[2]<<8 | Cert[3];
	if (length != (CertSize - 4))
		return FALSE;

	return TRUE;
}

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
static BOOLEAN verify_eku(UINT8 *Cert, UINTN CertSize)
{
	X509 *x509;
	CONST UINT8 *Temp = Cert;
	EXTENDED_KEY_USAGE *eku;
	ASN1_OBJECT *module_signing;

	module_signing = OBJ_nid2obj(OBJ_create(OID_EKU_MODSIGN, NULL, NULL));

	x509 = d2i_X509 (NULL, &Temp, (long) CertSize);
	if (x509 != NULL) {
		eku = X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL);

		if (eku) {
			int i = 0;
			for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
				ASN1_OBJECT *key_usage = sk_ASN1_OBJECT_value(eku, i);

				if (OBJ_cmp(module_signing, key_usage) == 0)
					return FALSE;
			}
			EXTENDED_KEY_USAGE_free(eku);
		}

		X509_free(x509);
	}

404 405
	OBJ_cleanup();

406 407 408
	return TRUE;
}

409 410 411
static CHECK_STATUS check_db_cert_in_ram(EFI_SIGNATURE_LIST *CertList,
					 UINTN dbsize,
					 WIN_CERTIFICATE_EFI_PKCS *data,
412 413
					 UINT8 *hash, CHAR16 *dbname,
					 EFI_GUID guid)
414 415
{
	EFI_SIGNATURE_DATA *Cert;
416
	UINTN CertSize;
417
	BOOLEAN IsFound = FALSE;
418 419

	while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
420
		if (CompareGuid (&CertList->SignatureType, &EFI_CERT_TYPE_X509_GUID) == 0) {
421
			Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
422 423
			CertSize = CertList->SignatureSize - sizeof(EFI_GUID);
			if (verify_x509(Cert->SignatureData, CertSize)) {
424 425 426 427 428 429
				if (verify_eku(Cert->SignatureData, CertSize)) {
					IsFound = AuthenticodeVerify (data->CertData,
								      data->Hdr.dwLength - sizeof(data->Hdr),
								      Cert->SignatureData,
								      CertSize,
								      hash, SHA256_DIGEST_SIZE);
430 431 432
					if (IsFound) {
						tpm_measure_variable(dbname, guid, CertSize, Cert->SignatureData);
						drain_openssl_errors();
433
						return DATA_FOUND;
434 435 436
					} else {
						LogError(L"AuthenticodeVerify(): %d\n", IsFound);
					}
437
				}
438 439
			} else if (verbose) {
				console_notify(L"Not a DER encoding x.509 Certificate");
440 441 442 443 444 445 446 447 448 449
			}
		}

		dbsize -= CertList->SignatureListSize;
		CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
	}

	return DATA_NOT_FOUND;
}

450 451
static CHECK_STATUS check_db_cert(CHAR16 *dbname, EFI_GUID guid,
				  WIN_CERTIFICATE_EFI_PKCS *data, UINT8 *hash)
452
{
453
	CHECK_STATUS rc;
454 455 456
	EFI_STATUS efi_status;
	EFI_SIGNATURE_LIST *CertList;
	UINTN dbsize = 0;
457
	UINT8 *db;
458

459
	efi_status = get_variable(dbname, &db, &dbsize, guid);
460
	if (EFI_ERROR(efi_status))
461
		return VAR_NOT_FOUND;
462

463
	CertList = (EFI_SIGNATURE_LIST *)db;
464

465
	rc = check_db_cert_in_ram(CertList, dbsize, data, hash, dbname, guid);
466 467 468 469 470 471

	FreePool(db);

	return rc;
}

Matthew Garrett's avatar
Matthew Garrett committed
472 473 474
/*
 * Check a hash against an EFI_SIGNATURE_LIST in a buffer
 */
475 476
static CHECK_STATUS check_db_hash_in_ram(EFI_SIGNATURE_LIST *CertList,
					 UINTN dbsize, UINT8 *data,
477 478
					 int SignatureSize, EFI_GUID CertType,
					 CHAR16 *dbname, EFI_GUID guid)
479 480 481 482 483
{
	EFI_SIGNATURE_DATA *Cert;
	UINTN CertCount, Index;
	BOOLEAN IsFound = FALSE;

484
	while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
485
		CertCount = (CertList->SignatureListSize -sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
486
		Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
487
		if (CompareGuid(&CertList->SignatureType, &CertType) == 0) {
488
			for (Index = 0; Index < CertCount; Index++) {
489
				if (CompareMem (Cert->SignatureData, data, SignatureSize) == 0) {
490 491 492 493
					//
					// Find the signature in database.
					//
					IsFound = TRUE;
494
					tpm_measure_variable(dbname, guid, SignatureSize, data);
495 496 497 498 499 500 501 502 503 504
					break;
				}

				Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
			}
			if (IsFound) {
				break;
			}
		}

505
		dbsize -= CertList->SignatureListSize;
506 507 508 509
		CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
	}

	if (IsFound)
510 511 512 513 514
		return DATA_FOUND;

	return DATA_NOT_FOUND;
}

Matthew Garrett's avatar
Matthew Garrett committed
515 516 517
/*
 * Check a hash against an EFI_SIGNATURE_LIST in a UEFI variable
 */
518 519 520 521 522 523
static CHECK_STATUS check_db_hash(CHAR16 *dbname, EFI_GUID guid, UINT8 *data,
				  int SignatureSize, EFI_GUID CertType)
{
	EFI_STATUS efi_status;
	EFI_SIGNATURE_LIST *CertList;
	UINTN dbsize = 0;
524
	UINT8 *db;
525

526
	efi_status = get_variable(dbname, &db, &dbsize, guid);
527
	if (EFI_ERROR(efi_status)) {
528 529 530
		return VAR_NOT_FOUND;
	}

531
	CertList = (EFI_SIGNATURE_LIST *)db;
532 533

	CHECK_STATUS rc = check_db_hash_in_ram(CertList, dbsize, data,
534 535
					       SignatureSize, CertType,
					       dbname, guid);
536 537 538 539 540
	FreePool(db);
	return rc;

}

Matthew Garrett's avatar
Matthew Garrett committed
541 542 543 544
/*
 * Check whether the binary signature or hash are present in dbx or the
 * built-in blacklist
 */
Matthew Garrett's avatar
Matthew Garrett committed
545 546
static EFI_STATUS check_blacklist (WIN_CERTIFICATE_EFI_PKCS *cert,
				   UINT8 *sha256hash, UINT8 *sha1hash)
547
{
548
	EFI_SIGNATURE_LIST *dbx = (EFI_SIGNATURE_LIST *)vendor_dbx;
549

550
	if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha256hash,
551 552
			SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID, L"dbx",
			EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
553
		LogError(L"binary sha256hash found in vendor dbx\n");
554
		return EFI_SECURITY_VIOLATION;
555
	}
556
	if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha1hash,
557 558
				 SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID, L"dbx",
				 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
559
		LogError(L"binary sha1hash found in vendor dbx\n");
560
		return EFI_SECURITY_VIOLATION;
561
	}
562 563 564
	if (cert &&
	    check_db_cert_in_ram(dbx, vendor_dbx_size, cert, sha256hash, L"dbx",
				 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
565
		LogError(L"cert sha256hash found in vendor dbx\n");
566
		return EFI_SECURITY_VIOLATION;
567
	}
568 569
	if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
570
		LogError(L"binary sha256hash found in system dbx\n");
571
		return EFI_SECURITY_VIOLATION;
572
	}
573 574
	if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha1hash,
			  SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID) == DATA_FOUND) {
575
		LogError(L"binary sha1hash found in system dbx\n");
576
		return EFI_SECURITY_VIOLATION;
577
	}
578 579 580
	if (cert &&
	    check_db_cert(L"dbx", EFI_SECURE_BOOT_DB_GUID,
			  cert, sha256hash) == DATA_FOUND) {
581
		LogError(L"cert sha256hash found in system dbx\n");
582
		return EFI_SECURITY_VIOLATION;
583
	}
584 585
	if (check_db_hash(L"MokListX", SHIM_LOCK_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
586
		LogError(L"binary sha256hash found in Mok dbx\n");
587
		return EFI_SECURITY_VIOLATION;
588
	}
589 590 591
	if (cert &&
	    check_db_cert(L"MokListX", SHIM_LOCK_GUID,
			  cert, sha256hash) == DATA_FOUND) {
592
		LogError(L"cert sha256hash found in Mok dbx\n");
593
		return EFI_SECURITY_VIOLATION;
594
	}
595

596
	drain_openssl_errors();
597 598 599
	return EFI_SUCCESS;
}

600 601 602 603 604 605
static void update_verification_method(verification_method_t method)
{
	if (verification_method == VERIFIED_BY_NOTHING)
		verification_method = method;
}

Matthew Garrett's avatar
Matthew Garrett committed
606 607 608
/*
 * Check whether the binary signature or hash are present in db or MokList
 */
Matthew Garrett's avatar
Matthew Garrett committed
609 610
static EFI_STATUS check_whitelist (WIN_CERTIFICATE_EFI_PKCS *cert,
				   UINT8 *sha256hash, UINT8 *sha1hash)
611
{
612
	if (!ignore_db) {
613
		if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha256hash, SHA256_DIGEST_SIZE,
614 615 616
					EFI_CERT_SHA256_GUID) == DATA_FOUND) {
			update_verification_method(VERIFIED_BY_HASH);
			return EFI_SUCCESS;
617 618
		} else {
			LogError(L"check_db_hash(db, sha256hash) != DATA_FOUND\n");
619
		}
620
		if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha1hash, SHA1_DIGEST_SIZE,
621 622 623 624
					EFI_CERT_SHA1_GUID) == DATA_FOUND) {
			verification_method = VERIFIED_BY_HASH;
			update_verification_method(VERIFIED_BY_HASH);
			return EFI_SUCCESS;
625 626
		} else {
			LogError(L"check_db_hash(db, sha1hash) != DATA_FOUND\n");
627
		}
628
		if (cert && check_db_cert(L"db", EFI_SECURE_BOOT_DB_GUID, cert, sha256hash)
629
					== DATA_FOUND) {
630 631 632
			verification_method = VERIFIED_BY_CERT;
			update_verification_method(VERIFIED_BY_CERT);
			return EFI_SUCCESS;
633 634
		} else {
			LogError(L"check_db_cert(db, sha256hash) != DATA_FOUND\n");
635
		}
636
	}
637

638 639 640
	if (check_db_hash(L"MokList", SHIM_LOCK_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID)
				== DATA_FOUND) {
641 642
		verification_method = VERIFIED_BY_HASH;
		update_verification_method(VERIFIED_BY_HASH);
643
		return EFI_SUCCESS;
644 645
	} else {
		LogError(L"check_db_hash(MokList, sha256hash) != DATA_FOUND\n");
646
	}
647 648
	if (cert && check_db_cert(L"MokList", SHIM_LOCK_GUID, cert, sha256hash)
			== DATA_FOUND) {
649 650
		verification_method = VERIFIED_BY_CERT;
		update_verification_method(VERIFIED_BY_CERT);
651
		return EFI_SUCCESS;
652 653
	} else {
		LogError(L"check_db_cert(MokList, sha256hash) != DATA_FOUND\n");
654
	}
655

656
	update_verification_method(VERIFIED_BY_NOTHING);
657
	return EFI_SECURITY_VIOLATION;
658 659
}

660 661 662 663 664 665
/*
 * Check whether we're in Secure Boot and user mode
 */

static BOOLEAN secure_mode (void)
{
666
	static int first = 1;
667
	if (user_insecure_mode)
668 669
		return FALSE;

670
	if (variable_is_secureboot() != 1) {
671
		if (verbose && !in_protocol && first)
672
			console_notify(L"Secure boot not enabled");
673
		first = 0;
674 675
		return FALSE;
	}
676

677 678 679 680 681 682 683
	/* If we /do/ have "SecureBoot", but /don't/ have "SetupMode",
	 * then the implementation is bad, but we assume that secure boot is
	 * enabled according to the status of "SecureBoot".  If we have both
	 * of them, then "SetupMode" may tell us additional data, and we need
	 * to consider it.
	 */
	if (variable_is_setupmode(0) == 1) {
684
		if (verbose && !in_protocol && first)
685
			console_notify(L"Platform is in setup mode");
686
		first = 0;
687 688 689
		return FALSE;
	}

690
	first = 0;
691 692 693
	return TRUE;
}

694 695 696
#define check_size_line(data, datasize_in, hashbase, hashsize, l) ({	\
	if ((unsigned long)hashbase >					\
			(unsigned long)data + datasize_in) {		\
697
		efi_status = EFI_INVALID_PARAMETER;			\
698 699 700 701 702 703
		perror(L"shim.c:%d Invalid hash base 0x%016x\n", l,	\
			hashbase);					\
		goto done;						\
	}								\
	if ((unsigned long)hashbase + hashsize >			\
			(unsigned long)data + datasize_in) {		\
704
		efi_status = EFI_INVALID_PARAMETER;			\
705 706 707 708 709 710 711
		perror(L"shim.c:%d Invalid hash size 0x%016x\n", l,	\
			hashsize);					\
		goto done;						\
	}								\
})
#define check_size(d,ds,h,hs) check_size_line(d,ds,h,hs,__LINE__)

Matthew Garrett's avatar
Matthew Garrett committed
712
/*
Matthew Garrett's avatar
Matthew Garrett committed
713
 * Calculate the SHA1 and SHA256 hashes of a binary
Matthew Garrett's avatar
Matthew Garrett committed
714
 */
Matthew Garrett's avatar
Matthew Garrett committed
715

716
static EFI_STATUS generate_hash (char *data, unsigned int datasize_in,
Matthew Garrett's avatar
Matthew Garrett committed
717 718 719
				 PE_COFF_LOADER_IMAGE_CONTEXT *context,
				 UINT8 *sha256hash, UINT8 *sha1hash)

Matthew Garrett's avatar
Matthew Garrett committed
720
{
Matthew Garrett's avatar
Matthew Garrett committed
721
	unsigned int sha256ctxsize, sha1ctxsize;
722
	unsigned int size = datasize_in;
Matthew Garrett's avatar
Matthew Garrett committed
723
	void *sha256ctx = NULL, *sha1ctx = NULL;
Matthew Garrett's avatar
Matthew Garrett committed
724 725 726
	char *hashbase;
	unsigned int hashsize;
	unsigned int SumOfBytesHashed, SumOfSectionBytes;
727
	unsigned int index, pos;
728
	unsigned int datasize;
Matthew Garrett's avatar
Matthew Garrett committed
729
	EFI_IMAGE_SECTION_HEADER  *Section;
Matthew Garrett's avatar
Matthew Garrett committed
730
	EFI_IMAGE_SECTION_HEADER  *SectionHeader = NULL;
731
	EFI_STATUS efi_status = EFI_SUCCESS;
732 733
	EFI_IMAGE_DOS_HEADER *DosHdr = (void *)data;
	unsigned int PEHdr_offset = 0;
Matthew Garrett's avatar
Matthew Garrett committed
734

735
	size = datasize = datasize_in;
736

737 738
	if (datasize <= sizeof (*DosHdr) ||
	    DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
739
		perror(L"Invalid signature\n");
740 741 742 743 744 745 746 747 748 749
		return EFI_INVALID_PARAMETER;
	}
	PEHdr_offset = DosHdr->e_lfanew;

	sha256ctxsize = Sha256GetContextSize();
	sha256ctx = AllocatePool(sha256ctxsize);

	sha1ctxsize = Sha1GetContextSize();
	sha1ctx = AllocatePool(sha1ctxsize);

Matthew Garrett's avatar
Matthew Garrett committed
750
	if (!sha256ctx || !sha1ctx) {
751
		perror(L"Unable to allocate memory for hash context\n");
Matthew Garrett's avatar
Matthew Garrett committed
752 753 754
		return EFI_OUT_OF_RESOURCES;
	}

Matthew Garrett's avatar
Matthew Garrett committed
755
	if (!Sha256Init(sha256ctx) || !Sha1Init(sha1ctx)) {
756
		perror(L"Unable to initialise hash\n");
757
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
758 759 760 761
		goto done;
	}

	/* Hash start to checksum */
Matthew Garrett's avatar
Matthew Garrett committed
762
	hashbase = data;
Matthew Garrett's avatar
Matthew Garrett committed
763 764
	hashsize = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum -
		hashbase;
765
	check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
766

Matthew Garrett's avatar
Matthew Garrett committed
767 768
	if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
	    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
769
		perror(L"Unable to generate hash\n");
770
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
771 772 773 774 775 776 777
		goto done;
	}

	/* Hash post-checksum to start of certificate table */
	hashbase = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum +
		sizeof (int);
	hashsize = (char *)context->SecDir - hashbase;
778
	check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
779

Matthew Garrett's avatar
Matthew Garrett committed
780 781
	if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
	    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
782
		perror(L"Unable to generate hash\n");
783
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
784 785 786 787
		goto done;
	}

	/* Hash end of certificate table to end of image header */
788 789 790 791 792
	EFI_IMAGE_DATA_DIRECTORY *dd = context->SecDir + 1;
	hashbase = (char *)dd;
	hashsize = context->SizeOfHeaders - (unsigned long)((char *)dd - data);
	if (hashsize > datasize_in) {
		perror(L"Data Directory size %d is invalid\n", hashsize);
793
		efi_status = EFI_INVALID_PARAMETER;
794 795
		goto done;
	}
796
	check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
797

Matthew Garrett's avatar
Matthew Garrett committed
798 799
	if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
	    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
800
		perror(L"Unable to generate hash\n");
801
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
802 803 804
		goto done;
	}

Matthew Garrett's avatar
Matthew Garrett committed
805
	/* Sort sections */
806
	SumOfBytesHashed = context->SizeOfHeaders;
Matthew Garrett's avatar
Matthew Garrett committed
807

808
	/* Validate section locations and sizes */
809
	for (index = 0, SumOfSectionBytes = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
810 811 812 813
		EFI_IMAGE_SECTION_HEADER  *SectionPtr;

		/* Validate SectionPtr is within image */
		SectionPtr = ImageAddress(data, datasize,
814
			PEHdr_offset +
815 816 817 818 819
			sizeof (UINT32) +
			sizeof (EFI_IMAGE_FILE_HEADER) +
			context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader +
			(index * sizeof(*SectionPtr)));
		if (!SectionPtr) {
820
			perror(L"Malformed section %d\n", index);
821
			efi_status = EFI_INVALID_PARAMETER;
822 823 824 825 826
			goto done;
		}
		/* Validate section size is within image. */
		if (SectionPtr->SizeOfRawData >
		    datasize - SumOfBytesHashed - SumOfSectionBytes) {
827
			perror(L"Malformed section %d size\n", index);
828
			efi_status = EFI_INVALID_PARAMETER;
829 830 831
			goto done;
		}
		SumOfSectionBytes += SectionPtr->SizeOfRawData;
Matthew Garrett's avatar
Matthew Garrett committed
832 833 834 835
	}

	SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * context->PEHdr->Pe32.FileHeader.NumberOfSections);
	if (SectionHeader == NULL) {
836
		perror(L"Unable to allocate section header\n");
837
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
838 839 840
		goto done;
	}

841
	/* Already validated above */
842 843 844
	Section = ImageAddress(data, datasize,
		PEHdr_offset +
		sizeof (UINT32) +
845 846
		sizeof (EFI_IMAGE_FILE_HEADER) +
		context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader);
847 848 849 850 851 852 853 854 855 856 857 858 859
	/* But check it again just for better error messaging, and so
	 * clang-analyzer doesn't get confused. */
	if (Section == NULL) {
		uint64_t addr;

		addr = PEHdr_offset + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER)
			+ context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader;
		perror(L"Malformed file header.\n");
		perror(L"Image address for Section 0 is 0x%016llx\n", addr);
		perror(L"File size is 0x%016llx\n", datasize);
		efi_status = EFI_INVALID_PARAMETER;
		goto done;
	}
860

Matthew Garrett's avatar
Matthew Garrett committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
	/* Sort the section headers */
	for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
		pos = index;
		while ((pos > 0) && (Section->PointerToRawData < SectionHeader[pos - 1].PointerToRawData)) {
			CopyMem (&SectionHeader[pos], &SectionHeader[pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
			pos--;
		}
		CopyMem (&SectionHeader[pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
		Section += 1;
	}

	/* Hash the sections */
	for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
		Section = &SectionHeader[index];
		if (Section->SizeOfRawData == 0) {
			continue;
		}
878
		hashbase  = ImageAddress(data, size, Section->PointerToRawData);
Matthew Garrett's avatar
Matthew Garrett committed
879

Matthew Garrett's avatar
Matthew Garrett committed
880
		if (!hashbase) {
881
			perror(L"Malformed section header\n");
882
			efi_status = EFI_INVALID_PARAMETER;
883
			goto done;
Matthew Garrett's avatar
Matthew Garrett committed
884 885
		}

886 887 888
		/* Verify hashsize within image. */
		if (Section->SizeOfRawData >
		    datasize - Section->PointerToRawData) {
889
			perror(L"Malformed section raw size %d\n", index);
890
			efi_status = EFI_INVALID_PARAMETER;
891 892 893
			goto done;
		}
		hashsize  = (unsigned int) Section->SizeOfRawData;
894
		check_size(data, datasize_in, hashbase, hashsize);
895

Matthew Garrett's avatar
Matthew Garrett committed
896 897
		if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
		    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
898
			perror(L"Unable to generate hash\n");
899
			efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
900 901 902 903 904
			goto done;
		}
		SumOfBytesHashed += Section->SizeOfRawData;
	}

905 906
	/* Hash all remaining data up to SecDir if SecDir->Size is not 0 */
	if (datasize > SumOfBytesHashed && context->SecDir->Size) {
Matthew Garrett's avatar
Matthew Garrett committed
907
		hashbase = data + SumOfBytesHashed;
908
		hashsize = datasize - context->SecDir->Size - SumOfBytesHashed;
909 910 911 912

		if ((datasize - SumOfBytesHashed < context->SecDir->Size) ||
		    (SumOfBytesHashed + hashsize != context->SecDir->VirtualAddress)) {
			perror(L"Malformed binary after Attribute Certificate Table\n");
913 914 915 916 917
			console_print(L"datasize: %u SumOfBytesHashed: %u SecDir->Size: %lu\n",
				      datasize, SumOfBytesHashed, context->SecDir->Size);
			console_print(L"hashsize: %u SecDir->VirtualAddress: 0x%08lx\n",
				      hashsize, context->SecDir->VirtualAddress);
			efi_status = EFI_INVALID_PARAMETER;
918 919
			goto done;
		}
920
		check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
921

Matthew Garrett's avatar
Matthew Garrett committed
922 923
		if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
		    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
924
			perror(L"Unable to generate hash\n");
925
			efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
926 927
			goto done;
		}
928

929 930 931
#if 1
	}
#else // we have to migrate to doing this later :/
932
		SumOfBytesHashed += hashsize;
Matthew Garrett's avatar
Matthew Garrett committed
933 934
	}

935 936 937 938 939 940 941 942 943 944
	/* Hash all remaining data */
	if (datasize > SumOfBytesHashed) {
		hashbase = data + SumOfBytesHashed;
		hashsize = datasize - SumOfBytesHashed;

		check_size(data, datasize_in, hashbase, hashsize);

		if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
		    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
			perror(L"Unable to generate hash\n");
945
			efi_status = EFI_OUT_OF_RESOURCES;
946 947 948 949 950 951 952
			goto done;
		}

		SumOfBytesHashed += hashsize;
	}
#endif

Matthew Garrett's avatar
Matthew Garrett committed
953 954
	if (!(Sha256Final(sha256ctx, sha256hash)) ||
	    !(Sha1Final(sha1ctx, sha1hash))) {
955
		perror(L"Unable to finalise hash\n");
956
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
957 958 959
		goto done;
	}

Matthew Garrett's avatar
Matthew Garrett committed
960 961 962 963 964 965 966 967
done:
	if (SectionHeader)
		FreePool(SectionHeader);
	if (sha1ctx)
		FreePool(sha1ctx);
	if (sha256ctx)
		FreePool(sha256ctx);

968
	return efi_status;
969 970
}

Matthew Garrett's avatar
Matthew Garrett committed
971 972 973 974
/*
 * Check that the signature is valid and matches the binary
 */
static EFI_STATUS verify_buffer (char *data, int datasize,
975 976
				 PE_COFF_LOADER_IMAGE_CONTEXT *context,
				 UINT8 *sha256hash, UINT8 *sha1hash)
Matthew Garrett's avatar
Matthew Garrett committed
977
{
978
	EFI_STATUS efi_status = EFI_SECURITY_VIOLATION;
979
	WIN_CERTIFICATE_EFI_PKCS *cert = NULL;
Matthew Garrett's avatar
Matthew Garrett committed
980
	unsigned int size = datasize;
981 982 983

	if (datasize < 0)
		return EFI_INVALID_PARAMETER;
Matthew Garrett's avatar
Matthew Garrett committed
984

985
	if (context->SecDir->Size != 0) {
986 987 988 989 990
		if (context->SecDir->Size >= size) {
			perror(L"Certificate Database size is too large\n");
			return EFI_INVALID_PARAMETER;
		}

991 992
		cert = ImageAddress (data, size,
				     context->SecDir->VirtualAddress);
993

994
		if (!cert) {
995
			perror(L"Certificate located outside the image\n");
996 997
			return EFI_INVALID_PARAMETER;
		}
Matthew Garrett's avatar
Matthew Garrett committed
998

999 1000 1001 1002 1003
		if (cert->Hdr.dwLength > context->SecDir->Size) {
			perror(L"Certificate list size is inconsistent with PE headers");
			return EFI_INVALID_PARAMETER;
		}

1004 1005
		if (cert->Hdr.wCertificateType !=
		    WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1006
			perror(L"Unsupported certificate type %x\n",
1007 1008 1009
				cert->Hdr.wCertificateType);
			return EFI_UNSUPPORTED;
		}
Matthew Garrett's avatar
Matthew Garrett committed
1010 1011
	}

1012 1013 1014 1015 1016 1017 1018
	/*
	 * Clear OpenSSL's error log, because we get some DSO unimplemented
	 * errors during its intialization, and we don't want those to look
	 * like they're the reason for validation failures.
	 */
	drain_openssl_errors();

1019 1020 1021 1022
	efi_status = generate_hash(data, datasize, context, sha256hash, sha1hash);
	if (EFI_ERROR(efi_status)) {
		LogError(L"generate_hash: %r\n", efi_status);
		return efi_status;
1023
	}
1024

Matthew Garrett's avatar
Matthew Garrett committed
1025 1026 1027
	/*
	 * Ensure that the binary isn't blacklisted
	 */
1028 1029
	efi_status = check_blacklist(cert, sha256hash, sha1hash);
	if (EFI_ERROR(efi_status)) {
1030
		perror(L"Binary is blacklisted\n");
1031 1032
		LogError(L"Binary is blacklisted: %r\n", efi_status);
		return efi_status;
1033 1034
	}

Matthew Garrett's avatar
Matthew Garrett committed
1035 1036 1037 1038
	/*
	 * Check whether the binary is whitelisted in any of the firmware
	 * databases
	 */
1039 1040 1041
	efi_status = check_whitelist(cert, sha256hash, sha1hash);
	if (EFI_ERROR(efi_status)) {
		LogError(L"check_whitelist(): %r\n", efi_status);
1042
	} else {
1043 1044
		drain_openssl_errors();
		return efi_status;
1045
	}
1046

1047
	if (cert) {
1048
#if defined(ENABLE_SHIM_CERT)
1049 1050 1051
		/*
		 * Check against the shim build key
		 */
1052 1053
		if (sizeof(shim_cert) &&
		    AuthenticodeVerify(cert->CertData,
1054
			       cert->Hdr.dwLength - sizeof(cert->Hdr),
1055 1056
			       shim_cert, sizeof(shim_cert), sha256hash,
			       SHA256_DIGEST_SIZE)) {
1057
			update_verification_method(VERIFIED_BY_CERT);
1058 1059 1060
			tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
					     sizeof(shim_cert), shim_cert);
			efi_status = EFI_SUCCESS;
1061
			drain_openssl_errors();
1062
			return efi_status;
1063 1064
		} else {
			LogError(L"AuthenticodeVerify(shim_cert) failed\n");
1065
		}
1066
#endif /* defined(ENABLE_SHIM_CERT) */
1067

1068 1069 1070
		/*
		 * And finally, check against shim's built-in key
		 */
1071 1072 1073 1074 1075
		if (vendor_cert_size &&
		    AuthenticodeVerify(cert->CertData,
				       cert->Hdr.dwLength - sizeof(cert->Hdr),
				       vendor_cert, vendor_cert_size,
				       sha256hash, SHA256_DIGEST_SIZE)) {
1076
			update_verification_method(VERIFIED_BY_CERT);
1077 1078 1079
			tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
					     vendor_cert_size, vendor_cert);
			efi_status = EFI_SUCCESS;
1080
			drain_openssl_errors();
1081
			return efi_status;
1082 1083
		} else {
			LogError(L"AuthenticodeVerify(vendor_cert) failed\n");
1084
		}
1085 1086
	}

1087 1088 1089
	LogError(L"Binary is not whitelisted\n");
	crypterr(EFI_SECURITY_VIOLATION);
	PrintErrors();
1090 1091
	efi_status = EFI_SECURITY_VIOLATION;
	return efi_status;
Matthew Garrett's avatar
Matthew Garrett committed
1092
}
Matthew Garrett's avatar
Matthew Garrett committed
1093

Matthew Garrett's avatar
Matthew Garrett committed
1094 1095 1096
/*
 * Read the binary header and grab appropriate information from it
 */
1097
static EFI_STATUS read_header(void *data, unsigned int datasize,
Matthew Garrett's avatar
Matthew Garrett committed
1098 1099
			      PE_COFF_LOADER_IMAGE_CONTEXT *context)
{
Matthew Garrett's avatar
Matthew Garrett committed
1100 1101
	EFI_IMAGE_DOS_HEADER *DosHdr = data;
	EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr = data;
1102
	unsigned long HeaderWithoutDataDir, SectionHeaderOffset, OptHeaderSize;
1103
	unsigned long FileAlignment = 0;
Matthew Garrett's avatar
Matthew Garrett committed
1104

1105
	if (datasize < sizeof (PEHdr->Pe32)) {
1106
		perror(L"Invalid image\n");
1107 1108 1109
		return EFI_UNSUPPORTED;
	}

Matthew Garrett's avatar
Matthew Garrett committed
1110
	if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE)
Matthew Garrett's avatar
Matthew Garrett committed
1111
		PEHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((char *)data + DosHdr->e_lfanew);
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

	if (!image_is_loadable(PEHdr)) {
		perror(L"Platform does not support this image\n");
		return EFI_UNSUPPORTED;
	}

	if (image_is_64_bit(PEHdr)) {
		context->NumberOfRvaAndSizes = PEHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes;
		context->SizeOfHeaders = PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders;
		context->ImageSize = PEHdr->Pe32Plus.OptionalHeader.SizeOfImage;
1122
		context->SectionAlignment = PEHdr->Pe32Plus.OptionalHeader.SectionAlignment;
1123
		FileAlignment = PEHdr->Pe32Plus.OptionalHeader.FileAlignment;
1124 1125 1126 1127 1128
		OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER64);
	} else {
		context->NumberOfRvaAndSizes = PEHdr->Pe32.OptionalHeader.NumberOfRvaAndSizes;
		context->SizeOfHeaders = PEHdr->Pe32.OptionalHeader.SizeOfHeaders;
		context->ImageSize = (UINT64)PEHdr->Pe32.OptionalHeader.SizeOfImage;
1129
		context->SectionAlignment = PEHdr->Pe32.OptionalHeader.SectionAlignment;
1130
		FileAlignment = PEHdr->Pe32.OptionalHeader.FileAlignment;
1131 1132 1133
		OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER32);
	}

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	if (FileAlignment % 2 != 0) {
		perror(L"File Alignment is invalid (%d)\n", FileAlignment);
		return EFI_UNSUPPORTED;
	}
	if (FileAlignment == 0)
		FileAlignment = 0x200;
	if (context->SectionAlignment == 0)
		context->SectionAlignment = PAGE_SIZE;
	if (context->SectionAlignment < FileAlignment)
		context->SectionAlignment = FileAlignment;

1145
	context->NumberOfSections = PEHdr->Pe32.FileHeader.NumberOfSections;
Matthew Garrett's avatar
Matthew Garrett committed
1146

1147
	if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < context->NumberOfRvaAndSizes) {
1148
		perror(L"Image header too small\n");
1149 1150 1151
		return EFI_UNSUPPORTED;
	}

1152
	HeaderWithoutDataDir = OptHeaderSize
1153
			- sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
1154 1155
	if (((UINT32)PEHdr->Pe32.FileHeader.SizeOfOptionalHeader - HeaderWithoutDataDir) !=
			context->NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY)) {
1156
		perror(L"Image header overflows data directory\n");
1157 1158 1159 1160 1161 1162
		return EFI_UNSUPPORTED;
	}

	SectionHeaderOffset = DosHdr->e_lfanew
				+ sizeof (UINT32)
				+ sizeof (EFI_IMAGE_FILE_HEADER)
1163 1164 1165
				+ PEHdr->Pe32.FileHeader.SizeOfOptionalHeader;
	if (((UINT32)context->ImageSize - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
			<= context->NumberOfSections) {
1166
		perror(L"Image sections overflow image size\n");
1167 1168 1169
		return EFI_UNSUPPORTED;
	}

1170 1171
	if ((context->SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
			< (UINT32)context->NumberOfSections) {
1172
		perror(L"Image sections overflow section headers\n");
1173 1174 1175
		return EFI_UNSUPPORTED;
	}

1176
	if ((((UINT8 *)PEHdr - (UINT8 *)data) + sizeof(EFI_IMAGE_OPTIONAL_HEADER_UNION)) > datasize) {
1177
		perror(L"Invalid image\n");
1178 1179 1180
		return EFI_UNSUPPORTED;
	}

Matthew Garrett's avatar
Matthew Garrett committed
1181
	if (PEHdr->Te.Signature != EFI_IMAGE_NT_SIGNATURE) {
1182
		perror(L"Unsupported image type\n");
Matthew Garrett's avatar
Matthew Garrett committed
1183 1184
		return EFI_UNSUPPORTED;
	}
Matthew Garrett's avatar
Matthew Garrett committed
1185

Matthew Garrett's avatar
Matthew Garrett committed
1186
	if (PEHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) {
1187
		perror(L"Unsupported image - Relocations have been stripped\n");
Matthew Garrett's avatar
Matthew Garrett committed
1188 1189
		return EFI_UNSUPPORTED;
	}
Matthew Garrett's avatar
Matthew Garrett committed
1190

Matthew Garrett's avatar
Matthew Garrett committed
1191
	context->PEHdr = PEHdr;
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

	if (image_is_64_bit(PEHdr)) {
		context->ImageAddress = PEHdr->Pe32Plus.OptionalHeader.ImageBase;
		context->EntryPoint = PEHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint;
		context->RelocDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
		context->SecDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
	} else {
		context->ImageAddress = PEHdr->Pe32.OptionalHeader.ImageBase;
		context->EntryPoint = PEHdr->Pe32.OptionalHeader.AddressOfEntryPoint;
		context->RelocDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
		context->SecDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
	}

1205
	context->FirstSection = (EFI_IMAGE_SECTION_HEADER *)((char *)PEHdr + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER));
Matthew Garrett's avatar
Matthew Garrett committed
1206

1207
	if (context->ImageSize < context->SizeOfHeaders) {
1208
		perror(L"Invalid image\n");
1209
		return EFI_UNSUPPORTED;
Matthew Garrett's avatar
Matthew Garrett committed
1210 1211
	}

1212 1213
	if ((unsigned long)((UINT8 *)context->SecDir - (UINT8 *)data) >
	    (datasize - sizeof(EFI_IMAGE_DATA_DIRECTORY))) {
1214
		perror(L"Invalid image\n");
1215 1216 1217
		return EFI_UNSUPPORTED;
	}

1218 1219 1220
	if (context->SecDir->VirtualAddress > datasize ||
	    (context->SecDir->VirtualAddress == datasize &&
	     context->SecDir->Size > 0)) {
1221
		perror(L"Malformed security header\n");
Matthew Garrett's avatar
Matthew Garrett committed
1222 1223 1224
		return EFI_INVALID_PARAMETER;
	}
	return EFI_SUCCESS;
Matthew Garrett's avatar
Matthew Garrett committed
1225 1226
}

Matthew Garrett's avatar
Matthew Garrett committed
1227 1228 1229
/*
 * Once the image has been loaded it needs to be validated and relocated
 */
1230
static EFI_STATUS handle_image (void *data, unsigned int datasize,
1231 1232 1233 1234
				EFI_LOADED_IMAGE *li,
				EFI_IMAGE_ENTRY_POINT *entry_point,
				EFI_PHYSICAL_ADDRESS *alloc_address,
				UINTN *alloc_pages)
Matthew Garrett's avatar
Matthew Garrett committed
1235 1236 1237
{
	EFI_STATUS efi_status;
	char *buffer;
1238
	int i;
Matthew Garrett's avatar
Matthew Garrett committed
1239
	EFI_IMAGE_SECTION_HEADER *Section;
1240
	char *base, *end;
Matthew Garrett's avatar
Matthew Garrett committed
1241
	PE_COFF_LOADER_IMAGE_CONTEXT context;
1242
	unsigned int alignment, alloc_size;
1243
	int found_entry_point = 0;
1244 1245
	UINT8 sha1hash[SHA1_DIGEST_SIZE];
	UINT8 sha256hash[SHA256_DIGEST_SIZE];
Matthew Garrett's avatar
Matthew Garrett committed
1246

Matthew Garrett's avatar
Matthew Garrett committed
1247 1248 1249
	/*
	 * The binary header contains relevant context and section pointers
	 */
1250
	efi_status = read_header(data, datasize, &context);
1251
	if (EFI_ERROR(efi_status)) {
1252
		perror(L"Failed to read header: %r\n", efi_status);
Matthew Garrett's avatar
Matthew Garrett committed
1253 1254 1255
		return efi_status;
	}

Matthew Garrett's avatar
Matthew Garrett committed
1256 1257 1258
	/*
	 * We only need to verify the binary if we're in secure mode
	 */