shim.c 70.8 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
#include <stdarg.h>

40 41 42 43 44 45 46 47
#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>
48 49
#include <openssl/x509.h>
#include <openssl/x509v3.h>
50
#include <openssl/rsa.h>
51
#include <internal/dso.h>
52 53

#include <Library/BaseCryptLib.h>
54

55
#include <stdint.h>
56 57

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

Matthew Garrett's avatar
Matthew Garrett committed
59
static EFI_SYSTEM_TABLE *systab;
60
static EFI_HANDLE global_image_handle;
Matthew Garrett's avatar
Matthew Garrett committed
61

62 63 64
static CHAR16 *second_stage;
static void *load_options;
static UINT32 load_options_size;
65

Matthew Garrett's avatar
Matthew Garrett committed
66 67 68
/*
 * The vendor certificate used for validating the second stage loader
 */
69 70 71 72 73 74 75 76 77 78 79
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
80

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

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

89
UINT8 user_insecure_mode;
90
UINT8 ignore_db;
91

92 93 94 95 96 97
typedef enum {
	DATA_FOUND,
	DATA_NOT_FOUND,
	VAR_NOT_FOUND
} CHECK_STATUS;

98 99 100 101 102
typedef struct {
	UINT32 MokSize;
	UINT8 *Mok;
} MokListNode;

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

112 113 114 115 116
	/* 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
117 118
	return image + address;
}
Matthew Garrett's avatar
Matthew Garrett committed
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 218 219
/* 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
220 221 222
/*
 * Perform the actual relocation
 */
Matthew Garrett's avatar
Matthew Garrett committed
223
static EFI_STATUS relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT *context,
224
				 EFI_IMAGE_SECTION_HEADER *Section,
225
				 void *orig, void *data)
Matthew Garrett's avatar
Matthew Garrett committed
226 227 228 229
{
	EFI_IMAGE_BASE_RELOCATION *RelocBase, *RelocBaseEnd;
	UINT64 Adjust;
	UINT16 *Reloc, *RelocEnd;
230
	char *Fixup, *FixupBase;
Matthew Garrett's avatar
Matthew Garrett committed
231 232 233 234
	UINT16 *Fixup16;
	UINT32 *Fixup32;
	UINT64 *Fixup64;
	int size = context->ImageSize;
235
	void *ImageEnd = (char *)orig + size;
236
	int n = 0;
Matthew Garrett's avatar
Matthew Garrett committed
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 269 270
	/* 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
271

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

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

279 280 281
	if (Adjust == 0)
		return EFI_SUCCESS;

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

285 286 287 288 289 290 291 292
		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);
293 294 295 296
			return EFI_UNSUPPORTED;
		}

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

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

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

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

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

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

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

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

	return EFI_SUCCESS;
}

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

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
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;
}

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 404 405 406 407 408
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);
	}

	return TRUE;
}

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
static void show_ca_warning()
{
	CHAR16 *text[9];

	text[0] = L"WARNING!";
	text[1] = L"";
	text[2] = L"The CA certificate used to verify this image doesn't   ";
	text[3] = L"contain the CA flag in Basic Constraints or KeyCertSign";
	text[4] = L"in KeyUsage. Such CA certificates will not be supported";
	text[5] = L"in the future.                                         ";
	text[6] = L"";
	text[7] = L"Please contact the issuer to update the certificate.   ";
	text[8] = NULL;

	console_reset();
	console_print_box(text, -1);
}

427 428 429
static CHECK_STATUS check_db_cert_in_ram(EFI_SIGNATURE_LIST *CertList,
					 UINTN dbsize,
					 WIN_CERTIFICATE_EFI_PKCS *data,
430 431
					 UINT8 *hash, CHAR16 *dbname,
					 EFI_GUID guid)
432 433
{
	EFI_SIGNATURE_DATA *Cert;
434
	UINTN CertSize;
435
	BOOLEAN IsFound = FALSE;
436 437

	while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
438
		if (CompareGuid (&CertList->SignatureType, &EFI_CERT_TYPE_X509_GUID) == 0) {
439
			Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
440 441
			CertSize = CertList->SignatureSize - sizeof(EFI_GUID);
			if (verify_x509(Cert->SignatureData, CertSize)) {
442
				if (verify_eku(Cert->SignatureData, CertSize)) {
443
					clear_ca_warning();
444 445 446 447 448
					IsFound = AuthenticodeVerify (data->CertData,
								      data->Hdr.dwLength - sizeof(data->Hdr),
								      Cert->SignatureData,
								      CertSize,
								      hash, SHA256_DIGEST_SIZE);
449
					if (IsFound) {
450 451 452
						if (get_ca_warning()) {
							show_ca_warning();
						}
453 454
						tpm_measure_variable(dbname, guid, CertSize, Cert->SignatureData);
						drain_openssl_errors();
455
						return DATA_FOUND;
456 457 458
					} else {
						LogError(L"AuthenticodeVerify(): %d\n", IsFound);
					}
459
				}
460 461
			} else if (verbose) {
				console_notify(L"Not a DER encoding x.509 Certificate");
462 463 464 465 466 467 468 469 470 471
			}
		}

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

	return DATA_NOT_FOUND;
}

472 473
static CHECK_STATUS check_db_cert(CHAR16 *dbname, EFI_GUID guid,
				  WIN_CERTIFICATE_EFI_PKCS *data, UINT8 *hash)
474
{
475
	CHECK_STATUS rc;
476 477 478
	EFI_STATUS efi_status;
	EFI_SIGNATURE_LIST *CertList;
	UINTN dbsize = 0;
479
	UINT8 *db;
480

481
	efi_status = get_variable(dbname, &db, &dbsize, guid);
482
	if (EFI_ERROR(efi_status))
483
		return VAR_NOT_FOUND;
484

485
	CertList = (EFI_SIGNATURE_LIST *)db;
486

487
	rc = check_db_cert_in_ram(CertList, dbsize, data, hash, dbname, guid);
488 489 490 491 492 493

	FreePool(db);

	return rc;
}

Matthew Garrett's avatar
Matthew Garrett committed
494 495 496
/*
 * Check a hash against an EFI_SIGNATURE_LIST in a buffer
 */
497 498
static CHECK_STATUS check_db_hash_in_ram(EFI_SIGNATURE_LIST *CertList,
					 UINTN dbsize, UINT8 *data,
499 500
					 int SignatureSize, EFI_GUID CertType,
					 CHAR16 *dbname, EFI_GUID guid)
501 502 503 504 505
{
	EFI_SIGNATURE_DATA *Cert;
	UINTN CertCount, Index;
	BOOLEAN IsFound = FALSE;

506
	while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
507
		CertCount = (CertList->SignatureListSize -sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
508
		Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
509
		if (CompareGuid(&CertList->SignatureType, &CertType) == 0) {
510
			for (Index = 0; Index < CertCount; Index++) {
511
				if (CompareMem (Cert->SignatureData, data, SignatureSize) == 0) {
512 513 514 515
					//
					// Find the signature in database.
					//
					IsFound = TRUE;
516
					tpm_measure_variable(dbname, guid, SignatureSize, data);
517 518 519 520 521 522 523 524 525 526
					break;
				}

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

527
		dbsize -= CertList->SignatureListSize;
528 529 530 531
		CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
	}

	if (IsFound)
532 533 534 535 536
		return DATA_FOUND;

	return DATA_NOT_FOUND;
}

Matthew Garrett's avatar
Matthew Garrett committed
537 538 539
/*
 * Check a hash against an EFI_SIGNATURE_LIST in a UEFI variable
 */
540 541 542 543 544 545
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;
546
	UINT8 *db;
547

548
	efi_status = get_variable(dbname, &db, &dbsize, guid);
549
	if (EFI_ERROR(efi_status)) {
550 551 552
		return VAR_NOT_FOUND;
	}

553
	CertList = (EFI_SIGNATURE_LIST *)db;
554 555

	CHECK_STATUS rc = check_db_hash_in_ram(CertList, dbsize, data,
556 557
					       SignatureSize, CertType,
					       dbname, guid);
558 559 560 561 562
	FreePool(db);
	return rc;

}

Matthew Garrett's avatar
Matthew Garrett committed
563 564 565 566
/*
 * Check whether the binary signature or hash are present in dbx or the
 * built-in blacklist
 */
Matthew Garrett's avatar
Matthew Garrett committed
567 568
static EFI_STATUS check_blacklist (WIN_CERTIFICATE_EFI_PKCS *cert,
				   UINT8 *sha256hash, UINT8 *sha1hash)
569
{
570
	EFI_SIGNATURE_LIST *dbx = (EFI_SIGNATURE_LIST *)vendor_dbx;
571

572
	if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha256hash,
573 574
			SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID, L"dbx",
			EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
575
		LogError(L"binary sha256hash found in vendor dbx\n");
576
		return EFI_SECURITY_VIOLATION;
577
	}
578
	if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha1hash,
579 580
				 SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID, L"dbx",
				 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
581
		LogError(L"binary sha1hash found in vendor dbx\n");
582
		return EFI_SECURITY_VIOLATION;
583
	}
584 585 586
	if (cert &&
	    check_db_cert_in_ram(dbx, vendor_dbx_size, cert, sha256hash, L"dbx",
				 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
587
		LogError(L"cert sha256hash found in vendor dbx\n");
588
		return EFI_SECURITY_VIOLATION;
589
	}
590 591
	if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
592
		LogError(L"binary sha256hash found in system dbx\n");
593
		return EFI_SECURITY_VIOLATION;
594
	}
595 596
	if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha1hash,
			  SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID) == DATA_FOUND) {
597
		LogError(L"binary sha1hash found in system dbx\n");
598
		return EFI_SECURITY_VIOLATION;
599
	}
600 601 602
	if (cert &&
	    check_db_cert(L"dbx", EFI_SECURE_BOOT_DB_GUID,
			  cert, sha256hash) == DATA_FOUND) {
603
		LogError(L"cert sha256hash found in system dbx\n");
604
		return EFI_SECURITY_VIOLATION;
605
	}
606 607
	if (check_db_hash(L"MokListX", SHIM_LOCK_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
608
		LogError(L"binary sha256hash found in Mok dbx\n");
609
		return EFI_SECURITY_VIOLATION;
610
	}
611 612 613
	if (cert &&
	    check_db_cert(L"MokListX", SHIM_LOCK_GUID,
			  cert, sha256hash) == DATA_FOUND) {
614
		LogError(L"cert sha256hash found in Mok dbx\n");
615
		return EFI_SECURITY_VIOLATION;
616
	}
617

618
	drain_openssl_errors();
619 620 621
	return EFI_SUCCESS;
}

622 623 624 625 626 627
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
628 629 630
/*
 * Check whether the binary signature or hash are present in db or MokList
 */
Matthew Garrett's avatar
Matthew Garrett committed
631 632
static EFI_STATUS check_whitelist (WIN_CERTIFICATE_EFI_PKCS *cert,
				   UINT8 *sha256hash, UINT8 *sha1hash)
633
{
634
	if (!ignore_db) {
635
		if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha256hash, SHA256_DIGEST_SIZE,
636 637 638
					EFI_CERT_SHA256_GUID) == DATA_FOUND) {
			update_verification_method(VERIFIED_BY_HASH);
			return EFI_SUCCESS;
639 640
		} else {
			LogError(L"check_db_hash(db, sha256hash) != DATA_FOUND\n");
641
		}
642
		if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha1hash, SHA1_DIGEST_SIZE,
643 644 645 646
					EFI_CERT_SHA1_GUID) == DATA_FOUND) {
			verification_method = VERIFIED_BY_HASH;
			update_verification_method(VERIFIED_BY_HASH);
			return EFI_SUCCESS;
647 648
		} else {
			LogError(L"check_db_hash(db, sha1hash) != DATA_FOUND\n");
649
		}
650
		if (cert && check_db_cert(L"db", EFI_SECURE_BOOT_DB_GUID, cert, sha256hash)
651
					== DATA_FOUND) {
652 653 654
			verification_method = VERIFIED_BY_CERT;
			update_verification_method(VERIFIED_BY_CERT);
			return EFI_SUCCESS;
655 656
		} else {
			LogError(L"check_db_cert(db, sha256hash) != DATA_FOUND\n");
657
		}
658
	}
659

660 661 662
	if (check_db_hash(L"MokList", SHIM_LOCK_GUID, sha256hash,
			  SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID)
				== DATA_FOUND) {
663 664
		verification_method = VERIFIED_BY_HASH;
		update_verification_method(VERIFIED_BY_HASH);
665
		return EFI_SUCCESS;
666 667
	} else {
		LogError(L"check_db_hash(MokList, sha256hash) != DATA_FOUND\n");
668
	}
669 670
	if (cert && check_db_cert(L"MokList", SHIM_LOCK_GUID, cert, sha256hash)
			== DATA_FOUND) {
671 672
		verification_method = VERIFIED_BY_CERT;
		update_verification_method(VERIFIED_BY_CERT);
673
		return EFI_SUCCESS;
674 675
	} else {
		LogError(L"check_db_cert(MokList, sha256hash) != DATA_FOUND\n");
676
	}
677

678
	update_verification_method(VERIFIED_BY_NOTHING);
679
	return EFI_SECURITY_VIOLATION;
680 681
}

682 683 684 685 686 687
/*
 * Check whether we're in Secure Boot and user mode
 */

static BOOLEAN secure_mode (void)
{
688
	static int first = 1;
689
	if (user_insecure_mode)
690 691
		return FALSE;

692
	if (variable_is_secureboot() != 1) {
693
		if (verbose && !in_protocol && first)
694
			console_notify(L"Secure boot not enabled");
695
		first = 0;
696 697
		return FALSE;
	}
698

699 700 701 702 703 704 705
	/* 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) {
706
		if (verbose && !in_protocol && first)
707
			console_notify(L"Platform is in setup mode");
708
		first = 0;
709 710 711
		return FALSE;
	}

712
	first = 0;
713 714 715
	return TRUE;
}

716 717 718
#define check_size_line(data, datasize_in, hashbase, hashsize, l) ({	\
	if ((unsigned long)hashbase >					\
			(unsigned long)data + datasize_in) {		\
719
		efi_status = EFI_INVALID_PARAMETER;			\
720 721 722 723 724 725
		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) {		\
726
		efi_status = EFI_INVALID_PARAMETER;			\
727 728 729 730 731 732 733
		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
734
/*
Matthew Garrett's avatar
Matthew Garrett committed
735
 * Calculate the SHA1 and SHA256 hashes of a binary
Matthew Garrett's avatar
Matthew Garrett committed
736
 */
Matthew Garrett's avatar
Matthew Garrett committed
737

738
static EFI_STATUS generate_hash (char *data, unsigned int datasize_in,
Matthew Garrett's avatar
Matthew Garrett committed
739 740 741
				 PE_COFF_LOADER_IMAGE_CONTEXT *context,
				 UINT8 *sha256hash, UINT8 *sha1hash)

Matthew Garrett's avatar
Matthew Garrett committed
742
{
Matthew Garrett's avatar
Matthew Garrett committed
743
	unsigned int sha256ctxsize, sha1ctxsize;
744
	unsigned int size = datasize_in;
Matthew Garrett's avatar
Matthew Garrett committed
745
	void *sha256ctx = NULL, *sha1ctx = NULL;
Matthew Garrett's avatar
Matthew Garrett committed
746 747 748
	char *hashbase;
	unsigned int hashsize;
	unsigned int SumOfBytesHashed, SumOfSectionBytes;
749
	unsigned int index, pos;
750
	unsigned int datasize;
Matthew Garrett's avatar
Matthew Garrett committed
751
	EFI_IMAGE_SECTION_HEADER  *Section;
Matthew Garrett's avatar
Matthew Garrett committed
752
	EFI_IMAGE_SECTION_HEADER  *SectionHeader = NULL;
753
	EFI_STATUS efi_status = EFI_SUCCESS;
754 755
	EFI_IMAGE_DOS_HEADER *DosHdr = (void *)data;
	unsigned int PEHdr_offset = 0;
Matthew Garrett's avatar
Matthew Garrett committed
756

757
	size = datasize = datasize_in;
758

759 760
	if (datasize <= sizeof (*DosHdr) ||
	    DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
761
		perror(L"Invalid signature\n");
762 763 764 765 766 767 768 769 770 771
		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
772
	if (!sha256ctx || !sha1ctx) {
773
		perror(L"Unable to allocate memory for hash context\n");
Matthew Garrett's avatar
Matthew Garrett committed
774 775 776
		return EFI_OUT_OF_RESOURCES;
	}

Matthew Garrett's avatar
Matthew Garrett committed
777
	if (!Sha256Init(sha256ctx) || !Sha1Init(sha1ctx)) {
778
		perror(L"Unable to initialise hash\n");
779
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
780 781 782 783
		goto done;
	}

	/* Hash start to checksum */
Matthew Garrett's avatar
Matthew Garrett committed
784
	hashbase = data;
Matthew Garrett's avatar
Matthew Garrett committed
785 786
	hashsize = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum -
		hashbase;
787
	check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
788

Matthew Garrett's avatar
Matthew Garrett committed
789 790
	if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
	    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
791
		perror(L"Unable to generate hash\n");
792
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
793 794 795 796 797 798 799
		goto done;
	}

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

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

	/* Hash end of certificate table to end of image header */
810 811 812 813 814
	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);
815
		efi_status = EFI_INVALID_PARAMETER;
816 817
		goto done;
	}
818
	check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
819

Matthew Garrett's avatar
Matthew Garrett committed
820 821
	if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
	    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
822
		perror(L"Unable to generate hash\n");
823
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
824 825 826
		goto done;
	}

Matthew Garrett's avatar
Matthew Garrett committed
827
	/* Sort sections */
828
	SumOfBytesHashed = context->SizeOfHeaders;
Matthew Garrett's avatar
Matthew Garrett committed
829

830
	/* Validate section locations and sizes */
831
	for (index = 0, SumOfSectionBytes = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
832 833 834 835
		EFI_IMAGE_SECTION_HEADER  *SectionPtr;

		/* Validate SectionPtr is within image */
		SectionPtr = ImageAddress(data, datasize,
836
			PEHdr_offset +
837 838 839 840 841
			sizeof (UINT32) +
			sizeof (EFI_IMAGE_FILE_HEADER) +
			context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader +
			(index * sizeof(*SectionPtr)));
		if (!SectionPtr) {
842
			perror(L"Malformed section %d\n", index);
843
			efi_status = EFI_INVALID_PARAMETER;
844 845 846 847 848
			goto done;
		}
		/* Validate section size is within image. */
		if (SectionPtr->SizeOfRawData >
		    datasize - SumOfBytesHashed - SumOfSectionBytes) {
849
			perror(L"Malformed section %d size\n", index);
850
			efi_status = EFI_INVALID_PARAMETER;
851 852 853
			goto done;
		}
		SumOfSectionBytes += SectionPtr->SizeOfRawData;
Matthew Garrett's avatar
Matthew Garrett committed
854 855 856 857
	}

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

863
	/* Already validated above */
864 865 866
	Section = ImageAddress(data, datasize,
		PEHdr_offset +
		sizeof (UINT32) +
867 868
		sizeof (EFI_IMAGE_FILE_HEADER) +
		context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader);
869 870 871 872 873 874 875 876 877 878 879 880 881
	/* 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;
	}
882

Matthew Garrett's avatar
Matthew Garrett committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	/* 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;
		}
900
		hashbase  = ImageAddress(data, size, Section->PointerToRawData);
Matthew Garrett's avatar
Matthew Garrett committed
901

Matthew Garrett's avatar
Matthew Garrett committed
902
		if (!hashbase) {
903
			perror(L"Malformed section header\n");
904
			efi_status = EFI_INVALID_PARAMETER;
905
			goto done;
Matthew Garrett's avatar
Matthew Garrett committed
906 907
		}

908 909 910
		/* Verify hashsize within image. */
		if (Section->SizeOfRawData >
		    datasize - Section->PointerToRawData) {
911
			perror(L"Malformed section raw size %d\n", index);
912
			efi_status = EFI_INVALID_PARAMETER;
913 914 915
			goto done;
		}
		hashsize  = (unsigned int) Section->SizeOfRawData;
916
		check_size(data, datasize_in, hashbase, hashsize);
917

Matthew Garrett's avatar
Matthew Garrett committed
918 919
		if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
		    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
920
			perror(L"Unable to generate hash\n");
921
			efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
922 923 924 925 926
			goto done;
		}
		SumOfBytesHashed += Section->SizeOfRawData;
	}

927 928
	/* 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
929
		hashbase = data + SumOfBytesHashed;
930
		hashsize = datasize - context->SecDir->Size - SumOfBytesHashed;
931 932 933 934

		if ((datasize - SumOfBytesHashed < context->SecDir->Size) ||
		    (SumOfBytesHashed + hashsize != context->SecDir->VirtualAddress)) {
			perror(L"Malformed binary after Attribute Certificate Table\n");
935 936 937 938 939
			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;
940 941
			goto done;
		}
942
		check_size(data, datasize_in, hashbase, hashsize);
Matthew Garrett's avatar
Matthew Garrett committed
943

Matthew Garrett's avatar
Matthew Garrett committed
944 945
		if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
		    !(Sha1Update(sha1ctx, hashbase, hashsize))) {
946
			perror(L"Unable to generate hash\n");
947
			efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
948 949
			goto done;
		}
950

951 952 953
#if 1
	}
#else // we have to migrate to doing this later :/
954
		SumOfBytesHashed += hashsize;
Matthew Garrett's avatar
Matthew Garrett committed
955 956
	}

957 958 959 960 961 962 963 964 965 966
	/* 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");
967
			efi_status = EFI_OUT_OF_RESOURCES;
968 969 970 971 972 973 974
			goto done;
		}

		SumOfBytesHashed += hashsize;
	}
#endif

Matthew Garrett's avatar
Matthew Garrett committed
975 976
	if (!(Sha256Final(sha256ctx, sha256hash)) ||
	    !(Sha1Final(sha1ctx, sha1hash))) {
977
		perror(L"Unable to finalise hash\n");
978
		efi_status = EFI_OUT_OF_RESOURCES;
Matthew Garrett's avatar
Matthew Garrett committed
979 980 981
		goto done;
	}

Matthew Garrett's avatar
Matthew Garrett committed
982 983 984 985 986 987 988 989
done:
	if (SectionHeader)
		FreePool(SectionHeader);
	if (sha1ctx)
		FreePool(sha1ctx);
	if (sha256ctx)
		FreePool(sha256ctx);

990
	return efi_status;
991 992
}

Matthew Garrett's avatar
Matthew Garrett committed
993 994 995 996
/*
 * Check that the signature is valid and matches the binary
 */
static EFI_STATUS verify_buffer (char *data, int datasize,
997 998
				 PE_COFF_LOADER_IMAGE_CONTEXT *context,
				 UINT8 *sha256hash, UINT8 *sha1hash)
Matthew Garrett's avatar
Matthew Garrett committed
999
{
1000
	EFI_STATUS efi_status = EFI_SECURITY_VIOLATION;
1001
	WIN_CERTIFICATE_EFI_PKCS *cert = NULL;
Matthew Garrett's avatar
Matthew Garrett committed
1002
	unsigned int size = datasize;
1003 1004 1005

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

1007
	if (context->SecDir->Size != 0) {
1008 1009 1010 1011 1012
		if (context->SecDir->Size >= size) {
			perror(L"Certificate Database size is too large\n");
			return EFI_INVALID_PARAMETER;
		}

1013 1014
		cert = ImageAddress (data, size,
				     context->SecDir->VirtualAddress);
1015

1016
		if (!cert) {
1017
			perror(L"Certificate located outside the image\n");
1018 1019
			return EFI_INVALID_PARAMETER;
		}
Matthew Garrett's avatar
Matthew Garrett committed
1020

1021 1022 1023 1024 1025
		if (cert->Hdr.dwLength > context->SecDir->Size) {
			perror(L"Certificate list size is inconsistent with PE headers");
			return EFI_INVALID_PARAMETER;
		}

1026 1027
		if (cert->Hdr.wCertificateType !=
		    WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1028
			perror(L"Unsupported certificate type %x\n",
1029 1030 1031
				cert->Hdr.wCertificateType);
			return EFI_UNSUPPORTED;
		}
Matthew Garrett's avatar
Matthew Garrett committed
1032 1033
	}

1034 1035 1036 1037 1038 1039 1040
	/*
	 * 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();

1041 1042 1043 1044
	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;
1045
	}
1046

Matthew Garrett's avatar
Matthew Garrett committed
1047 1048 1049
	/*
	 * Ensure that the binary isn't blacklisted
	 */
1050 1051
	efi_status = check_blacklist(cert, sha256hash, sha1hash);
	if (EFI_ERROR(efi_status)) {
1052
		perror(L"Binary is blacklisted\n");
1053 1054
		LogError(L"Binary is blacklisted: %r\n", efi_status);
		return efi_status;
1055 1056
	}

Matthew Garrett's avatar
Matthew Garrett committed
1057 1058 1059 1060
	/*
	 * Check whether the binary is whitelisted in any of the firmware
	 * databases
	 */
1061 1062 1063
	efi_status = check_whitelist(cert, sha256hash, sha1hash);
	if (EFI_ERROR(efi_status)) {
		LogError(L"check_whitelist(): %r\n", efi_status);
1064
	} else {
1065 1066
		drain_openssl_errors();
		return efi_status;
1067
	}
1068

1069
	if (cert) {
1070
#if defined(ENABLE_SHIM_CERT)
1071 1072 1073
		/*
		 * Check against the shim build key
		 */
1074
		clear_ca_warning();
1075 1076
		if (sizeof(shim_cert) &&
		    AuthenticodeVerify(cert->CertData,
1077
			       cert->Hdr.dwLength - sizeof(cert->Hdr),
1078 1079
			       shim_cert, sizeof(shim_cert), sha256hash,
			       SHA256_DIGEST_SIZE)) {
1080 1081 1082
			if (get_ca_warning()) {
				show_ca_warning();
			}
1083
			update_verification_method(VERIFIED_BY_CERT);
1084 1085 1086
			tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
					     sizeof(shim_cert), shim_cert);
			efi_status = EFI_SUCCESS;
1087
			drain_openssl_errors();
1088
			return efi_status;
1089 1090
		} else {
			LogError(L"AuthenticodeVerify(shim_cert) failed\n");
1091
		}
1092
#endif /* defined(ENABLE_SHIM_CERT) */
1093

1094 1095 1096
		/*
		 * And finally, check against shim's built-in key
		 */
1097
		clear_ca_warning();
1098 1099 1100 1101 1102
		if (vendor_cert_size &&
		    AuthenticodeVerify(cert->CertData,
				       cert->Hdr.dwLength - sizeof(cert->Hdr),
				       vendor_cert, vendor_cert_size,
				       sha256hash, SHA256_DIGEST_SIZE)) {
1103 1104 1105
			if (get_ca_warning()) {
				show_ca_warning();
			}
1106
			update_verification_method(VERIFIED_BY_CERT);
1107 1108 1109
			tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
					     vendor_cert_size, vendor_cert);
			efi_status = EFI_SUCCESS;
1110
			drain_openssl_errors();
1111
			return efi_status;
1112 1113
		} else {
			LogError(L"AuthenticodeVerify(vendor_cert) failed\n");
1114
		}
1115 1116
	}

1117 1118 1119
	LogError(L"Binary is not whitelisted\n");
	crypterr(EFI_SECURITY_VIOLATION);
	PrintErrors();
1120 1121
	efi_status = EFI_SECURITY_VIOLATION;
	return efi_status;
Matthew Garrett's avatar
Matthew Garrett committed
1122
}
Matthew Garrett's avatar
Matthew Garrett committed
1123

Matthew Garrett's avatar
Matthew Garrett committed
1124 1125 1126
/*
 * Read the binary header and grab appropriate information from it
 */
1127
static EFI_STATUS read_header(void *data, unsigned int datasize,
Matthew Garrett's avatar
Matthew Garrett committed
1128 1129
			      PE_COFF_LOADER_IMAGE_CONTEXT *context)
{
Matthew Garrett's avatar
Matthew Garrett committed
1130 1131
	EFI_IMAGE_DOS_HEADER *DosHdr = data;
	EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr = data;
1132
	unsigned long HeaderWithoutDataDir, SectionHeaderOffset, OptHeaderSize;
1133
	unsigned long FileAlignment = 0;
Matthew Garrett's avatar
Matthew Garrett committed
1134

1135
	if (datasize < sizeof (PEHdr->Pe32)) {
1136
		perror(L"Invalid image\n");
1137 1138 1139
		return EFI_UNSUPPORTED;
	}

Matthew Garrett's avatar
Matthew Garrett committed
1140
	if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE)
Matthew Garrett's avatar
Matthew Garrett committed
1141
		PEHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((char *)data + DosHdr->e_lfanew);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151

	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;
1152
		context->SectionAlignment = PEHdr->Pe32Plus.OptionalHeader.SectionAlignment;
1153
		FileAlignment = PEHdr->Pe32Plus.OptionalHeader.FileAlignment;
1154 1155 1156 1157 1158
		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;
1159
		context->SectionAlignment = PEHdr->Pe32.OptionalHeader.SectionAlignment;
1160
		FileAlignment = PEHdr->Pe32.OptionalHeader.FileAlignment;
1161 1162 1163
		OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER32);
	}

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
	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;

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

1177
	if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < context->NumberOfRvaAndSizes) {
1178
		perror(L"Image header too small\n");
1179 1180 1181
		return EFI_UNSUPPORTED;
	}

1182
	HeaderWithoutDataDir = OptHeaderSize
1183
			- sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
1184 1185
	if (((UINT32)PEHdr->Pe32.FileHeader.SizeOfOptionalHeader - HeaderWithoutDataDir) !=
			context->NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY)) {
1186
		perror(L"Image header overflows data directory\n");
1187 1188 1189 1190 1191 1192
		return EFI_UNSUPPORTED;
	}

	SectionHeaderOffset = DosHdr->e_lfanew
				+ sizeof (UINT32)
				+ sizeof (EFI_IMAGE_FILE_HEADER)
1193 1194 1195
				+ PEHdr->Pe32.FileHeader.SizeOfOptionalHeader;
	if (((UINT32)context->ImageSize - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
			<= context->NumberOfSections) {
1196
		perror(L"Image sections overflow image size\n");
1197 1198 1199
		return EFI_UNSUPPORTED;
	}

1200 1201
	if ((context->SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
			< (UINT32)context->NumberOfSections) {
1202
		perror(L"Image sections overflow section headers\n");
1203 1204 1205
		return EFI_UNSUPPORTED;
	}

1206
	if ((((UINT8 *)PEHdr - (UINT8 *)data) + sizeof(EFI_IMAGE_OPTIONAL_HEADER_UNION)) > datasize) {
1207
		perror(L"Invalid image\n");
1208 1209 1210
		return EFI_UNSUPPORTED;
	}

Matthew Garrett's avatar
Matthew Garrett committed
1211
	if (PEHdr->Te.Signature != EFI_IMAGE_NT_SIGNATURE) {
1212
		perror(L"Unsupported image type\n");
Matthew Garrett's avatar
Matthew Garrett committed
1213 1214
		return EFI_UNSUPPORTED;
	}
Matthew Garrett's avatar
Matthew Garrett committed
1215

Matthew Garrett's avatar
Matthew Garrett committed
1216
	if (PEHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) {
1217
		perror(L"Unsupported image - Relocations have been stripped\n");
Matthew Garrett's avatar
Matthew Garrett committed
1218 1219
		return EFI_UNSUPPORTED;
	}
Matthew Garrett's avatar
Matthew Garrett committed
1220

Matthew Garrett's avatar
Matthew Garrett committed
1221
	context->PEHdr = PEHdr;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

	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];
	}

1235
	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
1236

1237
	if (context->ImageSize < context->SizeOfHeaders) {
1238
		perror(L"Invalid image\n");
1239
		return EFI_UNSUPPORTED;
Matthew Garrett's avatar
Matthew Garrett committed
1240 1241
	}

1242 1243
	if ((unsigned long)((UINT8 *)context->SecDir - (UINT8 *)data) >
	    (datasize - sizeof(EFI_IMAGE_DATA_DIRECTORY))) {
1244
		perror(L"Invalid image\n");
1245 1246 1247
		return EFI_UNSUPPORTED;
	}

1248 1249 1250
	if (context->SecDir->VirtualAddress > datasize ||
	    (context->SecDir->VirtualAddress == datasize &&
	     context->SecDir->Size > 0)) {
1251
		perror(L"Malformed security header\n");
Matthew Garrett's avatar
Matthew Garrett committed
1252 1253 1254
		return EFI_INVALID_PARAMETER;
	}
	return EFI_SUCCESS;
Matthew Garrett's avatar
Matthew Garrett committed
1255 1256
}

Matthew Garrett's avatar
Matthew Garrett committed
1257 1258 1259
/*
 * Once the image has been loaded it needs to be validated and relocated
 */
1260
static EFI_STATUS handle_image (void *data, unsigned int datasize,
1261 1262 1263 1264
				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
1265 1266 1267
{
	EFI_STATUS efi_status;
	char *buffer;
1268
	int i;
Matthew Garrett's avatar
Matthew Garrett committed
1269
	EFI_IMAGE_SECTION_HEADER *Section;
1270
	char *base, *end;
Matthew Garrett's avatar
Matthew Garrett committed
1271
	PE_COFF_LOADER_IMAGE_CONTEXT context;
1272
	unsigned int alignment, alloc_size