Compare commits

..

8 Commits

Author SHA1 Message Date
242dcee217 UefiPayloadPkg: Disable EFI shell
Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
3f8a2a16b9 BmpSupportLib: fix BMP validation
BMP files by tools other than MS paint can have a
variable number of padding bytes, which results in
the DataSize being less than (ImageSize - HeaderSize).
Fix the check to be less stringent.

Test: use BMP created by/saved by Photoshop

Signed-off-by: Matt DeVillier <matt.devillier@gmail.com>
2024-06-06 12:22:41 -06:00
c24fa67677 MdeModulePkg: Center logo 38.2% from top of screen
Use Microsoft's recommended positioning for the boot logo.

> We recommend that the logo is placed with its center at 38.2% from the
> screen's top edge. This positioning is based on the golden ratio's
> visual aesthetics and matches the Windows 10 design proportions.

Ref: https://learn.microsoft.com/en-us/windows-hardware/drivers/bringup/boot-screen-components#position-the-logo-during-post
Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
cd00f3f47f MdeModulePkg/Logo: Use System76 boot logo
Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
b4f9a2237d UefiPayloadPkg: Show boot prompt as progress text
This causes it to be centered at the bottom of the screen like other
vendor's firmware instead of at the top left where the cursor is.

Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
9df51aa79f UefiPayloadPkg: Add lib for logging to System76 EC
Make use of the SMFI command interface to forward logs from edk2 to
System76 EC.

Signed-off-by: Jeremy Soller <jeremy@system76.com>
Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
013e5c94d6 BaseTools: Fix Python SyntaxWarning
- Windows paths must be escaped
- Regex should use raw strings

Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 12:22:41 -06:00
f04bd1e3b8 Remove GitHub integrations
Signed-off-by: Tim Crawford <tcrawford@system76.com>
2024-06-06 10:47:56 -06:00
136 changed files with 2120 additions and 9466 deletions

View File

@ -1,24 +0,0 @@
## @file
# GitHub issue configuration file.
#
# This file is meant to direct contributors familiar with GitHub's issue tracker
# to the external resources used by TianoCore.
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
blank_issues_enabled: false
contact_links:
- name: Bugs and Feature Requests
url: https://bugzilla.tianocore.org/
about: Submit bug reports and feature requests here
- name: Reporting Security Issues
url: https://github.com/tianocore/tianocore.github.io/wiki/Reporting-Security-Issues
about: Read the wiki page that describes the process here
- name: EDK II Development Mailing List
url: https://edk2.groups.io/g/devel
about: Submit code patches and ask questions on the mailing list (devel@edk2.groups.io)
- name: EDK II Discussions
url: https://github.com/tianocore/edk2/discussions
about: You can also reach out on the Discussion section of this repository

View File

@ -1,36 +0,0 @@
## @file
# Dependabot configuration file to enable GitHub services for managing and updating
# dependencies.
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
##
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix: "pip"
reviewers:
- "makubacki"
- "mdkinney"
- "spbrogan"
rebase-strategy: "disabled"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
commit-message:
prefix: "GitHub Action"
reviewers:
- "makubacki"
- "mdkinney"
- "spbrogan"
rebase-strategy: "disabled"

View File

@ -1,27 +0,0 @@
# Description
<_Include a description of the change and why this change was made._>
<_For each item, place an "x" in between `[` and `]` if true. Example: `[x]` (you can also check items in GitHub UI)_>
<_Create the PR as a Draft PR if it is only created to run CI checks._>
<_Delete lines in \<\> tags before creating the PR._>
- [ ] Breaking change?
- **Breaking change** - Will this cause a break in build or boot behavior?
- Examples: Add a new library class or move a module to a different repo.
- [ ] Impacts security?
- **Security** - Does the change have a direct security impact?
- Examples: Crypto algorithm change or buffer overflow fix.
- [ ] Includes tests?
- **Tests** - Does the change include any explicit test code?
- Examples: Unit tests or integration tests.
## How This Was Tested
<_Describe the test(s) that were run to verify the changes._>
## Integration Instructions
<_Describe how these changes should be integrated. Use N/A if nothing is required._>

View File

@ -1,361 +0,0 @@
# This workflow runs CodeQL against the repository.
#
# Results are uploaded to GitHub Code Scanning.
#
# Due to a known issue with the CodeQL extractor when building the edk2
# codebase on Linux systems, only Windows agents are used for build with
# the VS toolchain.
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
name: "CodeQL"
on:
push:
branches:
- master
pull_request:
branches:
- master
paths-ignore:
- '!**.c'
- '!**.h'
jobs:
analyze:
name: Analyze
runs-on: windows-2019
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
include:
- Package: "ArmPkg"
ArchList: "IA32,X64"
- Package: "CryptoPkg"
ArchList: "IA32"
- Package: "CryptoPkg"
ArchList: "X64"
- Package: "DynamicTablesPkg"
ArchList: "IA32,X64"
- Package: "FatPkg"
ArchList: "IA32,X64"
- Package: "FmpDevicePkg"
ArchList: "IA32,X64"
- Package: "IntelFsp2Pkg"
ArchList: "IA32,X64"
- Package: "IntelFsp2WrapperPkg"
ArchList: "IA32,X64"
- Package: "MdeModulePkg"
ArchList: "IA32"
- Package: "MdeModulePkg"
ArchList: "X64"
- Package: "MdePkg"
ArchList: "IA32,X64"
- Package: "PcAtChipsetPkg"
ArchList: "IA32,X64"
- Package: "PrmPkg"
ArchList: "IA32,X64"
- Package: "SecurityPkg"
ArchList: "IA32,X64"
- Package: "ShellPkg"
ArchList: "IA32,X64"
- Package: "SourceLevelDebugPkg"
ArchList: "IA32,X64"
- Package: "StandaloneMmPkg"
ArchList: "IA32,X64"
- Package: "UefiCpuPkg"
ArchList: "IA32,X64"
- Package: "UnitTestFrameworkPkg"
ArchList: "IA32,X64"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
cache-dependency-path: 'pip-requirements.txt'
- name: Use Git Long Paths on Windows
if: runner.os == 'Windows'
shell: pwsh
run: |
git config --system core.longpaths true
- name: Install/Upgrade pip Modules
run: pip install -r pip-requirements.txt --upgrade requests sarif-tools
- name: Determine CI Settings File Supported Operations
id: get_ci_file_operations
shell: python
run: |
import importlib
import os
import sys
from pathlib import Path
from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager
from edk2toolext.invocables.edk2_setup import SetupSettingsManager
# Find the repo CI Settings file
ci_settings_file = list(Path(os.environ['GITHUB_WORKSPACE']).rglob('.pytool/CISettings.py'))
# Note: At this point, submodules have not been pulled, only one CI Settings file should exist
if len(ci_settings_file) != 1 or not ci_settings_file[0].is_file():
print("::error title=Workspace Error!::Failed to find CI Settings file!")
sys.exit(1)
ci_settings_file = ci_settings_file[0]
# Try Finding the Settings class in the file
module_name = 'ci_settings'
spec = importlib.util.spec_from_file_location(module_name, ci_settings_file)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
try:
settings = getattr(module, 'Settings')
except AttributeError:
print("::error title=Workspace Error!::Failed to find Settings class in CI Settings file!")
sys.exit(1)
# Determine Which Operations Are Supported by the Settings Class
ci_setup_supported = issubclass(settings, CiSetupSettingsManager)
setup_supported = issubclass(settings, SetupSettingsManager)
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f'ci_setup_supported={str(ci_setup_supported).lower()}', file=fh)
print(f'setup_supported={str(setup_supported).lower()}', file=fh)
- name: Convert Arch to Log Format
id: convert_arch_hyphen
env:
ARCH_LIST: ${{ matrix.ArchList }}
shell: python
run: |
import os
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f'arch_list={os.environ["ARCH_LIST"].replace(",", "-")}', file=fh)
- name: Setup
if: steps.get_ci_file_operations.outputs.setup_supported == 'true'
run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019
- name: Upload Setup Log As An Artifact
uses: actions/upload-artifact@v4
if: (success() || failure()) && steps.get_ci_file_operations.outputs.setup_supported == 'true'
with:
name: ${{ matrix.Package }}-${{ steps.convert_arch_hyphen.outputs.arch_list }}-Setup-Log
path: |
**/SETUPLOG.txt
retention-days: 7
if-no-files-found: ignore
- name: CI Setup
if: steps.get_ci_file_operations.outputs.ci_setup_supported == 'true'
run: stuart_ci_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019
- name: Upload CI Setup Log As An Artifact
uses: actions/upload-artifact@v4
if: (success() || failure()) && steps.get_ci_file_operations.outputs.ci_setup_supported == 'true'
with:
name: ${{ matrix.Package }}-${{ steps.convert_arch_hyphen.outputs.arch_list }}-CI-Setup-Log
path: |
**/CISETUP.txt
retention-days: 7
if-no-files-found: ignore
- name: Update
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019
- name: Upload Update Log As An Artifact
uses: actions/upload-artifact@v4
if: success() || failure()
with:
name: ${{ matrix.Package }}-${{ steps.convert_arch_hyphen.outputs.arch_list }}-Update-Log
path: |
**/UPDATE_LOG.txt
retention-days: 7
if-no-files-found: ignore
- name: Build Tools From Source
run: python BaseTools/Edk2ToolsBuild.py -t VS2019
- name: Find CodeQL Plugin Directory
id: find_dir
shell: python
run: |
import os
import sys
from pathlib import Path
# Find the plugin directory that contains the CodeQL plugin
plugin_dir = list(Path(os.environ['GITHUB_WORKSPACE']).rglob('BaseTools/Plugin/CodeQL'))
# This should only be found once
if len(plugin_dir) == 1:
plugin_dir = str(plugin_dir[0])
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f'codeql_plugin_dir={plugin_dir}', file=fh)
else:
print("::error title=Workspace Error!::Failed to find CodeQL plugin directory!")
sys.exit(1)
- name: Get CodeQL CLI Cache Data
id: cache_key_gen
env:
CODEQL_PLUGIN_DIR: ${{ steps.find_dir.outputs.codeql_plugin_dir }}
shell: python
run: |
import os
import yaml
codeql_cli_ext_dep_name = 'codeqlcli_windows_ext_dep'
codeql_plugin_file = os.path.join(os.environ['CODEQL_PLUGIN_DIR'], codeql_cli_ext_dep_name + '.yaml')
with open (codeql_plugin_file) as pf:
codeql_cli_ext_dep = yaml.safe_load(pf)
cache_key_name = codeql_cli_ext_dep['name']
cache_key_version = codeql_cli_ext_dep['version']
cache_key = f'{cache_key_name}-{cache_key_version}'
codeql_plugin_cli_ext_dep_dir = os.path.join(os.environ['CODEQL_PLUGIN_DIR'], codeql_cli_ext_dep['name'].strip() + '_extdep')
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f'codeql_cli_cache_key={cache_key}', file=fh)
print(f'codeql_cli_ext_dep_dir={codeql_plugin_cli_ext_dep_dir}', file=fh)
- name: Attempt to Load CodeQL CLI From Cache
id: codeqlcli_cache
uses: actions/cache@v4
with:
path: ${{ steps.cache_key_gen.outputs.codeql_cli_ext_dep_dir }}
key: ${{ steps.cache_key_gen.outputs.codeql_cli_cache_key }}
- name: Download CodeQL CLI
if: steps.codeqlcli_cache.outputs.cache-hit != 'true'
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019 --codeql
- name: Remove CI Plugins Irrelevant to CodeQL
shell: python
env:
CODEQL_PLUGIN_DIR: ${{ steps.find_dir.outputs.codeql_plugin_dir }}
run: |
import os
import shutil
from pathlib import Path
# Only these two plugins are needed for CodeQL
plugins_to_keep = ['CompilerPlugin']
plugin_dir = Path('.pytool/Plugin').absolute()
if plugin_dir.is_dir():
for dir in plugin_dir.iterdir():
if str(dir.stem) not in plugins_to_keep:
shutil.rmtree(str(dir.absolute()), ignore_errors=True)
- name: CI Build
env:
STUART_CODEQL_PATH: ${{ steps.cache_key_gen.outputs.codeql_cli_ext_dep_dir }}
run: stuart_ci_build -c .pytool/CISettings.py -t DEBUG -p ${{ matrix.Package }} -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019 --codeql
- name: Build Cleanup
id: build_cleanup
shell: python
run: |
import os
import shutil
from pathlib import Path
dirs_to_delete = ['ia32', 'x64', 'arm', 'aarch64']
def delete_dirs(path: Path):
if path.exists() and path.is_dir():
if path.name.lower() in dirs_to_delete:
print(f'Removed {str(path)}')
shutil.rmtree(path)
return
for child_dir in path.iterdir():
delete_dirs(child_dir)
build_path = Path(os.environ['GITHUB_WORKSPACE'], 'Build')
delete_dirs(build_path)
- name: Upload Build Logs As An Artifact
uses: actions/upload-artifact@v4
if: success() || failure()
with:
name: ${{ matrix.Package }}-${{ steps.convert_arch_hyphen.outputs.arch_list }}-Build-Logs
path: |
**/BUILD_REPORT.TXT
**/OVERRIDELOG.TXT
**/BUILDLOG_*.md
**/BUILDLOG_*.txt
**/CI_*.md
**/CI_*.txt
retention-days: 7
if-no-files-found: ignore
- name: Prepare Env Data for CodeQL Upload
id: env_data
env:
PACKAGE_NAME: ${{ matrix.Package }}
shell: python
run: |
import logging
import os
from edk2toollib.utility_functions import RunCmd
from io import StringIO
from pathlib import Path
package = os.environ['PACKAGE_NAME'].strip().lower()
directory_name = 'codeql-analysis-' + package + '-debug'
file_name = 'codeql-db-' + package + '-debug-0.sarif'
sarif_path = Path('Build', directory_name, file_name)
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
if sarif_path.is_file():
emacs_file_path = sarif_path.with_name(sarif_path.stem + "-emacs.txt")
out_stream_buffer = StringIO()
exit_code = RunCmd("sarif", f"emacs {sarif_path} --output {emacs_file_path} --no-autotrim",
outstream=out_stream_buffer,
logging_level=logging.NOTSET)
print(f'upload_sarif_file=true', file=fh)
print(f'emacs_file_path={emacs_file_path}', file=fh)
print(f'sarif_file_path={sarif_path}', file=fh)
else:
print(f'upload_sarif_file=false', file=fh)
- name: Upload CodeQL Results (SARIF) As An Artifact
uses: actions/upload-artifact@v4
if: steps.env_data.outputs.upload_sarif_file == 'true'
with:
name: ${{ matrix.Package }}-${{ steps.convert_arch_hyphen.outputs.arch_list }}-CodeQL-SARIF
path: |
${{ steps.env_data.outputs.emacs_file_path }}
${{ steps.env_data.outputs.sarif_file_path }}
retention-days: 14
if-no-files-found: warn
- name: Upload CodeQL Results (SARIF) To GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
if: steps.env_data.outputs.upload_sarif_file == 'true'
with:
# Path to SARIF file relative to the root of the repository.
sarif_file: ${{ steps.env_data.outputs.sarif_file_path }}
# Optional category for the results. Used to differentiate multiple results for one commit.
# Each package is a separate category.
category: ${{ matrix.Package }}

View File

@ -1,36 +0,0 @@
# This workflow automatically applies labels to pull requests based on regular expression matches against the content
# in the pull request.
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
# For more information, see:
# https://github.com/github/issue-labeler
name: Apply Labels Based on Message Content
on:
pull_request_target:
types:
- edited
- opened
- reopened
- synchronize
workflow_dispatch:
jobs:
sync:
name: Label PR from Description
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Apply Labels Based on PR Description
uses: github/issue-labeler@v3.1
with:
configuration-path: .github/workflows/pr-labeler/regex.yml
enable-versioned-regex: 0
repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,16 +0,0 @@
# Specifies labels to apply to pull requests based on regular expressions.
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
# For more information, see:
# https://github.com/github/issue-labeler
impact:breaking-change:
- '\s*-\s*\[\s*[x|X]\s*\] Breaking change\?'
impact:security:
- '\s*-\s*\[\s*[x|X]\s*\] Impacts security\?'
impact:testing:
- '\s*-\s*\[\s*[x|X]\s*\] Includes tests\?'

View File

@ -1,44 +0,0 @@
# This workflow warns and then closes issues and PRs that have had no activity
# for a specified amount of time.
#
# For more information, see:
# https://github.com/actions/stale
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
name: Stale Check
on:
schedule:
# At 23:35 on every day-of-week from Sunday through Saturday
# https://crontab.guru/#35_23_*_*_0-6
- cron: '35 23 * * 0-6'
workflow_dispatch:
jobs:
stale:
name: Stale
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- name: Check for Stale Items
uses: actions/stale@v8
with:
days-before-issue-close: -1
days-before-issue-stale: -1
days-before-pr-stale: 60
days-before-pr-close: 7
stale-pr-message: >
This PR has been automatically marked as stale because it has not had
activity in 60 days. It will be closed if no further activity occurs within
7 days. Thank you for your contributions.
close-pr-message: >
This pull request has been automatically been closed because it did not have any
activity in 60 days and no follow up within 7 days after being marked stale.
Thank you for your contributions.
stale-pr-label: stale

View File

@ -78,6 +78,7 @@
gArmTokenSpaceGuid.PcdBaseBoardManufacturer
gArmTokenSpaceGuid.PcdBaseBoardProductName
gArmTokenSpaceGuid.PcdBaseBoardVersion
gArmTokenSpaceGuid.PcdFdBaseAddress
[Guids]
gEfiGenericVariableGuid

View File

@ -253,7 +253,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBiosVendor) {
(VOID)CopyMem (SmbiosRecord, InputData, sizeof (SMBIOS_TABLE_TYPE0));
SmbiosRecord->Hdr.Length = sizeof (SMBIOS_TABLE_TYPE0);
SmbiosRecord->BiosSegment = 0;
SmbiosRecord->BiosSegment = (UINT16)(FixedPcdGet32 (PcdFdBaseAddress) / SIZE_64KB);
if (BiosPhysicalSize < SIZE_16MB) {
SmbiosRecord->BiosSize = Base2ToByteWith64KUnit (BiosPhysicalSize) - 1;
} else {

View File

@ -66,7 +66,7 @@
QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf
TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
VirtNorFlashPlatformLib|OvmfPkg/Library/FdtNorFlashQemuLib/FdtNorFlashQemuLib.inf
VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf
CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf
@ -152,9 +152,6 @@
gArmTokenSpaceGuid.PcdVFPEnabled|1
!endif
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress|0x00000000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize|$(FD_SIZE)
gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase|0x4007c000
gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize|0x4000
gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
@ -234,10 +231,6 @@
# System Memory Size -- 128 MB initially, actual size will be fetched from DT
gArmTokenSpaceGuid.PcdSystemMemorySize|0x8000000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize | 0x40000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize | 0x40000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize | 0x40000
[PcdsFixedAtBuild.AARCH64]
# Clearing BIT0 in this PCD prevents installing a 32-bit SMBIOS entry point,
# if the entry point version is >= 3.0. AARCH64 OSes cannot assume the
@ -250,13 +243,6 @@
[PcdsDynamicDefault.common]
gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|3
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 | 0
## If TRUE, OvmfPkg/AcpiPlatformDxe will not wait for PCI
# enumeration to complete before installing ACPI tables.
gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE
@ -418,10 +404,7 @@
MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
!endif
MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf {
<LibraryClasses>
NULL|EmbeddedPkg/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf
}
MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf {

View File

@ -65,7 +65,7 @@
ArmVirtMemInfoLib|ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf
TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
VirtNorFlashPlatformLib|OvmfPkg/Library/FdtNorFlashQemuLib/FdtNorFlashQemuLib.inf
VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf
CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf
@ -120,8 +120,6 @@
gArmTokenSpaceGuid.PcdVFPEnabled|1
!endif
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress|0x00000000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize|$(FD_SIZE)
gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize|0x4000
gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
@ -183,10 +181,6 @@
gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|3
gEfiShellPkgTokenSpaceGuid.PcdShellFileOperationSize|0x20000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize | 0x40000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize | 0x40000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize | 0x40000
[PcdsPatchableInModule.common]
# we need to provide a resolution for this PCD that supports PcdSet64()
# being called from ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c,
@ -214,13 +208,6 @@
[PcdsDynamicDefault.common]
gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|3
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase | 0
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 | 0
## If TRUE, OvmfPkg/AcpiPlatformDxe will not wait for PCI
# enumeration to complete before installing ACPI tables.
gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE
@ -326,10 +313,7 @@
MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
!endif
MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf {
<LibraryClasses>
NULL|EmbeddedPkg/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf
}
MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf {

View File

@ -1,11 +1,10 @@
/** @file
Copyright (c) 2014-2018, Linaro Ltd. All rights reserved.<BR>
Copyright (c) 2024 Loongson Technology Corporation Limited. All rights reserved.<BR>
Copyright (c) 2014-2018, Linaro Ltd. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
**/
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
@ -13,12 +12,10 @@
#include <Library/VirtNorFlashPlatformLib.h>
#include <Protocol/FdtClient.h>
#include <stdbool.h>
#define QEMU_NOR_BLOCK_SIZE SIZE_256KB
#define MAX_FLASH_BANKS 4
STATIC VIRT_NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_BANKS];
#define MAX_FLASH_BANKS 4
EFI_STATUS
VirtNorFlashPlatformInitialization (
@ -28,6 +25,8 @@ VirtNorFlashPlatformInitialization (
return EFI_SUCCESS;
}
STATIC VIRT_NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_BANKS];
EFI_STATUS
VirtNorFlashPlatformGetDevices (
OUT VIRT_NOR_FLASH_DESCRIPTION **NorFlashDescriptions,
@ -43,7 +42,6 @@ VirtNorFlashPlatformGetDevices (
UINT32 Num;
UINT64 Base;
UINT64 Size;
BOOLEAN Found;
Status = gBS->LocateProtocol (
&gFdtClientProtocolGuid,
@ -52,8 +50,7 @@ VirtNorFlashPlatformGetDevices (
);
ASSERT_EFI_ERROR (Status);
Num = 0;
Found = FALSE;
Num = 0;
for (FindNodeStatus = FdtClient->FindCompatibleNode (
FdtClient,
"cfi-flash",
@ -97,8 +94,8 @@ VirtNorFlashPlatformGetDevices (
// Disregard any flash devices that overlap with the primary FV.
// The firmware is not updatable from inside the guest anyway.
//
if ((PcdGet32 (PcdOvmfFdBaseAddress) + PcdGet32 (PcdOvmfFirmwareFdSize) > Base) &&
((Base + Size) > PcdGet32 (PcdOvmfFdBaseAddress)))
if ((PcdGet64 (PcdFvBaseAddress) + PcdGet32 (PcdFvSize) > Base) &&
((Base + Size) > PcdGet64 (PcdFvBaseAddress)))
{
continue;
}
@ -108,32 +105,6 @@ VirtNorFlashPlatformGetDevices (
mNorFlashDevices[Num].Size = (UINTN)Size;
mNorFlashDevices[Num].BlockSize = QEMU_NOR_BLOCK_SIZE;
Num++;
if (!Found) {
//
// By default, the second available flash is stored as a non-volatile variable.
//
Status = PcdSet32S (PcdFlashNvStorageVariableBase, Base);
ASSERT_EFI_ERROR (Status);
//
// The Base is the value of PcdFlashNvStorageVariableBase,
// PcdFlashNvStorageFtwWorkingBase can be got by
// PcdFlashNvStorageVariableBase + PcdFlashNvStorageVariableSize
//
Base += PcdGet32 (PcdFlashNvStorageVariableSize);
Status = PcdSet32S (PcdFlashNvStorageFtwWorkingBase, Base);
ASSERT_EFI_ERROR (Status);
//
// Now, the Base is the value of PcdFlashNvStorageFtwWorkingBase,
// PcdFlashNvStorageFtwSpareBase can be got by
// PcdFlashNvStorageFtwWorkingBase + PcdFlashNvStorageFtwWorkingSize.
//
Base += PcdGet32 (PcdFlashNvStorageFtwWorkingSize);
Status = PcdSet32S (PcdFlashNvStorageFtwSpareBase, Base);
ASSERT_EFI_ERROR (Status);
Found = TRUE;
}
}
//

View File

@ -0,0 +1,42 @@
#/** @file
#
# Component description file for NorFlashQemuLib module
#
# Copyright (c) 2014, Linaro Ltd. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
#**/
[Defines]
INF_VERSION = 0x00010005
BASE_NAME = NorFlashQemuLib
FILE_GUID = 339B7829-4C5F-4EFC-B2DD-5050E530DECE
MODULE_TYPE = DXE_DRIVER
VERSION_STRING = 1.0
LIBRARY_CLASS = VirtNorFlashPlatformLib
[Sources.common]
NorFlashQemuLib.c
[Packages]
MdePkg/MdePkg.dec
ArmPkg/ArmPkg.dec
ArmVirtPkg/ArmVirtPkg.dec
EmbeddedPkg/EmbeddedPkg.dec
OvmfPkg/OvmfPkg.dec
[LibraryClasses]
BaseLib
DebugLib
UefiBootServicesTableLib
[Protocols]
gFdtClientProtocolGuid ## CONSUMES
[Depex]
gFdtClientProtocolGuid
[Pcd]
gArmTokenSpaceGuid.PcdFvBaseAddress
gArmTokenSpaceGuid.PcdFvSize

View File

@ -10,7 +10,7 @@
##
[FD.QEMU_VARS]
BaseAddress = 0x00000000
BaseAddress = 0x04000000
Size = 0xc0000
ErasePolarity = 1
BlockSize = 0x40000
@ -18,6 +18,7 @@ NumBlocks = 3
0x00000000|0x00040000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
#NV_VARIABLE_STORE
DATA = {
## This is the EFI_FIRMWARE_VOLUME_HEADER
@ -56,6 +57,7 @@ DATA = {
0x00040000|0x00040000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
#NV_FTW_WORKING
DATA = {
# EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER->Signature = gEdkiiWorkingBlockSignatureGuid =
@ -69,4 +71,5 @@ DATA = {
}
0x00080000|0x00040000
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
#NV_FTW_SPARE

View File

@ -34,7 +34,7 @@
import re
_double_star_after_invalid_regex = re.compile(r'[^/\\]\*\*')
_double_star_first_before_invalid_regex = re.compile('^\\*\\*[^/]')
_double_star_first_before_invalid_regex = re.compile(r'^\\*\\*[^/]')
_double_star_middle_before_invalid_regex = re.compile(r'[^\\]\*\*[^/]')

View File

@ -89,12 +89,12 @@ class parser_lst(object):
return structs_file
def struct(self):#struct:{offset:name}
unit_num = re.compile('(\d+)')
offset1_re = re.compile('(\d+)\[')
pcdname_num_re = re.compile('\w+\[(\S+)\]')
pcdname_re = re.compile('\](.*)\<')
pcdname2_re = re.compile('(\w+)\[')
uint_re = re.compile('\<(\S+)\>')
unit_num = re.compile(r'(\d+)')
offset1_re = re.compile(r'(\d+)\[')
pcdname_num_re = re.compile(r'\w+\[(\S+)\]')
pcdname_re = re.compile(r'\](.*)\<')
pcdname2_re = re.compile(r'(\w+)\[')
uint_re = re.compile(r'\<(\S+)\>')
name_format = re.compile(r'(?<!typedef)\s+struct (\w+) {.*?;', re.S)
name=name_format.findall(self.text)
info={}
@ -214,8 +214,8 @@ class Config(object):
#Parser .config file,return list[offset,name,guid,value,help]
def config_parser(self):
ids_re =re.compile('_ID:(\d+)',re.S)
id_re= re.compile('\s+')
ids_re =re.compile(r'_ID:(\d+)',re.S)
id_re= re.compile(r'\s+')
info = []
info_dict={}
with open(self.config, 'r') as text:
@ -435,7 +435,7 @@ class PATH(object):
def header(self,struct):
header={}
head_re = re.compile('typedef.*} %s;[\n]+(.*)(?:typedef|formset)'%struct,re.M|re.S)
head_re = re.compile(r'typedef.*} %s;[\n]+(.*)(?:typedef|formset)'%struct,re.M|re.S)
head_re2 = re.compile(r'#line[\s\d]+"(\S+h)"')
for i in list(self.lstinf.keys()):
with open(i,'r') as lst:

View File

@ -528,7 +528,7 @@ class EfiSectionHeader(BinaryItem):
rMapEntry = re.compile('^(\w+)[ \(\w\)]* \(BaseAddress=([0-9a-fA-F]+), EntryPoint=([0-9a-fA-F]+), GUID=([0-9a-fA-F\-]+)')
rMapEntry = re.compile(r'^(\w+)[ \(\w\)]* \(BaseAddress=([0-9a-fA-F]+), EntryPoint=([0-9a-fA-F]+), GUID=([0-9a-fA-F\-]+)')
class EfiFvMapFile(object):
def __init__(self):
self._mapentries = {}

View File

@ -234,8 +234,10 @@ class CommitMessageCheck:
def check_misc_signatures(self):
for sigtype in self.sig_types:
sigs = self.find_signatures(sigtype)
if sigtype == 'Cc' and len(sigs) == 0:
self.error('No Cc: tags for maintainers/reviewers found!')
cve_re = re.compile('CVE-[0-9]{4}-[0-9]{5}[^0-9]')
cve_re = re.compile(r'CVE-[0-9]{4}-[0-9]{5}[^0-9]')
def check_overall_format(self):
lines = self.msg.splitlines()

View File

@ -54,7 +54,7 @@ gHexPattern = re.compile(r'0[xX]{}+'.format(_HexChar))
gHexPatternAll = re.compile(r'0[xX]{}+$'.format(_HexChar))
## Regular expressions for string identifier checking
gIdentifierPattern = re.compile('^[a-zA-Z][a-zA-Z0-9_]*$', re.UNICODE)
gIdentifierPattern = re.compile(r'^[a-zA-Z][a-zA-Z0-9_]*$', re.UNICODE)
## Regular expression for GUID c structure format
_GuidCFormatPattern = r"{{\s*0[xX]{Hex}{{1,8}}\s*,\s*0[xX]{Hex}{{1,4}}\s*,\s*0[xX]{Hex}{{1,4}}" \
r"\s*,\s*{{\s*0[xX]{Hex}{{1,2}}\s*,\s*0[xX]{Hex}{{1,2}}" \

View File

@ -1926,4 +1926,4 @@ def CopyDict(ori_dict):
# Remove the c/c++ comments: // and /* */
#
def RemoveCComments(ctext):
return re.sub('//.*?\n|/\\*.*?\\*/', '\n', ctext, flags=re.S)
return re.sub(r'//.*?\n|/\\*.*?\\*/', '\n', ctext, flags=re.S)

View File

@ -21,7 +21,7 @@ from CommonDataClass.Exceptions import *
from Common.LongFilePathSupport import OpenLongFilePath as open
from Common.MultipleWorkspace import MultipleWorkspace as mws
gHexVerPatt = re.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re.IGNORECASE)
gHexVerPatt = re.compile(r'0x[a-f0-9]{4}[a-f0-9]{4}$', re.IGNORECASE)
gHumanReadableVerPatt = re.compile(r'([1-9][0-9]*|0)\.[0-9]{1,2}$')
## GetSplitValueList

View File

@ -1112,7 +1112,7 @@ class Check(object):
RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
for Record in RecordSet:
Path = Record[1]
Path = Path.upper().replace('\X64', '').replace('\IA32', '').replace('\EBC', '').replace('\IPF', '').replace('\ARM', '')
Path = Path.upper().replace('\\X64', '').replace('\\IA32', '').replace('\\EBC', '').replace('\\IPF', '').replace('\\ARM', '')
if Path in InfPathList:
if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, Record[2]):
EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, OtherMsg="The source file [%s] is existing in module directory but it is not described in INF file." % (Record[2]), BelongsToTable='File', BelongsToItem=Record[0])

View File

@ -435,7 +435,7 @@ class Configuration(object):
# test that our dict and out class still match in contents.
#
if __name__ == '__main__':
myconfig = Configuration("BaseTools\Source\Python\Ecc\config.ini")
myconfig = Configuration("BaseTools\\Source\\Python\\Ecc\\config.ini")
for each in myconfig.__dict__:
if each == "Filename":
continue

View File

@ -1841,14 +1841,14 @@ class DecParser(MetaFileParser):
if EccGlobalData.gConfig.UniCheckPCDInfo == '1' or EccGlobalData.gConfig.UniCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
# check Description, Prompt information
PatternDesc = re.compile('##\s*([\x21-\x7E\s]*)', re.S)
PatternPrompt = re.compile('#\s+@Prompt\s+([\x21-\x7E\s]*)', re.S)
PatternDesc = re.compile(r'##\s*([\x21-\x7E\s]*)', re.S)
PatternPrompt = re.compile(r'#\s+@Prompt\s+([\x21-\x7E\s]*)', re.S)
Description = None
Prompt = None
# check @ValidRange, @ValidList and @Expression format valid
ErrorCodeValid = '0x0 <= %s <= 0xFFFFFFFF'
PatternValidRangeIn = '(NOT)?\s*(\d+\s*-\s*\d+|0[xX][a-fA-F0-9]+\s*-\s*0[xX][a-fA-F0-9]+|LT\s*\d+|LT\s*0[xX][a-fA-F0-9]+|GT\s*\d+|GT\s*0[xX][a-fA-F0-9]+|LE\s*\d+|LE\s*0[xX][a-fA-F0-9]+|GE\s*\d+|GE\s*0[xX][a-fA-F0-9]+|XOR\s*\d+|XOR\s*0[xX][a-fA-F0-9]+|EQ\s*\d+|EQ\s*0[xX][a-fA-F0-9]+)'
PatternValidRng = re.compile('^' + '(NOT)?\s*' + PatternValidRangeIn + '$')
PatternValidRangeIn = r'(NOT)?\s*(\d+\s*-\s*\d+|0[xX][a-fA-F0-9]+\s*-\s*0[xX][a-fA-F0-9]+|LT\s*\d+|LT\s*0[xX][a-fA-F0-9]+|GT\s*\d+|GT\s*0[xX][a-fA-F0-9]+|LE\s*\d+|LE\s*0[xX][a-fA-F0-9]+|GE\s*\d+|GE\s*0[xX][a-fA-F0-9]+|XOR\s*\d+|XOR\s*0[xX][a-fA-F0-9]+|EQ\s*\d+|EQ\s*0[xX][a-fA-F0-9]+)'
PatternValidRng = re.compile(r'^' + r'(NOT)?\s*' + PatternValidRangeIn + '$')
for Comment in self._Comments:
Comm = Comment[0].strip()
if not Comm:
@ -2071,7 +2071,7 @@ class UniParser(object):
def CheckKeyValid(self, Key, Contents=None):
if not Contents:
Contents = self.FileIn
KeyPattern = re.compile('#string\s+%s\s+.*?#language.*?".*?"' % Key, re.S)
KeyPattern = re.compile(r'#string\s+%s\s+.*?#language.*?".*?"' % Key, re.S)
if KeyPattern.search(Contents):
return True
return False

View File

@ -43,7 +43,7 @@ def GetArrayPattern():
return p
def GetTypedefFuncPointerPattern():
p = re.compile('[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL)
p = re.compile(r'[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL)
return p
def GetDB():

View File

@ -11,7 +11,7 @@ from Common.LongFilePathSupport import OpenLongFilePath as open
gEFI_SOURCE = ''
gEDK_SOURCE = ''
gWORKSPACE = ''
gSHELL_INF = 'Application\Shell'
gSHELL_INF = 'Application\\Shell'
gMAKE_FILE = ''
gDSC_FILE = ''
gFV_FILE = []

View File

@ -54,7 +54,7 @@ def GetArrayPattern():
# @return p: the pattern of function pointer
#
def GetTypedefFuncPointerPattern():
p = re.compile('[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL)
p = re.compile(r'[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL)
return p
## GetDB() method

View File

@ -238,7 +238,7 @@ def ParseDecPcdGenericComment (GenericComment, ContainerFile, TokenSpaceGuidCNam
#
# To replace Macro
#
MACRO_PATTERN = '[\t\s]*\$\([A-Z][_A-Z0-9]*\)'
MACRO_PATTERN = r'[\t\s]*\$\([A-Z][_A-Z0-9]*\)'
MatchedStrs = re.findall(MACRO_PATTERN, Comment)
for MatchedStr in MatchedStrs:
if MatchedStr:

View File

@ -66,13 +66,13 @@ class _ExprError(Exception):
## _ExprBase
#
class _ExprBase:
HEX_PATTERN = '[\t\s]*0[xX][a-fA-F0-9]+'
INT_PATTERN = '[\t\s]*[0-9]+'
MACRO_PATTERN = '[\t\s]*\$\(([A-Z][_A-Z0-9]*)\)'
HEX_PATTERN = r'[\t\s]*0[xX][a-fA-F0-9]+'
INT_PATTERN = r'[\t\s]*[0-9]+'
MACRO_PATTERN = r'[\t\s]*\$\(([A-Z][_A-Z0-9]*)\)'
PCD_PATTERN = \
'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*'
QUOTED_PATTERN = '[\t\s]*L?"[^"]*"'
BOOL_PATTERN = '[\t\s]*(true|True|TRUE|false|False|FALSE)'
r'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*'
QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"'
BOOL_PATTERN = r'[\t\s]*(true|True|TRUE|false|False|FALSE)'
def __init__(self, Token):
self.Token = Token
self.Index = 0
@ -303,9 +303,9 @@ class _LogicalExpressionParser(_ExprBase):
## _ValidRangeExpressionParser
#
class _ValidRangeExpressionParser(_ExprBase):
INT_RANGE_PATTERN = '[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+'
INT_RANGE_PATTERN = r'[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+'
HEX_RANGE_PATTERN = \
'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+'
r'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+'
def __init__(self, Token):
_ExprBase.__init__(self, Token)
self.Parens = 0
@ -407,7 +407,7 @@ class _ValidRangeExpressionParser(_ExprBase):
## _ValidListExpressionParser
#
class _ValidListExpressionParser(_ExprBase):
VALID_LIST_PATTERN = '(0[xX][0-9a-fA-F]+|[0-9]+)([\t\s]*,[\t\s]*(0[xX][0-9a-fA-F]+|[0-9]+))*'
VALID_LIST_PATTERN = r'(0[xX][0-9a-fA-F]+|[0-9]+)([\t\s]*,[\t\s]*(0[xX][0-9a-fA-F]+|[0-9]+))*'
def __init__(self, Token):
_ExprBase.__init__(self, Token)
self.NUM = 1

View File

@ -69,11 +69,11 @@ def GuidStringToGuidStructureString(Guid):
def CheckGuidRegFormat(GuidValue):
## Regular expression used to find out register format of GUID
#
RegFormatGuidPattern = re.compile("^\s*([0-9a-fA-F]){8}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){12}\s*$")
RegFormatGuidPattern = re.compile(r"^\s*([0-9a-fA-F]){8}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){12}\s*$")
if RegFormatGuidPattern.match(GuidValue):
return True
@ -837,8 +837,8 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo):
ST.ERR_FILE_OPEN_FAILURE,
File=FullFileName)
ReFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$")
ReVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$")
ReFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$")
ReVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$")
FileLinesList = ProcessLineExtender(FileLinesList)
@ -978,7 +978,7 @@ def ValidateUNIFilePath(Path):
#
# Check if the file name is valid according to the DEC and INF specification
#
Pattern = '[a-zA-Z0-9_][a-zA-Z0-9_\-\.]*'
Pattern = r'[a-zA-Z0-9_][a-zA-Z0-9_\-\.]*'
FileName = Path.replace(Suffix, '')
InvalidCh = re.sub(Pattern, '', FileName)
if InvalidCh:

View File

@ -23,7 +23,7 @@ from Logger import StringTable as ST
#
# Regular expression for matching macro used in DSC/DEC/INF file inclusion
#
gMACRO_PATTERN = re.compile("\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE)
gMACRO_PATTERN = re.compile(r"\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE)
## GetSplitValueList
#
@ -167,7 +167,7 @@ def ReplaceMacro(String, MacroDefinitions=None, SelfReplacement=False, Line=None
if not Flag:
MacroUsed = gMACRO_PATTERN.findall(String)
else:
ReQuotedString = re.compile('\"')
ReQuotedString = re.compile(r'\"')
QuotedStringList = ReQuotedString.split(String)
if len(QuotedStringList) >= 3:
HaveQuotedMacroFlag = True

View File

@ -611,10 +611,10 @@ def ValidatePcdValueOnDatumType(Value, Type):
elif Type == 'UINT8' or Type == 'UINT16' or Type == 'UINT32' or Type == 'UINT64':
ReIsValidUint8z = re.compile('^0[x|X][a-fA-F0-9]{2}$')
ReIsValidUint16z = re.compile('^0[x|X][a-fA-F0-9]{4}$')
ReIsValidUint32z = re.compile('^0[x|X][a-fA-F0-9]{8}$')
ReIsValidUint64z = re.compile('^0[x|X][a-fA-F0-9]{16}$')
ReIsValidUint8z = re.compile(r'^0[x|X][a-fA-F0-9]{2}$')
ReIsValidUint16z = re.compile(r'^0[x|X][a-fA-F0-9]{4}$')
ReIsValidUint32z = re.compile(r'^0[x|X][a-fA-F0-9]{8}$')
ReIsValidUint64z = re.compile(r'^0[x|X][a-fA-F0-9]{16}$')
if not ReIsValidUint8z.match(Value) and Type == 'UINT8':
return False

View File

@ -25,10 +25,10 @@ from Library.ExpressionValidate import IsValidStringTest
from Library.Misc import CheckGuidRegFormat
TOOL_NAME = 'DecParser'
VERSION_PATTERN = '[0-9]+(\.[0-9]+)?'
CVAR_PATTERN = '[_a-zA-Z][a-zA-Z0-9_]*'
PCD_TOKEN_PATTERN = '(0[xX]0*[a-fA-F0-9]{1,8})|([0-9]+)'
MACRO_PATTERN = '[A-Z][_A-Z0-9]*'
VERSION_PATTERN = r'[0-9]+(\.[0-9]+)?'
CVAR_PATTERN = r'[_a-zA-Z][a-zA-Z0-9_]*'
PCD_TOKEN_PATTERN = r'(0[xX]0*[a-fA-F0-9]{1,8})|([0-9]+)'
MACRO_PATTERN = r'[A-Z][_A-Z0-9]*'
## FileContent
# Class to hold DEC file information

View File

@ -53,12 +53,12 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo, CurrentInfFileName):
#
# To deal with library instance specified by GUID and version
#
RegFormatGuidPattern = re.compile("\s*([0-9a-fA-F]){8}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){4}-"
"([0-9a-fA-F]){12}\s*")
VersionPattern = re.compile('[\t\s]*\d+(\.\d+)?[\t\s]*')
RegFormatGuidPattern = re.compile(r"\s*([0-9a-fA-F]){8}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){4}-"
r"([0-9a-fA-F]){12}\s*")
VersionPattern = re.compile(r'[\t\s]*\d+(\.\d+)?[\t\s]*')
GuidMatchedObj = RegFormatGuidPattern.search(String)
if String.upper().startswith('GUID') and GuidMatchedObj and 'Version' in String:
@ -75,8 +75,8 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo, CurrentInfFileName):
FileLinesList = GetFileLineContent(String, WorkSpace, LineNo, OriginalString)
ReFindFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$")
ReFindVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$")
ReFindFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$")
ReFindVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$")
for Line in FileLinesList:
if ReFindFileGuidPattern.match(Line):
@ -106,8 +106,8 @@ def GetPackageListInfo(FileNameString, WorkSpace, LineNo):
FileLinesList = GetFileLineContent(FileNameString, WorkSpace, LineNo, '')
RePackageHeader = re.compile('^\s*\[Packages.*\].*$')
ReDefineHeader = re.compile('^\s*\[Defines].*$')
RePackageHeader = re.compile(r'^\s*\[Packages.*\].*$')
ReDefineHeader = re.compile(r'^\s*\[Defines].*$')
PackageHederFlag = False
DefineHeaderFlag = False
@ -255,8 +255,8 @@ def GetGuidVerFormLibInstance(Guid, Version, WorkSpace, CurrentInfFileName):
FileLinesList = InfFileObj.readlines()
FileLinesList = ProcessLineExtender(FileLinesList)
ReFindFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$")
ReFindVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$")
ReFindFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$")
ReFindVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$")
for Line in FileLinesList:
if ReFindFileGuidPattern.match(Line):

View File

@ -40,7 +40,7 @@ def GetValidateArchList(LineContent):
TempArch = GetSplitValueList(TempArch, '(', 1)[0]
ArchList = re.split('\s+', TempArch)
ArchList = re.split(r'\s+', TempArch)
NewArchList = []
for Arch in ArchList:
if IsValidArch(Arch):

View File

@ -109,7 +109,7 @@ def InfExpandMacro(Content, LineInfo, GlobalMacros=None, SectionMacros=None, Fla
return Content
else:
for Macro in MacroUsed:
gQuotedMacro = re.compile(".*\".*\$\(%s\).*\".*"%(Macro))
gQuotedMacro = re.compile(r".*\".*\$\(%s\).*\".*"%(Macro))
if not gQuotedMacro.match(Content):
#
# Still have MACROs can't be expanded.
@ -130,8 +130,8 @@ def IsBinaryInf(FileLineList):
if not FileLineList:
return False
ReIsSourcesSection = re.compile("^\s*\[Sources.*\]\s.*$", re.IGNORECASE)
ReIsBinarySection = re.compile("^\s*\[Binaries.*\]\s.*$", re.IGNORECASE)
ReIsSourcesSection = re.compile(r"^\s*\[Sources.*\]\s.*$", re.IGNORECASE)
ReIsBinarySection = re.compile(r"^\s*\[Binaries.*\]\s.*$", re.IGNORECASE)
BinarySectionFoundFlag = False
for Line in FileLineList:
@ -155,7 +155,7 @@ def IsBinaryInf(FileLineList):
# @return Flag
#
def IsLibInstanceInfo(String):
ReIsLibInstance = re.compile("^\s*##\s*@LIB_INSTANCES\s*$")
ReIsLibInstance = re.compile(r"^\s*##\s*@LIB_INSTANCES\s*$")
if ReIsLibInstance.match(String):
return True
else:
@ -171,7 +171,7 @@ def IsLibInstanceInfo(String):
# @return Flag
#
def IsAsBuildOptionInfo(String):
ReIsAsBuildInstance = re.compile("^\s*##\s*@AsBuilt\s*$")
ReIsAsBuildInstance = re.compile(r"^\s*##\s*@AsBuilt\s*$")
if ReIsAsBuildInstance.match(String):
return True
else:

View File

@ -747,12 +747,12 @@ class DecPomAlignment(PackageObject):
#
# deal with "NOT EQ", "NOT LT", "NOT GT", "NOT LE", "NOT GE", "NOT NOT"
#
NOTNOT_Pattern = '[\t\s]*NOT[\t\s]+NOT[\t\s]*'
NOTGE_Pattern = '[\t\s]*NOT[\t\s]+GE[\t\s]*'
NOTLE_Pattern = '[\t\s]*NOT[\t\s]+LE[\t\s]*'
NOTGT_Pattern = '[\t\s]*NOT[\t\s]+GT[\t\s]*'
NOTLT_Pattern = '[\t\s]*NOT[\t\s]+LT[\t\s]*'
NOTEQ_Pattern = '[\t\s]*NOT[\t\s]+EQ[\t\s]*'
NOTNOT_Pattern = r'[\t\s]*NOT[\t\s]+NOT[\t\s]*'
NOTGE_Pattern = r'[\t\s]*NOT[\t\s]+GE[\t\s]*'
NOTLE_Pattern = r'[\t\s]*NOT[\t\s]+LE[\t\s]*'
NOTGT_Pattern = r'[\t\s]*NOT[\t\s]+GT[\t\s]*'
NOTLT_Pattern = r'[\t\s]*NOT[\t\s]+LT[\t\s]*'
NOTEQ_Pattern = r'[\t\s]*NOT[\t\s]+EQ[\t\s]*'
ReplaceValue = re.compile(NOTNOT_Pattern).sub('', ReplaceValue)
ReplaceValue = re.compile(NOTLT_Pattern).sub('x >= ', ReplaceValue)
ReplaceValue = re.compile(NOTGT_Pattern).sub('x <= ', ReplaceValue)
@ -785,7 +785,7 @@ class DecPomAlignment(PackageObject):
if ReplaceValue.find('!') >= 0 and ReplaceValue[ReplaceValue.index('!') + 1] != '=':
ReplaceValue = ReplaceValue.replace('!', ' not ')
if '.' in ReplaceValue:
Pattern = '[a-zA-Z0-9]{1,}\.[a-zA-Z0-9]{1,}'
Pattern = r'[a-zA-Z0-9]{1,}\.[a-zA-Z0-9]{1,}'
MatchedList = re.findall(Pattern, ReplaceValue)
for MatchedItem in MatchedList:
if MatchedItem not in self.PcdDefaultValueDict:
@ -814,7 +814,7 @@ class DecPomAlignment(PackageObject):
#
# Delete the 'L' prefix of a quoted string, this operation is for eval()
#
QUOTED_PATTERN = '[\t\s]*L?"[^"]*"'
QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"'
QuotedMatchedObj = re.search(QUOTED_PATTERN, Expression)
if QuotedMatchedObj:
MatchedStr = QuotedMatchedObj.group().strip()
@ -847,7 +847,7 @@ class DecPomAlignment(PackageObject):
#
# Delete the 'L' prefix of a quoted string, this operation is for eval()
#
QUOTED_PATTERN = '[\t\s]*L?"[^"]*"'
QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"'
QuotedMatchedObj = re.search(QUOTED_PATTERN, DefaultValue)
if QuotedMatchedObj:
MatchedStr = QuotedMatchedObj.group().strip()

View File

@ -200,9 +200,9 @@ def ValidateRegValues(Key, Value):
('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}'
'-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}',
ST.ERR_GUID_VALUE % Value),
'Version' : ('[0-9]+(\.[0-9]+)?', ST.ERR_VERSION_VALUE % \
'Version' : (r'[0-9]+(\.[0-9]+)?', ST.ERR_VERSION_VALUE % \
(Key, Value)),
'XmlSpecification' : ('1\.1', ST.ERR_VERSION_XMLSPEC % Value)
'XmlSpecification' : (r'1\.1', ST.ERR_VERSION_XMLSPEC % Value)
}
if Key not in ValidateMap:
return True, ''

View File

@ -100,11 +100,11 @@ class PcdErrorXml(object):
def TransferValidRange2Expr(self, TokenSpaceGuidCName, CName, ValidRange):
if self.Expression:
pass
INT_RANGE_PATTERN1 = '[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+'
INT_RANGE_PATTERN2 = '[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*'
INT_RANGE_PATTERN1 = r'[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+'
INT_RANGE_PATTERN2 = r'[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*'
HEX_RANGE_PATTERN1 = \
'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+'
HEX_RANGE_PATTERN2 = '[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][a-fA-F0-9]+[\t\s]*'
r'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+'
HEX_RANGE_PATTERN2 = r'[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][a-fA-F0-9]+[\t\s]*'
IntMatch1 = re.compile(INT_RANGE_PATTERN1)
IntMatch2 = re.compile(INT_RANGE_PATTERN2)
HexMatch1 = re.compile(HEX_RANGE_PATTERN1)
@ -158,18 +158,18 @@ class PcdErrorXml(object):
pass
PCD_PATTERN = \
'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*'
r'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*'
IntPattern1 = \
'[\t\s]*\([\t\s]*'+PCD_PATTERN+'[\t\s]+GE[\t\s]+\d+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\
PCD_PATTERN+'[\t\s]+LE[\t\s]+\d+[\t\s]*\)'
r'[\t\s]*\([\t\s]*'+PCD_PATTERN+r'[\t\s]+GE[\t\s]+\d+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\
PCD_PATTERN+r'[\t\s]+LE[\t\s]+\d+[\t\s]*\)'
IntPattern1 = IntPattern1.replace(' ', '')
IntPattern2 = '[\t\s]*'+PCD_PATTERN+'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*'
IntPattern2 = r'[\t\s]*'+PCD_PATTERN+r'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*'
HexPattern1 = \
'[\t\s]*\([\t\s]*'+PCD_PATTERN+'[\t\s]+GE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\
PCD_PATTERN+'[\t\s]+LE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)'
r'[\t\s]*\([\t\s]*'+PCD_PATTERN+r'[\t\s]+GE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\
PCD_PATTERN+r'[\t\s]+LE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)'
HexPattern1 = HexPattern1.replace(' ', '')
HexPattern2 = '[\t\s]*'+PCD_PATTERN+'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][0-9a-zA-Z]+[\t\s]*'
HexPattern2 = r'[\t\s]*'+PCD_PATTERN+r'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][0-9a-zA-Z]+[\t\s]*'
#
# Do the Hex1 conversion
@ -180,7 +180,7 @@ class PcdErrorXml(object):
#
# To match items on both sides of '-'
#
RangeItemList = re.compile('[\t\s]*0[xX][0-9a-fA-F]+[\t\s]*').findall(HexMatchedItem)
RangeItemList = re.compile(r'[\t\s]*0[xX][0-9a-fA-F]+[\t\s]*').findall(HexMatchedItem)
if RangeItemList and len(RangeItemList) == 2:
HexRangeDict[HexMatchedItem] = RangeItemList
@ -204,7 +204,7 @@ class PcdErrorXml(object):
#
# To match items on both sides of '-'
#
RangeItemList = re.compile('[\t\s]*\d+[\t\s]*').findall(MatchedItem)
RangeItemList = re.compile(r'[\t\s]*\d+[\t\s]*').findall(MatchedItem)
if RangeItemList and len(RangeItemList) == 2:
IntRangeDict[MatchedItem] = RangeItemList

View File

@ -281,33 +281,33 @@ class DistributionPackageXml(object):
#
XmlContent = \
re.sub(r'[\s\r\n]*SupArchList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*COMMON'
'[\s\r\n]*"', '', XmlContent)
r'[\s\r\n]*"', '', XmlContent)
XmlContent = \
re.sub(r'[\s\r\n]*SupArchList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*common'
'[\s\r\n]*"', '', XmlContent)
r'[\s\r\n]*"', '', XmlContent)
#
# Remove <SupArchList> COMMON </SupArchList>
#
XmlContent = \
re.sub(r'[\s\r\n]*<SupArchList>[\s\r\n]*COMMON[\s\r\n]*'
'</SupArchList>[\s\r\n]*', '', XmlContent)
r'</SupArchList>[\s\r\n]*', '', XmlContent)
#
# Remove <SupArchList> common </SupArchList>
#
XmlContent = \
re.sub(r'[\s\r\n]*<SupArchList>[\s\r\n]*'
'common[\s\r\n]*</SupArchList>[\s\r\n]*', '', XmlContent)
r'common[\s\r\n]*</SupArchList>[\s\r\n]*', '', XmlContent)
#
# Remove SupModList="COMMON" or "common"
#
XmlContent = \
re.sub(r'[\s\r\n]*SupModList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*COMMON'
'[\s\r\n]*"', '', XmlContent)
r'[\s\r\n]*"', '', XmlContent)
XmlContent = \
re.sub(r'[\s\r\n]*SupModList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*common'
'[\s\r\n]*"', '', XmlContent)
r'[\s\r\n]*"', '', XmlContent)
return XmlContent

View File

@ -88,7 +88,6 @@
UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
MbedTlsLib|CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf
OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf

View File

@ -2351,8 +2351,6 @@ Pkcs7FreeSigners (
unchained to the signer's certificates.
The input signed data could be wrapped in a ContentInfo structure.
Pkcs7GetCertificatesList has not been implemented in BaseCryptoLibMbedTls.
@param[in] P7Data Pointer to the PKCS#7 message.
@param[in] P7Length Length of the PKCS#7 message in bytes.
@param[out] SignerChainCerts Pointer to the certificates list chained to signer's
@ -3141,8 +3139,6 @@ DhComputeKey (
If Seed is NULL, then default seed is used.
If this interface is not supported, then return FALSE.
RandomSeed has not been implemented in BaseCryptoLibMbedTls.
@param[in] Seed Pointer to seed value.
If NULL, default seed is used.
@param[in] SeedSize Size of seed value.

View File

@ -839,17 +839,17 @@ X509GetTBSCert (
Length = 0;
Inf = ASN1_get_object (&Temp, (long *)&Length, (int *)&Asn1Tag, (int *)&ObjClass, (long)CertSize);
if (((Inf & 0x80) == 0x80) || (Asn1Tag != V_ASN1_SEQUENCE)) {
if (((Inf & 0x80) == 0x00) && (Asn1Tag != V_ASN1_SEQUENCE)) {
return FALSE;
}
*TBSCert = (UINT8 *)Temp;
Inf = ASN1_get_object (&Temp, (long *)&Length, (int *)&Asn1Tag, (int *)&ObjClass, (long)Length);
ASN1_get_object (&Temp, (long *)&Length, (int *)&Asn1Tag, (int *)&ObjClass, (long)Length);
//
// Verify the parsed TBSCertificate is one correct SEQUENCE data.
//
if (((Inf & 0x80) == 0x80) || (Asn1Tag != V_ASN1_SEQUENCE)) {
if (((Inf & 0x80) == 0x00) && (Asn1Tag != V_ASN1_SEQUENCE)) {
return FALSE;
}

View File

@ -42,6 +42,14 @@ RandomSeed (
return FALSE;
}
//
// The software PRNG implementation built in OpenSSL depends on message digest algorithm.
// Make sure SHA-1 digest algorithm is available here.
//
if (EVP_add_digest (EVP_sha1 ()) == 0) {
return FALSE;
}
//
// Seed the pseudorandom number generator with user-supplied value.
// NOTE: A cryptographic PRNG must be seeded with unpredictable data.

View File

@ -40,6 +40,14 @@ RandomSeed (
return FALSE;
}
//
// The software PRNG implementation built in OpenSSL depends on message digest algorithm.
// Make sure SHA-1 digest algorithm is available here.
//
if (EVP_add_digest (EVP_sha1 ()) == 0) {
return FALSE;
}
//
// Seed the pseudorandom number generator with user-supplied value.
// NOTE: A cryptographic PRNG must be seeded with unpredictable data.

View File

@ -48,10 +48,10 @@
Cipher/CryptAes.c
Cipher/CryptAeadAesGcmNull.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExt.c
Pk/CryptRsaExtNull.c
Pk/CryptPkcs1Oaep.c
Pk/CryptPkcs5Pbkdf2.c
Pk/CryptPkcs7Sign.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyBase.c
Pk/CryptPkcs7VerifyEku.c
@ -63,7 +63,7 @@
Pk/CryptRsaPssSignNull.c
Pk/CryptEcNull.c
Pem/CryptPem.c
Bn/CryptBn.c
Bn/CryptBnNull.c
SysCall/CrtWrapper.c
SysCall/ConstantTimeClock.c

View File

@ -27,38 +27,34 @@
[Sources]
InternalCryptLib.h
Hash/CryptMd5.c
Hash/CryptSha1.c
Cipher/CryptAeadAesGcmNull.c
Cipher/CryptAes.c
Hash/CryptSha256.c
Hash/CryptSha512.c
Hash/CryptParallelHashNull.c
Hash/CryptSm3.c
Hash/CryptSm3Null.c
Hash/CryptMd5.c
Hash/CryptSha1.c
Hmac/CryptHmac.c
Kdf/CryptHkdf.c
Cipher/CryptAes.c
Cipher/CryptAeadAesGcm.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExt.c
Pk/CryptPkcs1Oaep.c
Pk/CryptPkcs5Pbkdf2.c
Pk/CryptPkcs7Sign.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyBase.c
Pk/CryptPkcs7VerifyEku.c
Pk/CryptDhNull.c
Pk/CryptX509.c
Pk/CryptAuthenticode.c
Pk/CryptTs.c
Pk/CryptRsaExtNull.c
Pk/CryptRsaPss.c
Pk/CryptRsaPssSign.c
Pk/CryptEcNull.c
Pem/CryptPem.c
Pk/CryptRsaPssSignNull.c
Bn/CryptBnNull.c
Rand/CryptRand.c
Pem/CryptPemNull.c
Pk/CryptDhNull.c
Pk/CryptEcNull.c
Pk/CryptPkcs1OaepNull.c
Pk/CryptPkcs5Pbkdf2Null.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyNull.c
Pk/CryptPkcs7VerifyEkuNull.c
Pk/CryptX509Null.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Rand/CryptRandNull.c
SysCall/CrtWrapper.c
SysCall/DummyOpensslSupport.c
SysCall/BaseMemAllocation.c
SysCall/TimerWrapper.c
[Packages]
@ -72,7 +68,6 @@
UefiRuntimeServicesTableLib
DebugLib
MbedTlsLib
OpensslLib
PrintLib
IntrinsicLib
RngLib

View File

@ -1,227 +0,0 @@
/** @file
AEAD (AES-GCM) Wrapper Implementation over MbedTLS.
RFC 5116 - An Interface and Algorithms for Authenticated Encryption
NIST SP800-38d - Cipher Modes of Operation: Galois / Counter Mode(GCM) and GMAC
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/gcm.h>
/**
Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be encrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[out] TagOut Pointer to a buffer that receives the authentication tag output.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the encryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated encryption succeeded.
@retval FALSE AEAD AES-GCM authenticated encryption failed.
**/
BOOLEAN
EFIAPI
AeadAesGcmEncrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
OUT UINT8 *TagOut,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
)
{
mbedtls_gcm_context Ctx;
INT32 Ret;
if (DataInSize > INT_MAX) {
return FALSE;
}
if (ADataSize > INT_MAX) {
return FALSE;
}
if (IvSize != 12) {
return FALSE;
}
switch (KeySize) {
case 16:
case 24:
case 32:
break;
default:
return FALSE;
}
if ((TagSize != 12) && (TagSize != 13) && (TagSize != 14) && (TagSize != 15) && (TagSize != 16)) {
return FALSE;
}
if (DataOutSize != NULL) {
if ((*DataOutSize > INT_MAX) || (*DataOutSize < DataInSize)) {
return FALSE;
}
}
mbedtls_gcm_init (&Ctx);
Ret = mbedtls_gcm_setkey (&Ctx, MBEDTLS_CIPHER_ID_AES, Key, (UINT32)(KeySize * 8));
if (Ret != 0) {
return FALSE;
}
Ret = mbedtls_gcm_crypt_and_tag (
&Ctx,
MBEDTLS_GCM_ENCRYPT,
(UINT32)DataInSize,
Iv,
(UINT32)IvSize,
AData,
(UINT32)ADataSize,
DataIn,
DataOut,
TagSize,
TagOut
);
mbedtls_gcm_free (&Ctx);
if (Ret != 0) {
return FALSE;
}
if (DataOutSize != NULL) {
*DataOutSize = DataInSize;
}
return TRUE;
}
/**
Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
If additional authenticated data verification fails, FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be decrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[in] Tag Pointer to a buffer that contains the authentication tag.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the decryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated decryption succeeded.
@retval FALSE AEAD AES-GCM authenticated decryption failed.
**/
BOOLEAN
EFIAPI
AeadAesGcmDecrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
IN CONST UINT8 *Tag,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
)
{
mbedtls_gcm_context Ctx;
INT32 Ret;
if (DataInSize > INT_MAX) {
return FALSE;
}
if (ADataSize > INT_MAX) {
return FALSE;
}
if (IvSize != 12) {
return FALSE;
}
switch (KeySize) {
case 16:
case 24:
case 32:
break;
default:
return FALSE;
}
if ((TagSize != 12) && (TagSize != 13) && (TagSize != 14) && (TagSize != 15) && (TagSize != 16)) {
return FALSE;
}
if (DataOutSize != NULL) {
if ((*DataOutSize > INT_MAX) || (*DataOutSize < DataInSize)) {
return FALSE;
}
}
mbedtls_gcm_init (&Ctx);
Ret = mbedtls_gcm_setkey (&Ctx, MBEDTLS_CIPHER_ID_AES, Key, (UINT32)(KeySize * 8));
if (Ret != 0) {
return FALSE;
}
Ret = mbedtls_gcm_auth_decrypt (
&Ctx,
(UINT32)DataInSize,
Iv,
(UINT32)IvSize,
AData,
(UINT32)ADataSize,
Tag,
(UINT32)TagSize,
DataIn,
DataOut
);
mbedtls_gcm_free (&Ctx);
if (Ret != 0) {
return FALSE;
}
if (DataOutSize != NULL) {
*DataOutSize = DataInSize;
}
return TRUE;
}

View File

@ -1,235 +0,0 @@
/** @file
SM3 Digest Wrapper Implementations over openssl.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include "internal/sm3.h"
/**
Retrieves the size, in bytes, of the context buffer required for SM3 hash operations.
@return The size, in bytes, of the context buffer required for SM3 hash operations.
**/
UINTN
EFIAPI
Sm3GetContextSize (
VOID
)
{
//
// Retrieves Openssl SM3 Context Size
//
return (UINTN)(sizeof (SM3_CTX));
}
/**
Initializes user-supplied memory pointed by Sm3Context as SM3 hash context for
subsequent use.
If Sm3Context is NULL, then return FALSE.
@param[out] Sm3Context Pointer to SM3 context being initialized.
@retval TRUE SM3 context initialization succeeded.
@retval FALSE SM3 context initialization failed.
**/
BOOLEAN
EFIAPI
Sm3Init (
OUT VOID *Sm3Context
)
{
//
// Check input parameters.
//
if (Sm3Context == NULL) {
return FALSE;
}
//
// Openssl SM3 Context Initialization
//
ossl_sm3_init ((SM3_CTX *)Sm3Context);
return TRUE;
}
/**
Makes a copy of an existing SM3 context.
If Sm3Context is NULL, then return FALSE.
If NewSm3Context is NULL, then return FALSE.
If this interface is not supported, then return FALSE.
@param[in] Sm3Context Pointer to SM3 context being copied.
@param[out] NewSm3Context Pointer to new SM3 context.
@retval TRUE SM3 context copy succeeded.
@retval FALSE SM3 context copy failed.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
Sm3Duplicate (
IN CONST VOID *Sm3Context,
OUT VOID *NewSm3Context
)
{
//
// Check input parameters.
//
if ((Sm3Context == NULL) || (NewSm3Context == NULL)) {
return FALSE;
}
CopyMem (NewSm3Context, Sm3Context, sizeof (SM3_CTX));
return TRUE;
}
/**
Digests the input data and updates SM3 context.
This function performs SM3 digest on a data buffer of the specified size.
It can be called multiple times to compute the digest of long or discontinuous data streams.
SM3 context should be already correctly initialized by Sm3Init(), and should not be finalized
by Sm3Final(). Behavior with invalid context is undefined.
If Sm3Context is NULL, then return FALSE.
@param[in, out] Sm3Context Pointer to the SM3 context.
@param[in] Data Pointer to the buffer containing the data to be hashed.
@param[in] DataSize Size of Data buffer in bytes.
@retval TRUE SM3 data digest succeeded.
@retval FALSE SM3 data digest failed.
**/
BOOLEAN
EFIAPI
Sm3Update (
IN OUT VOID *Sm3Context,
IN CONST VOID *Data,
IN UINTN DataSize
)
{
//
// Check input parameters.
//
if (Sm3Context == NULL) {
return FALSE;
}
//
// Check invalid parameters, in case that only DataLength was checked in Openssl
//
if ((Data == NULL) && (DataSize != 0)) {
return FALSE;
}
//
// Openssl SM3 Hash Update
//
ossl_sm3_update ((SM3_CTX *)Sm3Context, Data, DataSize);
return TRUE;
}
/**
Completes computation of the SM3 digest value.
This function completes SM3 hash computation and retrieves the digest value into
the specified memory. After this function has been called, the SM3 context cannot
be used again.
SM3 context should be already correctly initialized by Sm3Init(), and should not be
finalized by Sm3Final(). Behavior with invalid SM3 context is undefined.
If Sm3Context is NULL, then return FALSE.
If HashValue is NULL, then return FALSE.
@param[in, out] Sm3Context Pointer to the SM3 context.
@param[out] HashValue Pointer to a buffer that receives the SM3 digest
value (32 bytes).
@retval TRUE SM3 digest computation succeeded.
@retval FALSE SM3 digest computation failed.
**/
BOOLEAN
EFIAPI
Sm3Final (
IN OUT VOID *Sm3Context,
OUT UINT8 *HashValue
)
{
//
// Check input parameters.
//
if ((Sm3Context == NULL) || (HashValue == NULL)) {
return FALSE;
}
//
// Openssl SM3 Hash Finalization
//
ossl_sm3_final (HashValue, (SM3_CTX *)Sm3Context);
return TRUE;
}
/**
Computes the SM3 message digest of a input data buffer.
This function performs the SM3 message digest of a given data buffer, and places
the digest value into the specified memory.
If this interface is not supported, then return FALSE.
@param[in] Data Pointer to the buffer containing the data to be hashed.
@param[in] DataSize Size of Data buffer in bytes.
@param[out] HashValue Pointer to a buffer that receives the SM3 digest
value (32 bytes).
@retval TRUE SM3 digest computation succeeded.
@retval FALSE SM3 digest computation failed.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
Sm3HashAll (
IN CONST VOID *Data,
IN UINTN DataSize,
OUT UINT8 *HashValue
)
{
SM3_CTX Ctx;
//
// Check input parameters.
//
if (HashValue == NULL) {
return FALSE;
}
if ((Data == NULL) && (DataSize != 0)) {
return FALSE;
}
//
// SM3 Hash Computation.
//
ossl_sm3_init (&Ctx);
ossl_sm3_update (&Ctx, Data, DataSize);
ossl_sm3_final (HashValue, &Ctx);
return TRUE;
}

View File

@ -22,53 +22,4 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
//
#include <mbedtls/mbedtls_config.h>
/**
The MbedTLS function f_rng, which MbedtlsRand implements.
@param[in] RngState Not used, just for compatibility with mbedlts.
@param[out] Output Pointer to buffer to receive random value.
@param[in] Len Size of random bytes to generate.
@retval 0 Pseudorandom byte stream generated successfully.
@retval Non-0 Pseudorandom number generator fails to generate due to lack of entropy.
**/
INT32
MbedtlsRand (
VOID *RngState,
UINT8 *Output,
UINTN Len
);
/**
Check input P7Data is a wrapped ContentInfo structure or not. If not construct
a new structure to wrap P7Data.
Caution: This function may receive untrusted input.
UEFI Authenticated Variable is external input, so this function will do basic
check for PKCS#7 data structure.
@param[in] P7Data Pointer to the PKCS#7 message to verify.
@param[in] P7Length Length of the PKCS#7 message in bytes.
@param[out] WrapFlag If TRUE P7Data is a ContentInfo structure, otherwise
return FALSE.
@param[out] WrapData If return status of this function is TRUE:
1) when WrapFlag is TRUE, pointer to P7Data.
2) when WrapFlag is FALSE, pointer to a new ContentInfo
structure. It's caller's responsibility to free this
buffer.
@param[out] WrapDataSize Length of ContentInfo structure in bytes.
@retval TRUE The operation is finished successfully.
@retval FALSE The operation is failed due to lack of resources.
**/
BOOLEAN
WrapPkcs7Data (
IN CONST UINT8 *P7Data,
IN UINTN P7Length,
OUT BOOLEAN *WrapFlag,
OUT UINT8 **WrapData,
OUT UINTN *WrapDataSize
);
#endif

View File

@ -38,35 +38,31 @@
Hash/CryptMd5.c
Hash/CryptSha1.c
Hash/CryptSha256.c
Hash/CryptSm3Null.c
Hash/CryptSha512.c
Hash/CryptParallelHashNull.c
Hash/CryptSm3.c
Hmac/CryptHmac.c
Kdf/CryptHkdf.c
Cipher/CryptAes.c
Cipher/CryptAeadAesGcmNull.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExtNull.c
Pk/CryptRsaPss.c
Pk/CryptRsaPssSignNull.c
Bn/CryptBnNull.c
Pem/CryptPemNull.c
Pk/CryptDhNull.c
Pk/CryptEcNull.c
Pk/CryptPkcs1OaepNull.c
Pk/CryptPkcs5Pbkdf2Null.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyBase.c
Pk/CryptPkcs7VerifyEku.c
Pk/CryptDhNull.c
Pk/CryptPkcs7VerifyNull.c
Pk/CryptPkcs7VerifyEkuNull.c
Pk/CryptX509Null.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Pk/CryptRsaPss.c
Pk/CryptRsaPssSignNull.c
Pk/CryptEcNull.c
Pem/CryptPemNull.c
Rand/CryptRandNull.c
Bn/CryptBnNull.c
SysCall/CrtWrapper.c
SysCall/DummyOpensslSupport.c
SysCall/BaseMemAllocation.c
SysCall/ConstantTimeClock.c
[Packages]
@ -79,7 +75,6 @@
MemoryAllocationLib
DebugLib
MbedTlsLib
OpensslLib
IntrinsicLib
PrintLib
PeiServicesTablePointerLib

View File

@ -1,138 +0,0 @@
/** @file
PEM (Privacy Enhanced Mail) Format Handler Wrapper Implementation over MbedTLS.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/pem.h>
#include <mbedtls/pk.h>
#include <mbedtls/rsa.h>
#include <mbedtls/ecp.h>
#include <mbedtls/ecdh.h>
#include <mbedtls/ecdsa.h>
/**
Retrieve the RSA Private Key from the password-protected PEM key data.
@param[in] PemData Pointer to the PEM-encoded key data to be retrieved.
@param[in] PemSize Size of the PEM key data in bytes.
@param[in] Password NULL-terminated passphrase used for encrypted PEM key data.
@param[out] RsaContext Pointer to new-generated RSA context which contain the retrieved
RSA private key component. Use RsaFree() function to free the
resource.
If PemData is NULL, then return FALSE.
If RsaContext is NULL, then return FALSE.
@retval TRUE RSA Private Key was retrieved successfully.
@retval FALSE Invalid PEM key data or incorrect password.
**/
BOOLEAN
EFIAPI
RsaGetPrivateKeyFromPem (
IN CONST UINT8 *PemData,
IN UINTN PemSize,
IN CONST CHAR8 *Password,
OUT VOID **RsaContext
)
{
INT32 Ret;
mbedtls_pk_context Pk;
mbedtls_rsa_context *Rsa;
UINT8 *NewPemData;
UINTN PasswordLen;
if ((PemData == NULL) || (RsaContext == NULL) || (PemSize > INT_MAX)) {
return FALSE;
}
NewPemData = NULL;
if (PemData[PemSize - 1] != 0) {
NewPemData = AllocateZeroPool (PemSize + 1);
if (NewPemData == NULL) {
return FALSE;
}
CopyMem (NewPemData, PemData, PemSize + 1);
NewPemData[PemSize] = 0;
PemData = NewPemData;
PemSize += 1;
}
mbedtls_pk_init (&Pk);
if (Password != NULL) {
PasswordLen = AsciiStrLen (Password);
} else {
PasswordLen = 0;
}
Ret = mbedtls_pk_parse_key (&Pk, PemData, PemSize, (CONST UINT8 *)Password, PasswordLen, NULL, NULL);
if (NewPemData != NULL) {
FreePool (NewPemData);
NewPemData = NULL;
}
if (Ret != 0) {
mbedtls_pk_free (&Pk);
return FALSE;
}
if (mbedtls_pk_get_type (&Pk) != MBEDTLS_PK_RSA) {
mbedtls_pk_free (&Pk);
return FALSE;
}
Rsa = RsaNew ();
if (Rsa == NULL) {
mbedtls_pk_free (&Pk);
return FALSE;
}
Ret = mbedtls_rsa_copy (Rsa, mbedtls_pk_rsa (Pk));
if (Ret != 0) {
RsaFree (Rsa);
mbedtls_pk_free (&Pk);
return FALSE;
}
mbedtls_pk_free (&Pk);
*RsaContext = Rsa;
return TRUE;
}
/**
Retrieve the EC Private Key from the password-protected PEM key data.
@param[in] PemData Pointer to the PEM-encoded key data to be retrieved.
@param[in] PemSize Size of the PEM key data in bytes.
@param[in] Password NULL-terminated passphrase used for encrypted PEM key data.
@param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved
EC private key component. Use EcFree() function to free the
resource.
If PemData is NULL, then return FALSE.
If EcContext is NULL, then return FALSE.
@retval TRUE EC Private Key was retrieved successfully.
@retval FALSE Invalid PEM key data or incorrect password.
**/
BOOLEAN
EFIAPI
EcGetPrivateKeyFromPem (
IN CONST UINT8 *PemData,
IN UINTN PemSize,
IN CONST CHAR8 *Password,
OUT VOID **EcContext
)
{
ASSERT (FALSE);
return FALSE;
}

View File

@ -1,214 +0,0 @@
/** @file
Authenticode Portable Executable Signature Verification which does not provide
real capabilities.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/pkcs7.h>
//
// OID ASN.1 Value for SPC_INDIRECT_DATA_OBJID
//
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 mSpcIndirectOidValue[] = {
0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x04
};
/**
Verifies the validity of a PE/COFF Authenticode Signature as described in "Windows
Authenticode Portable Executable Signature Format".
Return FALSE to indicate this interface is not supported.
@param[in] AuthData Pointer to the Authenticode Signature retrieved from signed
PE/COFF image to be verified.
@param[in] DataSize Size of the Authenticode Signature in bytes.
@param[in] TrustedCert Pointer to a trusted/root certificate encoded in DER, which
is used for certificate chain verification.
@param[in] CertSize Size of the trusted certificate in bytes.
@param[in] ImageHash Pointer to the original image file hash value. The procedure
for calculating the image hash value is described in Authenticode
specification.
@param[in] HashSize Size of Image hash value in bytes.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
AuthenticodeVerify (
IN CONST UINT8 *AuthData,
IN UINTN DataSize,
IN CONST UINT8 *TrustedCert,
IN UINTN CertSize,
IN CONST UINT8 *ImageHash,
IN UINTN HashSize
)
{
BOOLEAN Status;
CONST UINT8 *OrigAuthData;
UINT8 *SpcIndirectDataContent;
UINT8 Asn1Byte;
UINTN ContentSize;
CONST UINT8 *SpcIndirectDataOid;
UINT8 *Ptr;
UINT8 *End;
INT32 Len;
UINTN ObjLen;
OrigAuthData = AuthData;
//
// Check input parameters.
//
if ((AuthData == NULL) || (TrustedCert == NULL) || (ImageHash == NULL)) {
return FALSE;
}
if ((DataSize > INT_MAX) || (CertSize > INT_MAX) || (HashSize > INT_MAX)) {
return FALSE;
}
if (DataSize <= HashSize) {
return FALSE;
}
Ptr = (UINT8 *)(UINTN)AuthData;
Len = (UINT32)DataSize;
End = Ptr + Len;
// ContentInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// ContentType
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Ptr += ObjLen;
// content
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
End = Ptr + ObjLen;
// signedData
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// version
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// digestAlgo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
Ptr += ObjLen;
// encapContentInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
End = Ptr + ObjLen;
// eContentType
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Status = FALSE;
SpcIndirectDataOid = Ptr;
if ((ObjLen != sizeof (mSpcIndirectOidValue)) ||
(CompareMem (
SpcIndirectDataOid,
mSpcIndirectOidValue,
sizeof (mSpcIndirectOidValue)
) != 0))
{
//
// Un-matched SPC_INDIRECT_DATA_OBJID.
//
goto _Exit;
}
Ptr += ObjLen;
// eContent
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
SpcIndirectDataContent = Ptr;
//
// Retrieve the SEQUENCE data size from ASN.1-encoded SpcIndirectDataContent.
//
Asn1Byte = *(SpcIndirectDataContent + 1);
if ((Asn1Byte & 0x80) == 0) {
//
// Short Form of Length Encoding (Length < 128)
//
ContentSize = (UINTN)(Asn1Byte & 0x7F);
//
// Skip the SEQUENCE Tag;
//
SpcIndirectDataContent += 2;
} else if ((Asn1Byte & 0x81) == 0x81) {
//
// Long Form of Length Encoding (128 <= Length < 255, Single Octet)
//
ContentSize = (UINTN)(*(UINT8 *)(SpcIndirectDataContent + 2));
//
// Skip the SEQUENCE Tag;
//
SpcIndirectDataContent += 3;
} else if ((Asn1Byte & 0x82) == 0x82) {
//
// Long Form of Length Encoding (Length > 255, Two Octet)
//
ContentSize = (UINTN)(*(UINT8 *)(SpcIndirectDataContent + 2));
ContentSize = (ContentSize << 8) + (UINTN)(*(UINT8 *)(SpcIndirectDataContent + 3));
//
// Skip the SEQUENCE Tag;
//
SpcIndirectDataContent += 4;
} else {
goto _Exit;
}
//
// Compare the original file hash value to the digest retrieve from SpcIndirectDataContent
// defined in Authenticode
// NOTE: Need to double-check HashLength here!
//
if (ContentSize < HashSize) {
return FALSE;
}
if (CompareMem (SpcIndirectDataContent + ContentSize - HashSize, ImageHash, HashSize) != 0) {
//
// Un-matched PE/COFF Hash Value
//
goto _Exit;
}
//
// Verifies the PKCS#7 Signed Data in PE/COFF Authenticode Signature
//
Status = (BOOLEAN)Pkcs7Verify (OrigAuthData, DataSize, TrustedCert, CertSize, SpcIndirectDataContent, ContentSize);
_Exit:
return Status;
}

View File

@ -1,278 +0,0 @@
/** @file
This file contains UEFI wrapper functions for RSA PKCS1v2 OAEP encryption routines.
SPDX-License-Identifier: BSD-2-Clause-Patent
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
**/
#include "InternalCryptLib.h"
#include <mbedtls/rsa.h>
#include <mbedtls/x509_crt.h>
#include <Library/MemoryAllocationLib.h>
/**
Encrypts a blob using PKCS1v2 (RSAES-OAEP) schema. On success, will return the
encrypted message in a newly allocated buffer.
Things that can cause a failure include:
- X509 key size does not match any known key size.
- Fail to parse X509 certificate.
- Fail to allocate an intermediate buffer.
- Null pointer provided for a non-optional parameter.
- Data size is too large for the provided key size (max size is a function of key size
and hash digest size).
@param[in] PublicKey A pointer to the DER-encoded X509 certificate that
will be used to encrypt the data.
@param[in] PublicKeySize Size of the X509 cert buffer.
@param[in] InData Data to be encrypted.
@param[in] InDataSize Size of the data buffer.
@param[in] PrngSeed [Optional] If provided, a pointer to a random seed buffer
to be used when initializing the PRNG. NULL otherwise.
@param[in] PrngSeedSize [Optional] If provided, size of the random seed buffer.
0 otherwise.
@param[out] EncryptedData Pointer to an allocated buffer containing the encrypted
message.
@param[out] EncryptedDataSize Size of the encrypted message buffer.
@retval TRUE Encryption was successful.
@retval FALSE Encryption failed.
**/
BOOLEAN
EFIAPI
Pkcs1v2Encrypt (
IN CONST UINT8 *PublicKey,
IN UINTN PublicKeySize,
IN UINT8 *InData,
IN UINTN InDataSize,
IN CONST UINT8 *PrngSeed OPTIONAL,
IN UINTN PrngSeedSize OPTIONAL,
OUT UINT8 **EncryptedData,
OUT UINTN *EncryptedDataSize
)
{
BOOLEAN Result;
UINT32 Ret;
UINT8 *OutData;
mbedtls_x509_crt CertContext;
mbedtls_rsa_context RsaContext;
//
// Check input parameters.
//
if ((PublicKey == NULL) || (InData == NULL) ||
(EncryptedData == NULL) || (EncryptedDataSize == NULL))
{
return FALSE;
}
//
// Check public key size.
//
if (PublicKeySize > UINT_MAX) {
//
// Public key size is too large for implementation.
//
return FALSE;
}
*EncryptedData = NULL;
*EncryptedDataSize = 0;
Result = FALSE;
OutData = NULL;
mbedtls_x509_crt_init (&CertContext);
if (mbedtls_x509_crt_parse_der (&CertContext, PublicKey, (UINT32)PublicKeySize) != 0) {
goto _Exit;
}
if (mbedtls_pk_get_type (&CertContext.pk) != MBEDTLS_PK_RSA) {
goto _Exit;
}
mbedtls_rsa_init (&RsaContext);
if (mbedtls_rsa_set_padding (&RsaContext, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_NONE) != 0) {
goto _Exit;
}
Ret = mbedtls_rsa_copy (&RsaContext, mbedtls_pk_rsa (CertContext.pk));
if (Ret != 0) {
goto _Exit;
}
*EncryptedDataSize = RsaContext.len;
//
// Allocate a buffer for the output data.
//
OutData = AllocateZeroPool (*EncryptedDataSize);
if (OutData == NULL) {
//
// Fail to allocate the output buffer.
//
goto _Exit;
}
Ret = mbedtls_rsa_pkcs1_encrypt (
&RsaContext,
MbedtlsRand,
NULL,
InDataSize,
InData,
OutData
);
if (Ret != 0) {
FreePool (OutData);
OutData = NULL;
goto _Exit;
}
*EncryptedData = OutData;
Result = TRUE;
_Exit:
//
// Release Resources
//
if (&CertContext != NULL) {
mbedtls_x509_crt_free (&CertContext);
}
if (&RsaContext != NULL) {
mbedtls_rsa_free (&RsaContext);
}
return Result;
}
/**
Encrypts a blob using PKCS1v2 (RSAES-OAEP) schema. On success, will return the
encrypted message in a newly allocated buffer.
Things that can cause a failure include:
- X509 key size does not match any known key size.
- Fail to allocate an intermediate buffer.
- Null pointer provided for a non-optional parameter.
- Data size is too large for the provided key size (max size is a function of key size
and hash digest size).
@param[in] RsaContext A pointer to an RSA context created by RsaNew() and
provisioned with a public key using RsaSetKey().
@param[in] InData Data to be encrypted.
@param[in] InDataSize Size of the data buffer.
@param[in] PrngSeed [Optional] If provided, a pointer to a random seed buffer
to be used when initializing the PRNG. NULL otherwise.
@param[in] PrngSeedSize [Optional] If provided, size of the random seed buffer.
0 otherwise.
@param[in] DigestLen [Optional] If provided, size of the hash used:
SHA1_DIGEST_SIZE
SHA256_DIGEST_SIZE
SHA384_DIGEST_SIZE
SHA512_DIGEST_SIZE
0 to use default (SHA1)
@param[out] EncryptedData Pointer to an allocated buffer containing the encrypted
message.
@param[out] EncryptedDataSize Size of the encrypted message buffer.
@retval TRUE Encryption was successful.
@retval FALSE Encryption failed.
**/
BOOLEAN
EFIAPI
RsaOaepEncrypt (
IN VOID *RsaContext,
IN UINT8 *InData,
IN UINTN InDataSize,
IN CONST UINT8 *PrngSeed OPTIONAL,
IN UINTN PrngSeedSize OPTIONAL,
IN UINT16 DigestLen OPTIONAL,
OUT UINT8 **EncryptedData,
OUT UINTN *EncryptedDataSize
)
{
ASSERT (FALSE);
return FALSE;
}
/**
Decrypts a blob using PKCS1v2 (RSAES-OAEP) schema. On success, will return the
decrypted message in a newly allocated buffer.
Things that can cause a failure include:
- Fail to parse private key.
- Fail to allocate an intermediate buffer.
- Null pointer provided for a non-optional parameter.
@param[in] PrivateKey A pointer to the DER-encoded private key.
@param[in] PrivateKeySize Size of the private key buffer.
@param[in] EncryptedData Data to be decrypted.
@param[in] EncryptedDataSize Size of the encrypted buffer.
@param[out] OutData Pointer to an allocated buffer containing the encrypted
message.
@param[out] OutDataSize Size of the encrypted message buffer.
@retval TRUE Encryption was successful.
@retval FALSE Encryption failed.
**/
BOOLEAN
EFIAPI
Pkcs1v2Decrypt (
IN CONST UINT8 *PrivateKey,
IN UINTN PrivateKeySize,
IN UINT8 *EncryptedData,
IN UINTN EncryptedDataSize,
OUT UINT8 **OutData,
OUT UINTN *OutDataSize
)
{
ASSERT (FALSE);
return FALSE;
}
/**
Decrypts a blob using PKCS1v2 (RSAES-OAEP) schema. On success, will return the
decrypted message in a newly allocated buffer.
Things that can cause a failure include:
- Fail to parse private key.
- Fail to allocate an intermediate buffer.
- Null pointer provided for a non-optional parameter.
@param[in] RsaContext A pointer to an RSA context created by RsaNew() and
provisioned with a private key using RsaSetKey().
@param[in] EncryptedData Data to be decrypted.
@param[in] EncryptedDataSize Size of the encrypted buffer.
@param[in] DigestLen [Optional] If provided, size of the hash used:
SHA1_DIGEST_SIZE
SHA256_DIGEST_SIZE
SHA384_DIGEST_SIZE
SHA512_DIGEST_SIZE
0 to use default (SHA1)
@param[out] OutData Pointer to an allocated buffer containing the encrypted
message.
@param[out] OutDataSize Size of the encrypted message buffer.
@retval TRUE Encryption was successful.
@retval FALSE Encryption failed.
**/
BOOLEAN
EFIAPI
RsaOaepDecrypt (
IN VOID *RsaContext,
IN UINT8 *EncryptedData,
IN UINTN EncryptedDataSize,
IN UINT16 DigestLen OPTIONAL,
OUT UINT8 **OutData,
OUT UINTN *OutDataSize
)
{
ASSERT (FALSE);
return FALSE;
}

View File

@ -1,100 +0,0 @@
/** @file
PBKDF2 Key Derivation Function Wrapper Implementation over MbedTLS.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/pkcs5.h>
/**
Derives a key from a password using a salt and iteration count, based on PKCS#5 v2.0
password based encryption key derivation function PBKDF2, as specified in RFC 2898.
If Password or Salt or OutKey is NULL, then return FALSE.
If the hash algorithm could not be determined, then return FALSE.
@param[in] PasswordLength Length of input password in bytes.
@param[in] Password Pointer to the array for the password.
@param[in] SaltLength Size of the Salt in bytes.
@param[in] Salt Pointer to the Salt.
@param[in] IterationCount Number of iterations to perform. Its value should be
greater than or equal to 1.
@param[in] DigestSize Size of the message digest to be used (eg. SHA256_DIGEST_SIZE).
NOTE: DigestSize will be used to determine the hash algorithm.
Only SHA1_DIGEST_SIZE or SHA256_DIGEST_SIZE is supported.
@param[in] KeyLength Size of the derived key buffer in bytes.
@param[out] OutKey Pointer to the output derived key buffer.
@retval TRUE A key was derived successfully.
@retval FALSE One of the pointers was NULL or one of the sizes was too large.
@retval FALSE The hash algorithm could not be determined from the digest size.
@retval FALSE The key derivation operation failed.
**/
BOOLEAN
EFIAPI
Pkcs5HashPassword (
IN UINTN PasswordLength,
IN CONST CHAR8 *Password,
IN UINTN SaltLength,
IN CONST UINT8 *Salt,
IN UINTN IterationCount,
IN UINTN DigestSize,
IN UINTN KeyLength,
OUT UINT8 *OutKey
)
{
mbedtls_md_type_t HashAlg;
//
// Parameter Checking.
//
if ((Password == NULL) || (Salt == NULL) || (OutKey == NULL)) {
return FALSE;
}
if ((PasswordLength == 0) || (PasswordLength > INT_MAX) ||
(SaltLength == 0) || (SaltLength > INT_MAX) ||
(KeyLength == 0) || (KeyLength > INT_MAX) ||
(IterationCount < 1) || (IterationCount > INT_MAX))
{
return FALSE;
}
//
// Make sure the digest algorithm is supported.
//
switch (DigestSize) {
case SHA1_DIGEST_SIZE:
HashAlg = MBEDTLS_MD_SHA1;
break;
case SHA256_DIGEST_SIZE:
HashAlg = MBEDTLS_MD_SHA256;
break;
default:
return FALSE;
break;
}
//
// Perform password-based key derivation routines.
//
if (mbedtls_pkcs5_pbkdf2_hmac_ext (
HashAlg,
(CONST UINT8 *)Password,
(int)PasswordLength,
(CONST UINT8 *)Salt,
(int)SaltLength,
(int)IterationCount,
(int)KeyLength,
(UINT8 *)OutKey
) != 0)
{
return FALSE;
} else {
return TRUE;
}
}

View File

@ -4,7 +4,7 @@
RFC 2315 - PKCS #7: Cryptographic Message Syntax Version 1.5
Copyright (c) 2023-2024, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2023, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
@ -31,6 +31,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
#define MBEDTLS_OID_PKCS7_DIGESTED_DATA MBEDTLS_OID_PKCS7 "\x05"
#define MBEDTLS_OID_PKCS7_ENCRYPTED_DATA MBEDTLS_OID_PKCS7 "\x06"
typedef mbedtls_asn1_buf MBEDTLSPKCS7BUF;
typedef mbedtls_asn1_named_data MBEDTLSPKCS7NAME;
typedef mbedtls_asn1_sequence MBEDTLSPKCS7SEQUENCE;
///
/// PKCS7 SignerInfo type
/// https://tools.ietf.org/html/rfc2315#section-9.2
@ -44,8 +48,8 @@ typedef struct MbedtlsPkcs7SignerInfo {
mbedtls_x509_buf SigAlgIdentifier;
mbedtls_x509_buf AuthAttr;
mbedtls_x509_buf Sig;
struct MbedtlsPkcs7SignerInfo *Next;
} MbedtlsPkcs7SignerInfo;
struct MBEDTLSPKCS7SIGNERINFO *Next;
} MBEDTLSPKCS7SIGNERINFO;
///
/// PKCS7 signed data attached data format
@ -53,7 +57,7 @@ typedef struct MbedtlsPkcs7SignerInfo {
typedef struct MbedtlsPkcs7Data {
mbedtls_asn1_buf Oid;
mbedtls_asn1_buf Data;
} MbedtlsPkcs7Data;
} MBEDTLSPKCS7DATA;
///
/// Signed Data
@ -62,27 +66,18 @@ typedef struct MbedtlsPkcs7Data {
typedef struct MbedtlsPkcs7SignedData {
INT32 Version;
mbedtls_asn1_buf DigestAlgorithms;
struct MbedtlsPkcs7Data ContentInfo;
struct MBEDTLSPKCS7DATA ContentInfo;
mbedtls_x509_crt Certificates;
mbedtls_x509_crl Crls;
struct MbedtlsPkcs7SignerInfo SignerInfos;
} MbedtlsPkcs7SignedData;
} MBEDTLSPKCS7SIGNEDDATA;
///
/// PKCS7 struct, only support SignedData
///
typedef struct MbedtlsPkcs7 {
mbedtls_asn1_buf ContentTypeOid;
struct MbedtlsPkcs7SignedData SignedData;
} MbedtlsPkcs7;
#define EDKII_ASN1_CHK_ADD(g, f) \
do \
{ \
if( ( Ret = (f) ) < 0 ) \
return( Ret ); \
else \
(g) += Ret; \
} while( 0 )
struct MBEDTLSPKCS7SIGNEDDATA SignedData;
} MBEDTLSPKCS7;
#endif

View File

@ -1,635 +0,0 @@
/** @file
PKCS#7 SignedData Sign Wrapper and PKCS#7 SignedData Verification Wrapper
Implementation over mbedtls.
RFC 8422 - Elliptic Curve Cryptography (ECC) Cipher Suites
FIPS 186-4 - Digital Signature Standard (DSS)
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "CryptPkcs7Internal.h"
#include <mbedtls/ecdh.h>
///
/// Enough to store any signature generated by PKCS7
///
#define MAX_SIGNATURE_SIZE 1024
GLOBAL_REMOVE_IF_UNREFERENCED UINT8 MbedtlsOidDigestAlgSha256[] = MBEDTLS_OID_DIGEST_ALG_SHA256;
GLOBAL_REMOVE_IF_UNREFERENCED UINT8 MbedtlsOidPkcs1Rsa[] = MBEDTLS_OID_PKCS1_RSA;
/**
Write DigestAlgorithmIdentifier.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] DigestType Digest Type
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteDigestAlgorithm (
UINT8 **Ptr,
UINT8 *Start,
mbedtls_md_type_t DigestType
)
{
UINT8 *OidPtr;
UINTN OidLen;
INT32 Ret;
Ret = mbedtls_oid_get_oid_by_md (DigestType, (CONST CHAR8 **)&OidPtr, &OidLen);
if (Ret == 0) {
return mbedtls_asn1_write_oid (Ptr, (CONST UINT8 *)Start, (CONST CHAR8 *)OidPtr, OidLen);
}
return 0;
}
/**
DigestAlgorithmIdentifiers ::=
SET OF DigestAlgorithmIdentifier.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] DigestTypes Digest Type array.
@param[in] Count The index for Digest Type.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteDigestAlgorithmSet (
UINT8 **Ptr,
UINT8 *Start,
mbedtls_md_type_t *DigestTypes,
INTN Count
)
{
INTN Idx;
INT32 Len;
INT32 Ret;
Len = 0;
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_null (Ptr, Start));
for (Idx = 0; Idx < Count; Idx++) {
EDKII_ASN1_CHK_ADD (
Len,
MbedTlsPkcs7WriteDigestAlgorithm (Ptr, Start, DigestTypes[Idx])
);
}
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, (UINTN)Len));
EDKII_ASN1_CHK_ADD (
Len,
mbedtls_asn1_write_tag (
Ptr,
Start,
(MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)
)
);
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, (UINTN)Len));
EDKII_ASN1_CHK_ADD (
Len,
mbedtls_asn1_write_tag (
Ptr,
Start,
(MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET)
)
);
return Len;
}
/**
ContentInfo ::= SEQUENCE {
contentType ContentType,
content
[0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] Content ContentInfo.
@param[in] ContentLen Size of ContentInfo.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteContentInfo (
UINT8 **Ptr,
UINT8 *Start,
UINT8 *Content,
INTN ContentLen
)
{
INT32 Ret;
INT32 Len;
Len = 0;
if (Content != NULL) {
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_octet_string (Ptr, Start, Content, ContentLen));
}
EDKII_ASN1_CHK_ADD (
Len,
mbedtls_asn1_write_oid (
Ptr,
Start,
MBEDTLS_OID_PKCS7_DATA,
sizeof (MBEDTLS_OID_PKCS7_DATA) - 1
)
);
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
return Len;
}
/**
certificates :: SET OF ExtendedCertificateOrCertificate,
ExtendedCertificateOrCertificate ::= CHOICE {
certificate Certificate -- x509,
extendedCertificate[0] IMPLICIT ExtendedCertificate }.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] Cert Certificate.
@param[in] OtherCerts Ohter Certificate.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteCertificates (
UINT8 **Ptr,
UINT8 *Start,
mbedtls_x509_crt *Cert,
mbedtls_x509_crt *OtherCerts
)
{
INT32 Ret;
INT32 Len;
mbedtls_x509_crt *TmpCert;
Len = 0;
/// Write OtherCerts
TmpCert = OtherCerts;
while (TmpCert != NULL) {
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_raw_buffer (Ptr, Start, TmpCert->raw.p, TmpCert->raw.len));
TmpCert = TmpCert->next;
}
/// Write Cert
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_raw_buffer (Ptr, Start, Cert->raw.p, Cert->raw.len));
/// Write NextContext
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC));
return Len;
}
/**
write Pkcs7 Int.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] SerialRaw SerialRaw.
@param[in] SerialRawLen Size of SerialRaw.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteInt (
UINT8 **Ptr,
UINT8 *Start,
UINT8 *SerialRaw,
INTN SerialRawLen
)
{
INT32 Ret;
UINT8 *Pt;
INT32 Len;
Len = 0;
Pt = SerialRaw + SerialRawLen;
while (Pt > SerialRaw) {
*--(*Ptr) = *--Pt;
Len++;
}
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_INTEGER));
return Len;
}
/**
write Pkcs7 Issuer And SerialNumber.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] Serial Serial.
@param[in] SerialLen Size of Serial.
@param[in] IssuerRaw IssuerRawLen.
@param[in] IssuerRawLen Size of IssuerRawLen.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteIssuerAndSerialNumber (
UINT8 **Ptr,
UINT8 *Start,
UINT8 *Serial,
INTN SerialLen,
UINT8 *IssuerRaw,
INTN IssuerRawLen
)
{
INT32 Ret;
INT32 Len;
Len = 0;
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteInt (Ptr, Start, Serial, SerialLen));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_raw_buffer (Ptr, Start, IssuerRaw, IssuerRawLen));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
return Len;
}
/**
SignerInfo ::= SEQUENCE {
version Version;
issuerAndSerialNumber IssuerAndSerialNumber,
digestAlgorithm DigestAlgorithmIdentifier,
authenticatedAttributes
[0] IMPLICIT Attributes OPTIONAL,
digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
encryptedDigest EncryptedDigest,
unauthenticatedAttributes
[1] IMPLICIT Attributes OPTIONAL.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] SignerInfo SignerInfo.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteSignerInfo (
UINT8 **Ptr,
UINT8 *Start,
MbedtlsPkcs7SignerInfo *SignerInfo
)
{
INT32 Ret;
INT32 Len;
Len = 0;
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_octet_string (Ptr, Start, SignerInfo->Sig.p, SignerInfo->Sig.len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_algorithm_identifier (Ptr, Start, (CONST CHAR8 *)SignerInfo->SigAlgIdentifier.p, SignerInfo->SigAlgIdentifier.len, 0));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_algorithm_identifier (Ptr, Start, (CONST CHAR8 *)SignerInfo->AlgIdentifier.p, SignerInfo->AlgIdentifier.len, 0));
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteIssuerAndSerialNumber (Ptr, Start, SignerInfo->Serial.p, SignerInfo->Serial.len, SignerInfo->IssuerRaw.p, SignerInfo->IssuerRaw.len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_int (Ptr, Start, SignerInfo->Version));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
return Len;
}
/**
write Pkcs7 Signers Info Set.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] SignersSet SignerInfo Set.
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteSignersInfoSet (
UINT8 **Ptr,
UINT8 *Start,
MbedtlsPkcs7SignerInfo *SignersSet
)
{
MbedtlsPkcs7SignerInfo *SignerInfo;
INT32 Ret;
INT32 Len;
SignerInfo = SignersSet;
Len = 0;
while (SignerInfo != NULL) {
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteSignerInfo (Ptr, Start, SignerInfo));
// move to next
SignerInfo = SignerInfo->Next;
}
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET));
return Len;
}
/**
Signed Data Type
SignedData ::= SEQUENCE {
version Version,
digestAlgorithms DigestAlgorithmIdentifiers,
contentInfo ContentInfo,
certificates
[0] IMPLICIT ExtendedCertificatesAndCertificates
OPTIONAL,
crls
[1] IMPLICIT CertificateRevocationLists OPTIONAL,
signerInfos SignerInfos }
DigestAlgorithmIdentifiers ::=
SET OF DigestAlgorithmIdentifier
SignerInfos ::= SET OF SignerInfo.
@param[in, out] Ptr The reference to the current position pointer.
@param[in] Start The start of the buffer, for bounds-checking.
@param[in] Pkcs7 MbedtlsPkcs7
@retval number The number of bytes written to p on success.
@retval negative A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7WriteDer (
UINT8 **Ptr,
UINT8 *Start,
MbedtlsPkcs7 *Pkcs7
)
{
INT32 Ret;
INT32 Len;
mbedtls_md_type_t DigestAlg[1];
DigestAlg[0] = MBEDTLS_MD_SHA256;
Len = 0;
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteSignersInfoSet (Ptr, Start, &(Pkcs7->SignedData.SignerInfos)));
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteCertificates (Ptr, Start, &(Pkcs7->SignedData.Certificates), Pkcs7->SignedData.Certificates.next));
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteContentInfo (Ptr, Start, NULL, 0));
EDKII_ASN1_CHK_ADD (Len, MbedTlsPkcs7WriteDigestAlgorithmSet (Ptr, Start, DigestAlg, 1));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_int (Ptr, Start, Pkcs7->SignedData.Version));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_len (Ptr, Start, Len));
EDKII_ASN1_CHK_ADD (Len, mbedtls_asn1_write_tag (Ptr, Start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
return Len;
}
/**
Creates a PKCS#7 signedData as described in "PKCS #7: Cryptographic Message
Syntax Standard, version 1.5". This interface is only intended to be used for
application to perform PKCS#7 functionality validation.
If this interface is not supported, then return FALSE.
@param[in] PrivateKey Pointer to the PEM-formatted private key data for
data signing.
@param[in] PrivateKeySize Size of the PEM private key data in bytes.
@param[in] KeyPassword NULL-terminated passphrase used for encrypted PEM
key data.
@param[in] InData Pointer to the content to be signed.
@param[in] InDataSize Size of InData in bytes.
@param[in] SignCert Pointer to signer's DER-encoded certificate to sign with.
@param[in] OtherCerts Pointer to an optional additional set of certificates to
include in the PKCS#7 signedData (e.g. any intermediate
CAs in the chain).
@param[out] SignedData Pointer to output PKCS#7 signedData. It's caller's
responsibility to free the buffer with FreePool().
@param[out] SignedDataSize Size of SignedData in bytes.
@retval TRUE PKCS#7 data signing succeeded.
@retval FALSE PKCS#7 data signing failed.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
Pkcs7Sign (
IN CONST UINT8 *PrivateKey,
IN UINTN PrivateKeySize,
IN CONST UINT8 *KeyPassword,
IN UINT8 *InData,
IN UINTN InDataSize,
IN UINT8 *SignCert,
IN UINT8 *OtherCerts OPTIONAL,
OUT UINT8 **SignedData,
OUT UINTN *SignedDataSize
)
{
BOOLEAN Status;
INT32 Ret;
mbedtls_pk_context Pkey;
UINT8 HashValue[SHA256_DIGEST_SIZE];
UINT8 Signature[MAX_SIGNATURE_SIZE];
UINTN SignatureLen;
UINT8 *NewPrivateKey;
mbedtls_x509_crt *Crt;
MbedtlsPkcs7 Pkcs7;
MbedtlsPkcs7SignerInfo SignerInfo;
UINT8 *Buffer;
INTN BufferSize;
UINT8 *Ptr;
INT32 Len;
//
// Check input parameters.
//
if ((PrivateKey == NULL) || (KeyPassword == NULL) || (InData == NULL) ||
(SignCert == NULL) || (SignedData == NULL) || (SignedDataSize == NULL) || (InDataSize > INT_MAX))
{
return FALSE;
}
BufferSize = 4096;
SignatureLen = MAX_SIGNATURE_SIZE;
Crt = (mbedtls_x509_crt *)SignCert;
NewPrivateKey = NULL;
if (PrivateKey[PrivateKeySize - 1] != 0) {
NewPrivateKey = AllocateZeroPool (PrivateKeySize + 1);
if (NewPrivateKey == NULL) {
return FALSE;
}
CopyMem (NewPrivateKey, PrivateKey, PrivateKeySize);
NewPrivateKey[PrivateKeySize] = 0;
PrivateKeySize++;
} else {
NewPrivateKey = AllocateZeroPool (PrivateKeySize);
if (NewPrivateKey == NULL) {
return FALSE;
}
CopyMem (NewPrivateKey, PrivateKey, PrivateKeySize);
}
mbedtls_pk_init (&Pkey);
Ret = mbedtls_pk_parse_key (
&Pkey,
NewPrivateKey,
PrivateKeySize,
KeyPassword,
KeyPassword == NULL ? 0 : AsciiStrLen ((CONST CHAR8 *)KeyPassword),
NULL,
NULL
);
if (Ret != 0) {
Status = FALSE;
goto Cleanup;
}
/// Calculate InData Digest
ZeroMem (HashValue, SHA256_DIGEST_SIZE);
Status = Sha256HashAll (InData, InDataSize, HashValue);
if (!Status) {
goto Cleanup;
}
/// Pk Sign
ZeroMem (Signature, MAX_SIGNATURE_SIZE);
Ret = mbedtls_pk_sign (
&Pkey,
MBEDTLS_MD_SHA256,
HashValue,
SHA256_DIGEST_SIZE,
Signature,
MAX_SIGNATURE_SIZE,
&SignatureLen,
MbedtlsRand,
NULL
);
if (Ret != 0) {
Status = FALSE;
goto Cleanup;
}
ZeroMem (&Pkcs7, sizeof (MbedtlsPkcs7));
Pkcs7.SignedData.Version = 1;
Crt->next = (mbedtls_x509_crt *)OtherCerts;
Pkcs7.SignedData.Certificates = *Crt;
SignerInfo.Next = NULL;
SignerInfo.Sig.p = Signature;
SignerInfo.Sig.len = SignatureLen;
SignerInfo.Version = 1;
SignerInfo.AlgIdentifier.p = MbedtlsOidDigestAlgSha256;
SignerInfo.AlgIdentifier.len = sizeof (MBEDTLS_OID_DIGEST_ALG_SHA256) - 1;
if (mbedtls_pk_get_type (&Pkey) == MBEDTLS_PK_RSA) {
SignerInfo.SigAlgIdentifier.p = MbedtlsOidPkcs1Rsa;
SignerInfo.SigAlgIdentifier.len = sizeof (MBEDTLS_OID_PKCS1_RSA) - 1;
} else {
Ret = mbedtls_oid_get_oid_by_sig_alg (MBEDTLS_PK_ECDSA, MBEDTLS_MD_SHA256, (CONST CHAR8 **)&SignerInfo.SigAlgIdentifier.p, &SignerInfo.SigAlgIdentifier.len);
if (Ret != 0) {
Status = FALSE;
goto Cleanup;
}
}
SignerInfo.Serial = ((mbedtls_x509_crt *)SignCert)->serial;
SignerInfo.IssuerRaw = ((mbedtls_x509_crt *)SignCert)->issuer_raw;
Pkcs7.SignedData.SignerInfos = SignerInfo;
Buffer = AllocateZeroPool (BufferSize);
if (Buffer == NULL) {
Status = FALSE;
goto Cleanup;
}
Ptr = Buffer + BufferSize;
Len = MbedTlsPkcs7WriteDer (&Ptr, Buffer, &Pkcs7);
/// Enlarge buffer if buffer is too small
while (Len == MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) {
BufferSize = BufferSize * 2;
Ptr = Buffer + BufferSize;
FreePool (Buffer);
Buffer = AllocateZeroPool (BufferSize);
if (Buffer == NULL) {
Status = FALSE;
goto Cleanup;
}
Ptr = Buffer + BufferSize;
Len = MbedTlsPkcs7WriteDer (&Ptr, Buffer, &Pkcs7);
}
if (Len <= 0) {
Status = FALSE;
goto Cleanup;
}
*SignedData = AllocateZeroPool (Len);
if (*SignedData == NULL) {
Status = FALSE;
goto Cleanup;
}
*SignedDataSize = Len;
CopyMem (*SignedData, Ptr, Len);
Status = TRUE;
Cleanup:
if (&Pkey != NULL) {
mbedtls_pk_free (&Pkey);
}
if (NewPrivateKey != NULL) {
memset (NewPrivateKey, 0, PrivateKeySize);
FreePool (NewPrivateKey);
}
if (Buffer != NULL) {
memset (Buffer, 0, BufferSize);
FreePool (Buffer);
}
return Status;
}

View File

@ -1,113 +0,0 @@
/** @file
Non-runtime specific implementation of PKCS#7 SignedData Verification Wrapper.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/pkcs7.h>
/**
Extracts the attached content from a PKCS#7 signed data if existed. The input signed
data could be wrapped in a ContentInfo structure.
If P7Data, Content, or ContentSize is NULL, then return FALSE. If P7Length overflow,
then return FALSE. If the P7Data is not correctly formatted, then return FALSE.
Caution: This function may receive untrusted input. So this function will do
basic check for PKCS#7 data structure.
@param[in] P7Data Pointer to the PKCS#7 signed data to process.
@param[in] P7Length Length of the PKCS#7 signed data in bytes.
@param[out] Content Pointer to the extracted content from the PKCS#7 signedData.
It's caller's responsibility to free the buffer with FreePool().
@param[out] ContentSize The size of the extracted content in bytes.
@retval TRUE The P7Data was correctly formatted for processing.
@retval FALSE The P7Data was not correctly formatted for processing.
**/
BOOLEAN
EFIAPI
Pkcs7GetAttachedContent (
IN CONST UINT8 *P7Data,
IN UINTN P7Length,
OUT VOID **Content,
OUT UINTN *ContentSize
)
{
BOOLEAN Status;
UINT8 *SignedData;
UINTN SignedDataSize;
BOOLEAN Wrapped;
INTN Ret;
mbedtls_pkcs7 Pkcs7;
mbedtls_pkcs7_data *MbedtlsContent;
mbedtls_pkcs7_init (&Pkcs7);
//
// Check input parameter.
//
if ((P7Data == NULL) || (P7Length > INT_MAX) || (Content == NULL) || (ContentSize == NULL)) {
return FALSE;
}
*Content = NULL;
SignedData = NULL;
Status = WrapPkcs7Data (P7Data, P7Length, &Wrapped, &SignedData, &SignedDataSize);
if (!Status || (SignedDataSize > INT_MAX)) {
goto _Exit;
}
Status = FALSE;
Ret = mbedtls_pkcs7_parse_der (&Pkcs7, SignedData, (INT32)SignedDataSize);
//
// The type of Pkcs7 must be signedData
//
if (Ret != MBEDTLS_PKCS7_SIGNED_DATA) {
goto _Exit;
}
//
// Check for detached or attached content
//
MbedtlsContent = &(Pkcs7.signed_data.content);
if (MbedtlsContent == NULL) {
//
// No Content supplied for PKCS7 detached signedData
//
*Content = NULL;
*ContentSize = 0;
} else {
//
// Retrieve the attached content in PKCS7 signedData
//
if ((MbedtlsContent->data.len > 0) && (MbedtlsContent->data.p != NULL)) {
*ContentSize = MbedtlsContent->data.len;
*Content = AllocateZeroPool (*ContentSize);
if (*Content == NULL) {
*ContentSize = 0;
goto _Exit;
}
CopyMem (*Content, MbedtlsContent->data.p, *ContentSize);
}
}
Status = TRUE;
_Exit:
//
// Release Resources
//
mbedtls_pkcs7_free (&Pkcs7);
return Status;
}

View File

@ -1,689 +0,0 @@
/** @file
This module verifies that Enhanced Key Usages (EKU's) are present within
a PKCS7 signature blob using MbedTLS.
Copyright (C) Microsoft Corporation. All Rights Reserved.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Base.h>
#include "InternalCryptLib.h"
#include <mbedtls/pkcs7.h>
#include <mbedtls/asn1write.h>
GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 EkuOID[] = { 0x55, 0x1D, 0x25 };
/*leaf Cert basic_constraints case1: CA: false and CA object is excluded */
GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gBasicConstraintsCase1[] = { 0x30, 0x00 };
/*leaf Cert basic_constraints case2: CA: false */
GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gBasicConstraintsCase2[] = { 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01, 0x00 };
GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gOidBasicConstraints[] = { 0x55, 0x1D, 0x13 };
/**
Find first Extension data match with given OID
@param[in] Start Pointer to the DER-encoded extensions data
@param[in] End extensions data size in bytes
@param[in ] Oid OID for match
@param[in ] OidSize OID size in bytes
@param[out] FindExtensionData output matched extension data.
@param[out] FindExtensionDataLen matched extension data size.
**/
STATIC
BOOLEAN
InternalX509FindExtensionData (
UINT8 *Start,
UINT8 *End,
CONST UINT8 *Oid,
UINTN OidSize,
UINT8 **FindExtensionData,
UINTN *FindExtensionDataLen
)
{
UINT8 *Ptr;
UINT8 *ExtensionPtr;
UINTN ObjLen;
INT32 Ret;
BOOLEAN Status;
UINTN FindExtensionLen;
UINTN HeaderLen;
/*If no Extension entry match Oid*/
Status = FALSE;
Ptr = Start;
Ret = 0;
while (TRUE) {
//
// Extension ::= SEQUENCE {
// extnID OBJECT IDENTIFIER,
// critical BOOLEAN DEFAULT FALSE,
// extnValue OCTET STRING }
//
ExtensionPtr = Ptr;
Ret = mbedtls_asn1_get_tag (
&Ptr,
End,
&ObjLen,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE
);
if (Ret == 0) {
HeaderLen = (UINTN)(Ptr - ExtensionPtr);
FindExtensionLen = ObjLen;
/* Get Object Identifier*/
Ret = mbedtls_asn1_get_tag (
&Ptr,
End,
&ObjLen,
MBEDTLS_ASN1_OID
);
} else {
break;
}
if ((Ret == 0) && !CompareMem (Ptr, Oid, OidSize)) {
Ptr += ObjLen;
Ret = mbedtls_asn1_get_tag (
&Ptr,
End,
&ObjLen,
MBEDTLS_ASN1_BOOLEAN
);
if (Ret == 0) {
Ptr += ObjLen;
}
Ret = mbedtls_asn1_get_tag (
&Ptr,
End,
&ObjLen,
MBEDTLS_ASN1_OCTET_STRING
);
} else {
Ret = 1;
}
if (Ret == 0) {
*FindExtensionData = Ptr;
*FindExtensionDataLen = ObjLen;
Status = TRUE;
break;
}
/* move to next*/
Ptr = ExtensionPtr + HeaderLen + FindExtensionLen;
Ret = 0;
}
return Status;
}
/**
Retrieve Extension data from one X.509 certificate.
@param[in] Cert Pointer to the X509 certificate.
@param[in] Oid Object identifier buffer
@param[in] OidSize Object identifier buffer size
@param[out] ExtensionData Extension bytes.
@param[in, out] ExtensionDataSize Extension bytes size.
@retval RETURN_SUCCESS The certificate Extension data retrieved successfully.
@retval RETURN_INVALID_PARAMETER If Cert is NULL.
If ExtensionDataSize is NULL.
If ExtensionData is not NULL and *ExtensionDataSize is 0.
If Certificate is invalid.
@retval RETURN_NOT_FOUND If no Extension entry match Oid.
@retval RETURN_BUFFER_TOO_SMALL If the ExtensionData is NULL. The required buffer size
is returned in the ExtensionDataSize parameter.
@retval RETURN_UNSUPPORTED The operation is not supported.
**/
STATIC
BOOLEAN
GetExtensionData (
CONST mbedtls_x509_crt *Cert,
CONST UINT8 *Oid,
UINTN OidSize,
UINT8 *ExtensionData,
UINTN *ExtensionDataSize
)
{
CONST mbedtls_x509_crt *Crt;
INT32 Ret;
BOOLEAN Status;
UINT8 *Ptr;
UINT8 *End;
UINTN ObjLen;
Ptr = NULL;
End = NULL;
ObjLen = 0;
if ((Cert == NULL) || (Oid == NULL) || (OidSize == 0) ||
(ExtensionDataSize == NULL))
{
return FALSE;
}
Status = FALSE;
Crt = Cert;
Ptr = Crt->v3_ext.p;
End = Crt->v3_ext.p + Crt->v3_ext.len;
Ret = mbedtls_asn1_get_tag (
&Ptr,
End,
&ObjLen,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE
);
if (Ret == 0) {
Status = InternalX509FindExtensionData (
Ptr,
End,
Oid,
OidSize,
&Ptr,
&ObjLen
);
}
if (Status) {
if (*ExtensionDataSize < ObjLen) {
*ExtensionDataSize = ObjLen;
Status = FALSE;
goto Cleanup;
}
if (Oid != NULL) {
if (ExtensionData == NULL) {
return FALSE;
}
CopyMem (ExtensionData, Ptr, ObjLen);
}
*ExtensionDataSize = ObjLen;
} else {
*ExtensionDataSize = 0;
}
Cleanup:
return Status;
}
/**
Determines if the specified EKU represented in ASN1 form is present
in a given certificate.
@param[in] Cert The certificate to check.
@param[in] EKU The EKU to look for.
@param[in] EkuLen The size of EKU.
@retval EFI_SUCCESS We successfully identified the signing type.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_NOT_FOUND One or more EKU's were not found in the signature.
**/
STATIC
EFI_STATUS
IsEkuInCertificate (
IN CONST mbedtls_x509_crt *Cert,
IN UINT8 *EKU,
IN UINTN EkuLen
)
{
EFI_STATUS Status;
BOOLEAN Ret;
UINT8 *Buffer;
UINTN Index;
UINTN Len;
if ((Cert == NULL) || (EKU == NULL)) {
Status = EFI_INVALID_PARAMETER;
return Status;
}
Len = 0;
Buffer = NULL;
Ret = GetExtensionData (
Cert,
(CONST UINT8 *)EkuOID,
sizeof (EkuOID),
NULL,
&Len
);
if (Len == 0) {
Status = EFI_NOT_FOUND;
goto Exit;
}
Buffer = AllocateZeroPool (Len);
if (Buffer == NULL) {
Status = EFI_NOT_FOUND;
goto Exit;
}
Ret = GetExtensionData (
Cert,
(CONST UINT8 *)EkuOID,
sizeof (EkuOID),
Buffer,
&Len
);
if ((Len == 0) || (!Ret)) {
Status = EFI_NOT_FOUND;
goto Exit;
}
Status = EFI_NOT_FOUND;
/*find the spdm hardware identity OID*/
for (Index = 0; Index <= Len - EkuLen; Index++) {
if (!CompareMem (Buffer + Index, EKU, EkuLen)) {
// check sub EKU
if (Index == Len - EkuLen) {
Status = EFI_SUCCESS;
break;
// Ensure that the OID is complete
} else if (Buffer[Index + EkuLen] == 0x06) {
Status = EFI_SUCCESS;
break;
} else {
break;
}
}
}
Exit:
if (Buffer != NULL) {
FreePool (Buffer);
}
return Status;
}
/**
Get OID from txt.
@param[in] RequiredEKUs Array of null-terminated strings listing OIDs of
required EKUs that must be present in the signature.
@param[in] RequiredEKUsSize Number of elements in the RequiredEKUs string array.
@param[in,out] CheckOid OID.
@param[out] OidLen The size of OID.
**/
VOID
GetOidFromTxt (
IN CONST CHAR8 *RequiredEKUs,
IN UINTN RequiredEKUsSize,
IN OUT UINT8 *CheckOid,
OUT UINT8 *OidLen
)
{
UINT8 *Ptr;
UINT16 Index;
UINT32 Data;
UINT8 OidIndex;
UINTN EKUsSize;
EKUsSize = RequiredEKUsSize;
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier?redirectedfrom=MSDN
CheckOid[0] = (UINT8)((RequiredEKUs[0] - '0') * 40 + (RequiredEKUs[2] - '0'));
EKUsSize = EKUsSize - 4;
Ptr = (UINT8 *)(RequiredEKUs + 4);
OidIndex = 1;
while (EKUsSize) {
Index = 0;
Data = 0;
while ((*Ptr != '.') && (*Ptr != '\0')) {
Index++;
Ptr++;
EKUsSize--;
}
while (Index) {
Data = 10 * Data + (*(Ptr - Index) - '0');
Index--;
}
if (EKUsSize != 0) {
Ptr++;
EKUsSize--;
}
if (Data < 128) {
CheckOid[OidIndex] = (UINT8)Data;
OidIndex++;
} else {
CheckOid[OidIndex + 1] = (UINT8)(Data & 0xFF);
CheckOid[OidIndex] = (UINT8)(((((Data & 0xFF00) << 1) | 0x8000) >> 8) & 0xFF);
OidIndex = OidIndex + 2;
}
}
*OidLen = OidIndex;
}
/**
Verify the Cert is signer cert
@param[in] Start Pointer to the DER-encoded certificate data Start.
@param[in] End Pointer to the DER-encoded certificate data End.
@retval true verify pass
@retval false verify fail
**/
STATIC
BOOLEAN
IsCertSignerCert (
UINT8 *Start,
UINT8 *End
)
{
BOOLEAN Status;
UINT8 *Buffer;
UINTN Len;
mbedtls_x509_crt Cert;
UINTN ObjLen;
mbedtls_x509_crt_init (&Cert);
ObjLen = End - Start;
if (mbedtls_x509_crt_parse_der (&Cert, Start, ObjLen) != 0) {
return FALSE;
}
Len = 0;
Buffer = NULL;
Status = GetExtensionData (
&Cert,
(CONST UINT8 *)gOidBasicConstraints,
sizeof (gOidBasicConstraints),
NULL,
&Len
);
if (Len == 0) {
/* basic constraints is not present in Cert */
return TRUE;
}
Buffer = AllocateZeroPool (Len);
if (Buffer == NULL) {
return FALSE;
}
Status = GetExtensionData (
&Cert,
(CONST UINT8 *)gOidBasicConstraints,
sizeof (gOidBasicConstraints),
Buffer,
&Len
);
if (Len == 0) {
/* basic constraints is not present in Cert */
Status = TRUE;
goto Exit;
} else if (!Status) {
Status = FALSE;
goto Exit;
}
if ((Len == sizeof (gBasicConstraintsCase1)) &&
(!CompareMem (Buffer, gBasicConstraintsCase1, sizeof (gBasicConstraintsCase1))))
{
Status = TRUE;
goto Exit;
}
if ((Len == sizeof (gBasicConstraintsCase2)) &&
(!CompareMem (Buffer, gBasicConstraintsCase2, sizeof (gBasicConstraintsCase2))))
{
Status = TRUE;
goto Exit;
}
Status = FALSE;
Exit:
mbedtls_x509_crt_free (&Cert);
if (Buffer != NULL) {
FreePool (Buffer);
}
return Status;
}
/**
Determines if the specified EKUs are present in a signing certificate.
@param[in] SignerCert The certificate to check.
@param[in] RequiredEKUs The EKUs to look for.
@param[in] RequiredEKUsSize The number of EKUs
@param[in] RequireAllPresent If TRUE, then all the specified EKUs
must be present in the certificate.
@retval EFI_SUCCESS We successfully identified the signing type.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_NOT_FOUND One or more EKU's were not found in the signature.
**/
STATIC
EFI_STATUS
CheckEKUs (
IN CONST mbedtls_x509_crt *SignerCert,
IN CONST CHAR8 *RequiredEKUs[],
IN CONST UINT32 RequiredEKUsSize,
IN BOOLEAN RequireAllPresent
)
{
EFI_STATUS Status;
UINT32 NumEkusFound;
UINT32 Index;
UINT8 *EKU;
UINTN EkuLen;
UINT8 CheckOid[20];
UINT8 OidLen;
Status = EFI_SUCCESS;
NumEkusFound = 0;
if ((SignerCert == NULL) || (RequiredEKUs == NULL) || (RequiredEKUsSize == 0)) {
Status = EFI_INVALID_PARAMETER;
goto Exit;
}
for (Index = 0; Index < RequiredEKUsSize; Index++) {
//
// Finding required EKU in Cert.
//
GetOidFromTxt (RequiredEKUs[Index], strlen (RequiredEKUs[Index]), CheckOid, &OidLen);
EKU = CheckOid;
EkuLen = OidLen;
Status = IsEkuInCertificate (SignerCert, EKU, EkuLen);
if (Status == EFI_SUCCESS) {
NumEkusFound++;
if (!RequireAllPresent) {
//
// Found at least one, so we are done.
//
goto Exit;
}
} else {
//
// Fail to find Eku in Cert
break;
}
}
Exit:
if (RequireAllPresent &&
(NumEkusFound == RequiredEKUsSize))
{
//
// Found all required EKUs in certificate.
//
Status = EFI_SUCCESS;
}
return Status;
}
/**
This function receives a PKCS#7 formatted signature blob,
looks for the EKU SEQUENCE blob, and if found then looks
for all the required EKUs. This function was created so that
the Surface team can cut down on the number of Certificate
Authorities (CA's) by checking EKU's on leaf signers for
a specific product. This prevents one product's certificate
from signing another product's firmware or unlock blobs.
Note that this function does not validate the certificate chain.
That needs to be done before using this function.
@param[in] Pkcs7Signature The PKCS#7 signed information content block. An array
containing the content block with both the signature,
the signer's certificate, and any necessary intermediate
certificates.
@param[in] Pkcs7SignatureSize Number of bytes in Pkcs7Signature.
@param[in] RequiredEKUs Array of null-terminated strings listing OIDs of
required EKUs that must be present in the signature.
@param[in] RequiredEKUsSize Number of elements in the RequiredEKUs string array.
@param[in] RequireAllPresent If this is TRUE, then all of the specified EKU's
must be present in the leaf signer. If it is
FALSE, then we will succeed if we find any
of the specified EKU's.
@retval EFI_SUCCESS The required EKUs were found in the signature.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_NOT_FOUND One or more EKU's were not found in the signature.
**/
EFI_STATUS
EFIAPI
VerifyEKUsInPkcs7Signature (
IN CONST UINT8 *Pkcs7Signature,
IN CONST UINT32 SignatureSize,
IN CONST CHAR8 *RequiredEKUs[],
IN CONST UINT32 RequiredEKUsSize,
IN BOOLEAN RequireAllPresent
)
{
EFI_STATUS Status;
mbedtls_x509_crt Cert;
UINT8 *Ptr;
UINT8 *End;
INT32 Len;
UINTN ObjLen;
UINT8 *OldEnd;
//
// Check input parameter.
//
if ((RequiredEKUs == NULL) || (Pkcs7Signature == NULL)) {
Status = EFI_INVALID_PARAMETER;
return Status;
}
mbedtls_x509_crt_init (&Cert);
Ptr = (UINT8 *)(UINTN)Pkcs7Signature;
Len = (UINT32)SignatureSize;
End = Ptr + Len;
// Cert
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// tbscert
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// signature algo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
Ptr += ObjLen;
// signature
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
OldEnd = Ptr;
// Cert
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
End = Ptr + ObjLen;
// leaf Cert
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
while ((Ptr != End) && (Ptr < End)) {
if (IsCertSignerCert (OldEnd, Ptr)) {
break;
}
OldEnd = Ptr;
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
}
if (Ptr != End) {
return FALSE;
} else {
Ptr = End - ObjLen;
}
// leaf Cert
ObjLen += Ptr - OldEnd;
Ptr = OldEnd;
if (mbedtls_x509_crt_parse_der (&Cert, Ptr, ObjLen) != 0) {
return FALSE;
}
Status = CheckEKUs (&Cert, RequiredEKUs, RequiredEKUsSize, RequireAllPresent);
if (Status != EFI_SUCCESS) {
goto Exit;
}
Exit:
//
// Release Resources
//
mbedtls_x509_crt_free (&Cert);
return Status;
}

View File

@ -1,352 +0,0 @@
/** @file
RSA Asymmetric Cipher Wrapper Implementation over MbedTLS.
This file implements following APIs which provide more capabilities for RSA:
1) RsaGetKey
2) RsaGenerateKey
3) RsaCheckKey
4) RsaPkcs1Sign
RFC 8017 - PKCS #1: RSA Cryptography Specifications Version 2.2
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/rsa.h>
/**
Gets the tag-designated RSA key component from the established RSA context.
This function retrieves the tag-designated RSA key component from the
established RSA context as a non-negative integer (octet string format
represented in RSA PKCS#1).
If specified key component has not been set or has been cleared, then returned
BnSize is set to 0.
If the BigNumber buffer is too small to hold the contents of the key, FALSE
is returned and BnSize is set to the required buffer size to obtain the key.
If RsaContext is NULL, then return FALSE.
If BnSize is NULL, then return FALSE.
If BnSize is large enough but BigNumber is NULL, then return FALSE.
@param[in, out] RsaContext Pointer to RSA context being set.
@param[in] KeyTag Tag of RSA key component being set.
@param[out] BigNumber Pointer to octet integer buffer.
@param[in, out] BnSize On input, the size of big number buffer in bytes.
On output, the size of data returned in big number buffer in bytes.
@retval TRUE RSA key component was retrieved successfully.
@retval FALSE Invalid RSA key component tag.
@retval FALSE BnSize is too small.
**/
BOOLEAN
EFIAPI
RsaGetKey (
IN OUT VOID *RsaContext,
IN RSA_KEY_TAG KeyTag,
OUT UINT8 *BigNumber,
IN OUT UINTN *BnSize
)
{
mbedtls_rsa_context *RsaKey;
INT32 Ret;
mbedtls_mpi Value;
UINTN Size;
//
// Check input parameters.
//
if ((RsaContext == NULL) || (*BnSize > INT_MAX)) {
return FALSE;
}
//
// Init mbedtls_mpi
//
mbedtls_mpi_init (&Value);
Size = *BnSize;
*BnSize = 0;
RsaKey = (mbedtls_rsa_context *)RsaContext;
switch (KeyTag) {
case RsaKeyN:
Ret = mbedtls_rsa_export (RsaKey, &Value, NULL, NULL, NULL, NULL);
break;
case RsaKeyE:
Ret = mbedtls_rsa_export (RsaKey, NULL, NULL, NULL, NULL, &Value);
break;
case RsaKeyD:
Ret = mbedtls_rsa_export (RsaKey, NULL, NULL, NULL, &Value, NULL);
break;
case RsaKeyQ:
Ret = mbedtls_rsa_export (RsaKey, NULL, NULL, &Value, NULL, NULL);
break;
case RsaKeyP:
Ret = mbedtls_rsa_export (RsaKey, NULL, &Value, NULL, NULL, NULL);
break;
case RsaKeyDp:
case RsaKeyDq:
case RsaKeyQInv:
default:
Ret = -1;
break;
}
if (Ret != 0) {
goto End;
}
if (mbedtls_mpi_size (&Value) == 0) {
Ret = 0;
goto End;
}
*BnSize = Size;
Size = mbedtls_mpi_size (&Value);
if (*BnSize < Size) {
Ret = 1;
*BnSize = Size;
goto End;
}
if (BigNumber == NULL) {
Ret = 0;
*BnSize = Size;
goto End;
}
if ((BigNumber != NULL) && (Ret == 0)) {
Ret = mbedtls_mpi_write_binary (&Value, BigNumber, Size);
*BnSize = Size;
}
End:
mbedtls_mpi_free (&Value);
return Ret == 0;
}
/**
Generates RSA key components.
This function generates RSA key components. It takes RSA public exponent Pe and
length in bits of RSA modulus N as input, and generates all key components.
If PublicExponent is NULL, the default RSA public exponent (0x10001) will be used.
Before this function can be invoked, pseudorandom number generator must be correctly
initialized by RandomSeed().
If RsaContext is NULL, then return FALSE.
@param[in, out] RsaContext Pointer to RSA context being set.
@param[in] ModulusLength Length of RSA modulus N in bits.
@param[in] PublicExponent Pointer to RSA public exponent.
@param[in] PublicExponentSize Size of RSA public exponent buffer in bytes.
@retval TRUE RSA key component was generated successfully.
@retval FALSE Invalid RSA key component tag.
**/
BOOLEAN
EFIAPI
RsaGenerateKey (
IN OUT VOID *RsaContext,
IN UINTN ModulusLength,
IN CONST UINT8 *PublicExponent,
IN UINTN PublicExponentSize
)
{
INT32 Ret;
mbedtls_rsa_context *Rsa;
INT32 Pe;
//
// Check input parameters.
//
if ((RsaContext == NULL) || (ModulusLength > INT_MAX) || (PublicExponentSize > INT_MAX)) {
return FALSE;
}
Rsa = (mbedtls_rsa_context *)RsaContext;
if (PublicExponent == NULL) {
Pe = 0x10001;
} else {
if (PublicExponentSize == 0) {
return FALSE;
}
switch (PublicExponentSize) {
case 1:
Pe = PublicExponent[0];
break;
case 2:
Pe = PublicExponent[0] << 8 | PublicExponent[1];
break;
case 3:
Pe = PublicExponent[0] << 16 | PublicExponent[1] << 8 |
PublicExponent[2];
break;
case 4:
Pe = PublicExponent[0] << 24 | PublicExponent[1] << 16 |
PublicExponent[2] << 8 | PublicExponent[3];
break;
default:
return FALSE;
}
}
Ret = mbedtls_rsa_gen_key (
Rsa,
MbedtlsRand,
NULL,
(UINT32)ModulusLength,
Pe
);
return Ret == 0;
}
/**
Validates key components of RSA context.
NOTE: This function performs integrity checks on all the RSA key material, so
the RSA key structure must contain all the private key data.
This function validates key components of RSA context in following aspects:
- Whether p is a prime
- Whether q is a prime
- Whether n = p * q
- Whether d*e = 1 mod lcm(p-1,q-1)
If RsaContext is NULL, then return FALSE.
@param[in] RsaContext Pointer to RSA context to check.
@retval TRUE RSA key components are valid.
@retval FALSE RSA key components are not valid.
**/
BOOLEAN
EFIAPI
RsaCheckKey (
IN VOID *RsaContext
)
{
if (RsaContext == NULL) {
return FALSE;
}
UINT32 Ret;
Ret = mbedtls_rsa_complete (RsaContext);
if (Ret == 0) {
Ret = mbedtls_rsa_check_privkey (RsaContext);
}
return Ret == 0;
}
/**
Carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme.
This function carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme defined in
RSA PKCS#1.
If the Signature buffer is too small to hold the contents of signature, FALSE
is returned and SigSize is set to the required buffer size to obtain the signature.
If RsaContext is NULL, then return FALSE.
If MessageHash is NULL, then return FALSE.
If HashSize is not equal to the size of MD5, SHA-1, SHA-256, SHA-384 or SHA-512 digest, then return FALSE.
If SigSize is large enough but Signature is NULL, then return FALSE.
@param[in] RsaContext Pointer to RSA context for signature generation.
@param[in] MessageHash Pointer to octet message hash to be signed.
@param[in] HashSize Size of the message hash in bytes.
@param[out] Signature Pointer to buffer to receive RSA PKCS1-v1_5 signature.
@param[in, out] SigSize On input, the size of Signature buffer in bytes.
On output, the size of data returned in Signature buffer in bytes.
@retval TRUE Signature successfully generated in PKCS1-v1_5.
@retval FALSE Signature generation failed.
@retval FALSE SigSize is too small.
**/
BOOLEAN
EFIAPI
RsaPkcs1Sign (
IN VOID *RsaContext,
IN CONST UINT8 *MessageHash,
IN UINTN HashSize,
OUT UINT8 *Signature,
IN OUT UINTN *SigSize
)
{
INT32 Ret;
mbedtls_md_type_t MdAlg;
if ((RsaContext == NULL) || (MessageHash == NULL)) {
return FALSE;
}
if (mbedtls_rsa_complete ((mbedtls_rsa_context *)RsaContext) != 0) {
return FALSE;
}
switch (HashSize) {
#ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
case SHA1_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA1;
break;
#endif
case SHA256_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA256;
break;
case SHA384_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA384;
break;
case SHA512_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA512;
break;
default:
return FALSE;
}
if (mbedtls_rsa_get_len (RsaContext) > *SigSize) {
*SigSize = mbedtls_rsa_get_len (RsaContext);
return FALSE;
}
if (Signature == NULL) {
return FALSE;
}
Ret = mbedtls_rsa_set_padding (RsaContext, MBEDTLS_RSA_PKCS_V15, MdAlg);
if (Ret != 0) {
return FALSE;
}
Ret = mbedtls_rsa_pkcs1_sign (
RsaContext,
MbedtlsRand,
NULL,
MdAlg,
(UINT32)HashSize,
MessageHash,
Signature
);
if (Ret != 0) {
return FALSE;
}
*SigSize = mbedtls_rsa_get_len (RsaContext);
return TRUE;
}

View File

@ -1,140 +0,0 @@
/** @file
RSA PSS Asymmetric Cipher Wrapper Implementation over MbedTLS.
This file implements following APIs which provide basic capabilities for RSA:
1) RsaPssSign
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/rsa.h>
#include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
/**
Carries out the RSA-SSA signature generation with EMSA-PSS encoding scheme.
This function carries out the RSA-SSA signature generation with EMSA-PSS encoding scheme defined in
RFC 8017.
Mask generation function is the same as the message digest algorithm.
If the Signature buffer is too small to hold the contents of signature, FALSE
is returned and SigSize is set to the required buffer size to obtain the signature.
If RsaContext is NULL, then return FALSE.
If Message is NULL, then return FALSE.
If MsgSize is zero or > INT_MAX, then return FALSE.
If DigestLen is NOT 32, 48 or 64, return FALSE.
If SaltLen is not equal to DigestLen, then return FALSE.
If SigSize is large enough but Signature is NULL, then return FALSE.
If this interface is not supported, then return FALSE.
@param[in] RsaContext Pointer to RSA context for signature generation.
@param[in] Message Pointer to octet message to be signed.
@param[in] MsgSize Size of the message in bytes.
@param[in] DigestLen Length of the digest in bytes to be used for RSA signature operation.
@param[in] SaltLen Length of the salt in bytes to be used for PSS encoding.
@param[out] Signature Pointer to buffer to receive RSA PSS signature.
@param[in, out] SigSize On input, the size of Signature buffer in bytes.
On output, the size of data returned in Signature buffer in bytes.
@retval TRUE Signature successfully generated in RSASSA-PSS.
@retval FALSE Signature generation failed.
@retval FALSE SigSize is too small.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
RsaPssSign (
IN VOID *RsaContext,
IN CONST UINT8 *Message,
IN UINTN MsgSize,
IN UINT16 DigestLen,
IN UINT16 SaltLen,
OUT UINT8 *Signature,
IN OUT UINTN *SigSize
)
{
INT32 Ret;
mbedtls_md_type_t MdAlg;
UINT8 HashValue[SHA512_DIGEST_SIZE];
if (RsaContext == NULL) {
return FALSE;
}
if (mbedtls_rsa_complete ((mbedtls_rsa_context *)RsaContext) != 0) {
return FALSE;
}
if ((Message == NULL) || (MsgSize == 0) || (MsgSize > INT_MAX)) {
return FALSE;
}
if (SaltLen != DigestLen) {
return FALSE;
}
ZeroMem (HashValue, DigestLen);
switch (DigestLen) {
case SHA256_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA256;
if (mbedtls_sha256 (Message, MsgSize, HashValue, FALSE) != 0) {
return FALSE;
}
break;
case SHA384_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA384;
if (mbedtls_sha512 (Message, MsgSize, HashValue, TRUE) != 0) {
return FALSE;
}
break;
case SHA512_DIGEST_SIZE:
MdAlg = MBEDTLS_MD_SHA512;
if (mbedtls_sha512 (Message, MsgSize, HashValue, FALSE) != 0) {
return FALSE;
}
break;
default:
return FALSE;
}
if (Signature == NULL) {
//
// If Signature is NULL, return safe SignatureSize
//
*SigSize = MBEDTLS_MPI_MAX_SIZE;
return FALSE;
}
Ret = mbedtls_rsa_set_padding (RsaContext, MBEDTLS_RSA_PKCS_V21, MdAlg);
if (Ret != 0) {
return FALSE;
}
Ret = mbedtls_rsa_rsassa_pss_sign (
RsaContext,
MbedtlsRand,
NULL,
MdAlg,
(UINT32)DigestLen,
HashValue,
Signature
);
if (Ret != 0) {
return FALSE;
}
*SigSize = ((mbedtls_rsa_context *)RsaContext)->len;
return TRUE;
}

View File

@ -1,381 +0,0 @@
/** @file
RFC3161 Timestamp Countersignature Verification Wrapper Implementation which does
not provide real capabilities.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <mbedtls/asn1.h>
//
// OID ASN.1 Value for SPC_RFC3161_OBJID ("1.3.6.1.4.1.311.3.3.1")
//
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 mSpcRFC3161OidValue[] = {
0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x03, 0x03, 0x01
};
/**
Convert ASN.1 GeneralizedTime to EFI Time.
@param[in] Ptr Pointer to the ASN.1 GeneralizedTime to be converted.
@param[out] EfiTime Return the corresponding EFI Time.
@retval TRUE The time conversion succeeds.
@retval FALSE Invalid parameters.
**/
STATIC
BOOLEAN
ConvertAsn1TimeToEfiTime (
IN UINT8 *Ptr,
OUT EFI_TIME *EfiTime
)
{
CONST CHAR8 *Str;
UINTN Index;
if ((Ptr == NULL) || (EfiTime == NULL)) {
return FALSE;
}
Str = (CONST CHAR8 *)Ptr;
SetMem (EfiTime, sizeof (EFI_TIME), 0);
Index = 0;
/* four digit year */
EfiTime->Year = (Str[Index++] - '0') * 1000;
EfiTime->Year += (Str[Index++] - '0') * 100;
EfiTime->Year += (Str[Index++] - '0') * 10;
EfiTime->Year += (Str[Index++] - '0');
if ((EfiTime->Year < 1900) || (EfiTime->Year > 9999)) {
return FALSE;
}
EfiTime->Month = (Str[Index++] - '0') * 10;
EfiTime->Month += (Str[Index++] - '0');
if ((EfiTime->Month < 1) || (EfiTime->Month > 12)) {
return FALSE;
}
EfiTime->Day = (Str[Index++] - '0') * 10;
EfiTime->Day += (Str[Index++] - '0');
if ((EfiTime->Day < 1) || (EfiTime->Day > 31)) {
return FALSE;
}
EfiTime->Hour = (Str[Index++] - '0') * 10;
EfiTime->Hour += (Str[Index++] - '0');
if (EfiTime->Hour > 23) {
return FALSE;
}
EfiTime->Minute = (Str[Index++] - '0') * 10;
EfiTime->Minute += (Str[Index++] - '0');
if (EfiTime->Minute > 59) {
return FALSE;
}
EfiTime->Second = (Str[Index++] - '0') * 10;
EfiTime->Second += (Str[Index++] - '0');
if (EfiTime->Second > 59) {
return FALSE;
}
/* Note: we did not adjust the time based on time zone information */
return TRUE;
}
/**
Verifies the validity of a RFC3161 Timestamp CounterSignature embedded in PE/COFF Authenticode
signature.
Return FALSE to indicate this interface is not supported.
@param[in] AuthData Pointer to the Authenticode Signature retrieved from signed
PE/COFF image to be verified.
@param[in] DataSize Size of the Authenticode Signature in bytes.
@param[in] TsaCert Pointer to a trusted/root TSA certificate encoded in DER, which
is used for TSA certificate chain verification.
@param[in] CertSize Size of the trusted certificate in bytes.
@param[out] SigningTime Return the time of timestamp generation time if the timestamp
signature is valid.
@retval FALSE This interface is not supported.
**/
BOOLEAN
EFIAPI
ImageTimestampVerify (
IN CONST UINT8 *AuthData,
IN UINTN DataSize,
IN CONST UINT8 *TsaCert,
IN UINTN CertSize,
OUT EFI_TIME *SigningTime
)
{
BOOLEAN Status;
UINT8 *Ptr;
UINT8 *End;
INT32 Len;
UINTN ObjLen;
UINT8 *TempPtr;
//
// Initializations
//
if (SigningTime != NULL) {
SetMem (SigningTime, sizeof (EFI_TIME), 0);
}
//
// Input Parameters Checking.
//
if ((AuthData == NULL) || (TsaCert == NULL)) {
return FALSE;
}
if ((DataSize > INT_MAX) || (CertSize > INT_MAX)) {
return FALSE;
}
Ptr = (UINT8 *)(UINTN)AuthData;
Len = (UINT32)DataSize;
End = Ptr + Len;
// ContentInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// ContentType
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Ptr += ObjLen;
// content
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
End = Ptr + ObjLen;
// signedData
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// version
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// digestAlgo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
Ptr += ObjLen;
// encapContentInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
// cert
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
Ptr += ObjLen;
TempPtr = Ptr;
// OPTIONAL CRLs
if (mbedtls_asn1_get_tag (&TempPtr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) == 0) {
Ptr = TempPtr + ObjLen;
}
// signerInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
// sub parse
// signerInfo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
End = Ptr + ObjLen;
// version
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// sid
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
// digestalgo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
// OPTIONAL AuthenticatedAttributes
TempPtr = Ptr;
if (mbedtls_asn1_get_tag (&TempPtr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) == 0) {
Ptr = TempPtr + ObjLen;
}
// signaturealgo
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
// signature
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OCTET_STRING) != 0) {
return FALSE;
}
Ptr += ObjLen;
// OPTIONAL UnauthenticatedAttributes
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, 0xA1) != 0) {
return FALSE;
}
// Attribute
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// type
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
if (CompareMem (Ptr, mSpcRFC3161OidValue, sizeof (mSpcRFC3161OidValue)) != 0) {
return FALSE;
}
Ptr += ObjLen;
// values
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
// values
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// signedData OID
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Ptr += ObjLen;
// [0]
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// integer
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// SET
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET) != 0) {
return FALSE;
}
Ptr += ObjLen;
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// tST OID
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Ptr += ObjLen;
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) != 0) {
return FALSE;
}
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OCTET_STRING) != 0) {
return FALSE;
}
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
// Integer
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// policy OID
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_OID) != 0) {
return FALSE;
}
Ptr += ObjLen;
// sequence
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) {
return FALSE;
}
Ptr += ObjLen;
// Integer
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_INTEGER) != 0) {
return FALSE;
}
Ptr += ObjLen;
// GeneralizedTime
if (mbedtls_asn1_get_tag (&Ptr, End, &ObjLen, MBEDTLS_ASN1_GENERALIZED_TIME) != 0) {
return FALSE;
}
//
// Retrieve the signing time from TS_TST_INFO structure.
//
if (SigningTime != NULL) {
SetMem (SigningTime, sizeof (EFI_TIME), 0);
Status = ConvertAsn1TimeToEfiTime (Ptr, SigningTime);
}
return Status;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,114 +0,0 @@
/** @file
Pseudorandom Number Generator Wrapper Implementation over MbedTLS.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <Library/RngLib.h>
/**
Sets up the seed value for the pseudorandom number generator.
This function sets up the seed value for the pseudorandom number generator.
If Seed is not NULL, then the seed passed in is used.
If Seed is NULL, then default seed is used.
@param[in] Seed Pointer to seed value.
If NULL, default seed is used.
@param[in] SeedSize Size of seed value.
If Seed is NULL, this parameter is ignored.
@retval TRUE Pseudorandom number generator has enough entropy for random generation.
@retval FALSE Pseudorandom number generator does not have enough entropy for random generation.
**/
BOOLEAN
EFIAPI
RandomSeed (
IN CONST UINT8 *Seed OPTIONAL,
IN UINTN SeedSize
)
{
return TRUE;
}
/**
Generates a pseudorandom byte stream of the specified size.
If Output is NULL, then return FALSE.
@param[out] Output Pointer to buffer to receive random value.
@param[in] Size Size of random bytes to generate.
@retval TRUE Pseudorandom byte stream generated successfully.
@retval FALSE Pseudorandom number generator fails to generate due to lack of entropy.
**/
BOOLEAN
EFIAPI
RandomBytes (
OUT UINT8 *Output,
IN UINTN Size
)
{
BOOLEAN Ret;
volatile UINT64 TempRand;
//
// Check input parameters.
//
if ((Output == NULL) || (Size > INT_MAX)) {
return FALSE;
}
Ret = FALSE;
while (Size > 0) {
// Use RngLib to get random number
Ret = GetRandomNumber64 ((UINT64 *)&TempRand);
if (!Ret) {
TempRand = 0;
return Ret;
}
if (Size >= sizeof (TempRand)) {
*((UINT64 *)Output) = TempRand;
Output += sizeof (UINT64);
Size -= sizeof (TempRand);
} else {
CopyMem (Output, (VOID *)&TempRand, Size);
Size = 0;
}
}
TempRand = 0;
return Ret;
}
/**
The MbedTLS function f_rng, which MbedtlsRand implements.
@param[in] RngState Not used, just for compatibility with mbedlts.
@param[out] Output Pointer to buffer to receive random value.
@param[in] Len Size of random bytes to generate.
@retval 0 Pseudorandom byte stream generated successfully.
@retval Non-0 Pseudorandom number generator fails to generate due to lack of entropy.
**/
INT32
MbedtlsRand (
VOID *RngState,
UINT8 *Output,
UINTN Len
)
{
BOOLEAN Result;
Result = RandomBytes (Output, Len);
return Result ? 0 : -1;
}

View File

@ -1,114 +0,0 @@
/** @file
Pseudorandom Number Generator Wrapper Implementation over MbedTLS.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "InternalCryptLib.h"
#include <Library/RngLib.h>
/**
Sets up the seed value for the pseudorandom number generator.
This function sets up the seed value for the pseudorandom number generator.
If Seed is not NULL, then the seed passed in is used.
If Seed is NULL, then default seed is used.
@param[in] Seed Pointer to seed value.
If NULL, default seed is used.
@param[in] SeedSize Size of seed value.
If Seed is NULL, this parameter is ignored.
@retval TRUE Pseudorandom number generator has enough entropy for random generation.
@retval FALSE Pseudorandom number generator does not have enough entropy for random generation.
**/
BOOLEAN
EFIAPI
RandomSeed (
IN CONST UINT8 *Seed OPTIONAL,
IN UINTN SeedSize
)
{
return TRUE;
}
/**
Generates a pseudorandom byte stream of the specified size.
If Output is NULL, then return FALSE.
@param[out] Output Pointer to buffer to receive random value.
@param[in] Size Size of random bytes to generate.
@retval TRUE Pseudorandom byte stream generated successfully.
@retval FALSE Pseudorandom number generator fails to generate due to lack of entropy.
**/
BOOLEAN
EFIAPI
RandomBytes (
OUT UINT8 *Output,
IN UINTN Size
)
{
BOOLEAN Ret;
volatile UINT64 TempRand;
//
// Check input parameters.
//
if ((Output == NULL) || (Size > INT_MAX)) {
return FALSE;
}
Ret = FALSE;
while (Size > 0) {
// Use RngLib to get random number
Ret = GetRandomNumber64 ((UINT64 *)&TempRand);
if (!Ret) {
TempRand = 0;
return Ret;
}
if (Size >= sizeof (TempRand)) {
*((UINT64 *)Output) = TempRand;
Output += sizeof (UINT64);
Size -= sizeof (TempRand);
} else {
CopyMem (Output, (VOID *)&TempRand, Size);
Size = 0;
}
}
TempRand = 0;
return Ret;
}
/**
The MbedTLS function f_rng, which MbedtlsRand implements.
@param[in] RngState Not used, just for compatibility with mbedlts.
@param[out] Output Pointer to buffer to receive random value.
@param[in] Len Size of random bytes to generate.
@retval 0 Pseudorandom byte stream generated successfully.
@retval Non-0 Pseudorandom number generator fails to generate due to lack of entropy.
**/
INT32
MbedtlsRand (
VOID *RngState,
UINT8 *Output,
UINTN Len
)
{
BOOLEAN Result;
Result = RandomBytes (Output, Len);
return Result ? 0 : -1;
}

View File

@ -37,35 +37,32 @@
Hash/CryptMd5.c
Hash/CryptSha1.c
Hash/CryptSha256.c
Hash/CryptSm3Null.c
Hash/CryptSha512.c
Hash/CryptParallelHashNull.c
Hash/CryptSm3.c
Hmac/CryptHmac.c
Kdf/CryptHkdf.c
Cipher/CryptAes.c
Cipher/CryptAeadAesGcmNull.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExtNull.c
Pk/CryptRsaPssNull.c
Pk/CryptRsaPssSignNull.c
Bn/CryptBnNull.c
Pem/CryptPemNull.c
Pk/CryptDhNull.c
Pk/CryptEcNull.c
Pk/CryptPkcs1OaepNull.c
Pk/CryptPkcs5Pbkdf2Null.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyRuntime.c
Pk/CryptPkcs7VerifyEkuRuntime.c
Pk/CryptDhNull.c
Pk/CryptX509.c
Pk/CryptPkcs7VerifyNull.c
Pk/CryptPkcs7VerifyEkuNull.c
Pk/CryptX509Null.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Pk/CryptRsaPssNull.c
Pk/CryptRsaPssSignNull.c
Pk/CryptEcNull.c
Pem/CryptPem.c
Bn/CryptBnNull.c
Rand/CryptRand.c
Rand/CryptRandNull.c
SysCall/CrtWrapper.c
SysCall/TimerWrapper.c
SysCall/DummyOpensslSupport.c
SysCall/RuntimeMemAllocation.c
[Packages]
@ -78,10 +75,8 @@
UefiRuntimeServicesTableLib
DebugLib
MbedTlsLib
OpensslLib
IntrinsicLib
PrintLib
RngLib
#
# Remove these [BuildOptions] after this library is cleaned up

View File

@ -29,6 +29,7 @@
[Sources]
InternalCryptLib.h
Hash/CryptSha512.c
Hash/CryptMd5Null.c
Hash/CryptSha1Null.c
Hash/CryptSha256Null.c

View File

@ -36,35 +36,31 @@
Hash/CryptMd5.c
Hash/CryptSha1.c
Hash/CryptSha256.c
Hash/CryptSm3Null.c
Hash/CryptSha512.c
Hash/CryptParallelHashNull.c
Hash/CryptSm3.c
Hmac/CryptHmac.c
Kdf/CryptHkdf.c
Cipher/CryptAes.c
Cipher/CryptAeadAesGcmNull.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExtNull.c
Pk/CryptPkcs1Oaep.c
Pk/CryptPkcs5Pbkdf2.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyBase.c
Pk/CryptPkcs7VerifyEku.c
Pk/CryptDhNull.c
Pk/CryptX509.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Pk/CryptRsaPss.c
Pk/CryptRsaPssSignNull.c
Pk/CryptEcNull.c
Pem/CryptPem.c
Bn/CryptBnNull.c
Rand/CryptRand.c
Pem/CryptPemNull.c
Pk/CryptDhNull.c
Pk/CryptEcNull.c
Pk/CryptPkcs1OaepNull.c
Pk/CryptPkcs5Pbkdf2Null.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyNull.c
Pk/CryptPkcs7VerifyEkuNull.c
Pk/CryptX509Null.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Rand/CryptRandNull.c
SysCall/CrtWrapper.c
SysCall/DummyOpensslSupport.c
SysCall/BaseMemAllocation.c
SysCall/ConstantTimeClock.c
[Packages]
@ -76,11 +72,9 @@
BaseMemoryLib
MemoryAllocationLib
MbedTlsLib
OpensslLib
IntrinsicLib
PrintLib
MmServicesTableLib
RngLib
SynchronizationLib
#

View File

@ -1,122 +0,0 @@
/** @file
Base Memory Allocation Routines Wrapper for Crypto library over OpenSSL
during PEI & DXE phases.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <CrtLibSupport.h>
#include <Library/MemoryAllocationLib.h>
//
// Extra header to record the memory buffer size from malloc routine.
//
#define CRYPTMEM_HEAD_SIGNATURE SIGNATURE_32('c','m','h','d')
typedef struct {
UINT32 Signature;
UINT32 Reserved;
UINTN Size;
} CRYPTMEM_HEAD;
#define CRYPTMEM_OVERHEAD sizeof(CRYPTMEM_HEAD)
//
// -- Memory-Allocation Routines --
//
/* Allocates memory blocks */
void *
malloc (
size_t size
)
{
CRYPTMEM_HEAD *PoolHdr;
UINTN NewSize;
VOID *Data;
//
// Adjust the size by the buffer header overhead
//
NewSize = (UINTN)(size) + CRYPTMEM_OVERHEAD;
Data = AllocatePool (NewSize);
if (Data != NULL) {
PoolHdr = (CRYPTMEM_HEAD *)Data;
//
// Record the memory brief information
//
PoolHdr->Signature = CRYPTMEM_HEAD_SIGNATURE;
PoolHdr->Size = size;
return (VOID *)(PoolHdr + 1);
} else {
//
// The buffer allocation failed.
//
return NULL;
}
}
/* Reallocate memory blocks */
void *
realloc (
void *ptr,
size_t size
)
{
CRYPTMEM_HEAD *OldPoolHdr;
CRYPTMEM_HEAD *NewPoolHdr;
UINTN OldSize;
UINTN NewSize;
VOID *Data;
NewSize = (UINTN)size + CRYPTMEM_OVERHEAD;
Data = AllocatePool (NewSize);
if (Data != NULL) {
NewPoolHdr = (CRYPTMEM_HEAD *)Data;
NewPoolHdr->Signature = CRYPTMEM_HEAD_SIGNATURE;
NewPoolHdr->Size = size;
if (ptr != NULL) {
//
// Retrieve the original size from the buffer header.
//
OldPoolHdr = (CRYPTMEM_HEAD *)ptr - 1;
ASSERT (OldPoolHdr->Signature == CRYPTMEM_HEAD_SIGNATURE);
OldSize = OldPoolHdr->Size;
//
// Duplicate the buffer content.
//
CopyMem ((VOID *)(NewPoolHdr + 1), ptr, MIN (OldSize, size));
FreePool ((VOID *)OldPoolHdr);
}
return (VOID *)(NewPoolHdr + 1);
} else {
//
// The buffer allocation failed.
//
return NULL;
}
}
/* De-allocates or frees a memory block */
void
free (
void *ptr
)
{
CRYPTMEM_HEAD *PoolHdr;
//
// In Standard C, free() handles a null pointer argument transparently. This
// is not true of FreePool() below, so protect it.
//
if (ptr != NULL) {
PoolHdr = (CRYPTMEM_HEAD *)ptr - 1;
ASSERT (PoolHdr->Signature == CRYPTMEM_HEAD_SIGNATURE);
FreePool (PoolHdr);
}
}

View File

@ -1,571 +0,0 @@
/**
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <CrtLibSupport.h>
int errno = 0;
FILE *stderr = NULL;
FILE *stdin = NULL;
FILE *stdout = NULL;
typedef
int
(*SORT_COMPARE)(
IN VOID *Buffer1,
IN VOID *Buffer2
);
//
// Duplicated from EDKII BaseSortLib for qsort() wrapper
//
STATIC
VOID
QuickSortWorker (
IN OUT VOID *BufferToSort,
IN CONST UINTN Count,
IN CONST UINTN ElementSize,
IN SORT_COMPARE CompareFunction,
IN VOID *Buffer
)
{
VOID *Pivot;
UINTN LoopCount;
UINTN NextSwapLocation;
ASSERT (BufferToSort != NULL);
ASSERT (CompareFunction != NULL);
ASSERT (Buffer != NULL);
if ((Count < 2) || (ElementSize < 1)) {
return;
}
NextSwapLocation = 0;
//
// Pick a pivot (we choose last element)
//
Pivot = ((UINT8 *)BufferToSort + ((Count - 1) * ElementSize));
//
// Now get the pivot such that all on "left" are below it
// and everything "right" are above it
//
for (LoopCount = 0; LoopCount < Count - 1; LoopCount++) {
//
// If the element is less than the pivot
//
if (CompareFunction ((VOID *)((UINT8 *)BufferToSort + ((LoopCount) * ElementSize)), Pivot) <= 0) {
//
// Swap
//
CopyMem (Buffer, (UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), ElementSize);
CopyMem ((UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), (UINT8 *)BufferToSort + ((LoopCount) * ElementSize), ElementSize);
CopyMem ((UINT8 *)BufferToSort + ((LoopCount) * ElementSize), Buffer, ElementSize);
//
// Increment NextSwapLocation
//
NextSwapLocation++;
}
}
//
// Swap pivot to its final position (NextSwapLocation)
//
CopyMem (Buffer, Pivot, ElementSize);
CopyMem (Pivot, (UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), ElementSize);
CopyMem ((UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), Buffer, ElementSize);
//
// Now recurse on 2 partial lists. Neither of these will have the 'pivot' element.
// IE list is sorted left half, pivot element, sorted right half...
//
QuickSortWorker (
BufferToSort,
NextSwapLocation,
ElementSize,
CompareFunction,
Buffer
);
QuickSortWorker (
(UINT8 *)BufferToSort + (NextSwapLocation + 1) * ElementSize,
Count - NextSwapLocation - 1,
ElementSize,
CompareFunction,
Buffer
);
return;
}
// ---------------------------------------------------------
// Standard C Run-time Library Interface Wrapper
// ---------------------------------------------------------
//
// -- String Manipulation Routines --
//
/* Scan a string for the last occurrence of a character */
char *
strrchr (
const char *str,
int c
)
{
char *save;
for (save = NULL; ; ++str) {
if (*str == c) {
save = (char *)str;
}
if (*str == 0) {
return (save);
}
}
}
/* Compare first n bytes of string s1 with string s2, ignoring case */
int
strncasecmp (
const char *s1,
const char *s2,
size_t n
)
{
int Val;
ASSERT (s1 != NULL);
ASSERT (s2 != NULL);
if (n != 0) {
do {
Val = tolower (*s1) - tolower (*s2);
if (Val != 0) {
return Val;
}
++s1;
++s2;
if (*s1 == '\0') {
break;
}
} while (--n != 0);
}
return 0;
}
/* Read formatted data from a string */
int
sscanf (
const char *buffer,
const char *format,
...
)
{
//
// Null sscanf() function implementation to satisfy the linker, since
// no direct functionality logic dependency in present UEFI cases.
//
return 0;
}
/* Maps errnum to an error-message string */
char *
strerror (
int errnum
)
{
return NULL;
}
/* Computes the length of the maximum initial segment of the string pointed to by s1
which consists entirely of characters from the string pointed to by s2. */
size_t
strspn (
const char *s1,
const char *s2
)
{
UINT8 Map[32];
UINT32 Index;
size_t Count;
for (Index = 0; Index < 32; Index++) {
Map[Index] = 0;
}
while (*s2) {
Map[*s2 >> 3] |= (1 << (*s2 & 7));
s2++;
}
if (*s1) {
Count = 0;
while (Map[*s1 >> 3] & (1 << (*s1 & 7))) {
Count++;
s1++;
}
return Count;
}
return 0;
}
/* Computes the length of the maximum initial segment of the string pointed to by s1
which consists entirely of characters not from the string pointed to by s2. */
size_t
strcspn (
const char *s1,
const char *s2
)
{
UINT8 Map[32];
UINT32 Index;
size_t Count;
for (Index = 0; Index < 32; Index++) {
Map[Index] = 0;
}
while (*s2) {
Map[*s2 >> 3] |= (1 << (*s2 & 7));
s2++;
}
Map[0] |= 1;
Count = 0;
while (!(Map[*s1 >> 3] & (1 << (*s1 & 7)))) {
Count++;
s1++;
}
return Count;
}
char *
strcpy (
char *strDest,
const char *strSource
)
{
// AsciiStrCpyS (strDest, MAX_STRING_SIZE, strSource);
// return strDest;
return NULL;
}
//
// -- Character Classification Routines --
//
/* Determines if a particular character is a decimal-digit character */
int
isdigit (
int c
)
{
//
// <digit> ::= [0-9]
//
return (('0' <= (c)) && ((c) <= '9'));
}
/* Determine if an integer represents character that is a hex digit */
int
isxdigit (
int c
)
{
//
// <hexdigit> ::= [0-9] | [a-f] | [A-F]
//
return ((('0' <= (c)) && ((c) <= '9')) ||
(('a' <= (c)) && ((c) <= 'f')) ||
(('A' <= (c)) && ((c) <= 'F')));
}
/* Determines if a particular character represents a space character */
int
isspace (
int c
)
{
//
// <space> ::= [ ]
//
return ((c) == ' ');
}
/* Determine if a particular character is an alphanumeric character */
int
isalnum (
int c
)
{
//
// <alnum> ::= [0-9] | [a-z] | [A-Z]
//
return ((('0' <= (c)) && ((c) <= '9')) ||
(('a' <= (c)) && ((c) <= 'z')) ||
(('A' <= (c)) && ((c) <= 'Z')));
}
/* Determines if a particular character is in upper case */
int
isupper (
int c
)
{
//
// <uppercase letter> := [A-Z]
//
return (('A' <= (c)) && ((c) <= 'Z'));
}
//
// -- Data Conversion Routines --
//
/* Convert strings to a long-integer value */
long
strtol (
const char *nptr,
char **endptr,
int base
)
{
//
// Null strtol() function implementation to satisfy the linker, since there is
// no direct functionality logic dependency in present UEFI cases.
//
return 0;
}
/* Convert strings to an unsigned long-integer value */
unsigned long
strtoul (
const char *nptr,
char **endptr,
int base
)
{
//
// Null strtoul() function implementation to satisfy the linker, since there is
// no direct functionality logic dependency in present UEFI cases.
//
return 0;
}
/* Convert character to lowercase */
int
tolower (
int c
)
{
if (('A' <= (c)) && ((c) <= 'Z')) {
return (c - ('A' - 'a'));
}
return (c);
}
//
// -- Searching and Sorting Routines --
//
/* Performs a quick sort */
void
qsort (
void *base,
size_t num,
size_t width,
int ( *compare )(const void *, const void *)
)
{
VOID *Buffer;
ASSERT (base != NULL);
ASSERT (compare != NULL);
//
// Use CRT-style malloc to cover BS and RT memory allocation.
//
Buffer = malloc (width);
ASSERT (Buffer != NULL);
//
// Re-use PerformQuickSort() function Implementation in EDKII BaseSortLib.
//
QuickSortWorker (base, (UINTN)num, (UINTN)width, (SORT_COMPARE)compare, Buffer);
free (Buffer);
return;
}
//
// -- Process and Environment Control Routines --
//
/* Get a value from the current environment */
char *
getenv (
const char *varname
)
{
//
// Null getenv() function implementation to satisfy the linker, since there is
// no direct functionality logic dependency in present UEFI cases.
//
return NULL;
}
/* Get a value from the current environment */
char *
secure_getenv (
const char *varname
)
{
//
// Null secure_getenv() function implementation to satisfy the linker, since
// there is no direct functionality logic dependency in present UEFI cases.
//
// From the secure_getenv() manual: 'just like getenv() except that it
// returns NULL in cases where "secure execution" is required'.
//
return NULL;
}
//
// -- Stream I/O Routines --
//
/* Write data to a stream */
size_t
fwrite (
const void *buffer,
size_t size,
size_t count,
FILE *stream
)
{
return 0;
}
#ifdef __GNUC__
typedef
VOID
(EFIAPI *NoReturnFuncPtr)(
VOID
) __attribute__ ((__noreturn__));
STATIC
VOID
EFIAPI
NopFunction (
VOID
)
{
}
void
abort (
void
)
{
NoReturnFuncPtr NoReturnFunc;
NoReturnFunc = (NoReturnFuncPtr)NopFunction;
NoReturnFunc ();
}
#else
void
abort (
void
)
{
// Do nothing
}
#endif
int
fclose (
FILE *f
)
{
return 0;
}
FILE *
fopen (
const char *c,
const char *m
)
{
return NULL;
}
size_t
fread (
void *b,
size_t c,
size_t i,
FILE *f
)
{
return 0;
}
uid_t
getuid (
void
)
{
return 0;
}
uid_t
geteuid (
void
)
{
return 0;
}
gid_t
getgid (
void
)
{
return 0;
}
gid_t
getegid (
void
)
{
return 0;
}
int
printf (
char const *fmt,
...
)
{
return 0;
}

View File

@ -1,63 +0,0 @@
/** @file
C Run-Time Libraries (CRT) Wrapper Implementation for OpenSSL-based
Cryptographic Library.
Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
Copyright (c) Microsoft Corporation
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <stdio.h>
#include <Base.h>
#include <Library/DebugLib.h>
/* Read formatted data from a string */
int
sscanf (
const char *buffer,
const char *format,
...
)
{
//
// Null sscanf() function implementation to satisfy the linker, since
// no direct functionality logic dependency in present UEFI cases.
//
return 0;
}
uid_t
getuid (
void
)
{
return 0;
}
uid_t
geteuid (
void
)
{
return 0;
}
gid_t
getgid (
void
)
{
return 0;
}
gid_t
getegid (
void
)
{
return 0;
}
int errno = 0;

View File

@ -27,36 +27,33 @@
[Sources]
InternalCryptLib.h
Hash/CryptMd5.c
Hash/CryptSha1.c
Cipher/CryptAeadAesGcmNull.c
Cipher/CryptAes.c
Hash/CryptSha256.c
Hash/CryptSha512.c
Hash/CryptSm3.c
Hash/CryptParallelHashNull.c
Hash/CryptSm3Null.c
Hash/CryptMd5.c
Hash/CryptSha1.c
Hmac/CryptHmac.c
Kdf/CryptHkdf.c
Cipher/CryptAes.c
Cipher/CryptAeadAesGcm.c
Pk/CryptRsaBasic.c
Pk/CryptRsaExt.c
Pk/CryptPkcs1Oaep.c
Pk/CryptPkcs5Pbkdf2.c
Pk/CryptPkcs7Sign.c
Pk/CryptPkcs7VerifyCommon.c
Pk/CryptPkcs7VerifyBase.c
Pk/CryptPkcs7VerifyEku.c
Pk/CryptDhNull.c
Pk/CryptX509.c
Pk/CryptAuthenticode.c
Pk/CryptTs.c
Pem/CryptPem.c
Pk/CryptRsaExtNull.c
Pk/CryptRsaPss.c
Pk/CryptRsaPssSign.c
Pk/CryptRsaPssSignNull.c
Bn/CryptBnNull.c
Pem/CryptPemNull.c
Pk/CryptDhNull.c
Pk/CryptEcNull.c
Rand/CryptRand.c
Pk/CryptPkcs1OaepNull.c
Pk/CryptPkcs5Pbkdf2Null.c
Pk/CryptPkcs7SignNull.c
Pk/CryptPkcs7VerifyNull.c
Pk/CryptPkcs7VerifyEkuNull.c
Pk/CryptX509Null.c
Pk/CryptAuthenticodeNull.c
Pk/CryptTsNull.c
Rand/CryptRandNull.c
SysCall/CrtWrapper.c
SysCall/UnitTestHostCrtWrapper.c
[Packages]
MdePkg/MdePkg.dec
@ -69,7 +66,6 @@
UefiRuntimeServicesTableLib
DebugLib
MbedTlsLib
OpensslLib
PrintLib
RngLib

View File

@ -141,17 +141,6 @@ static const OSSL_ALGORITHM_CAPABLE deflt_ciphers[] = {
ALG(PROV_NAMES_AES_192_GCM, ossl_aes192gcm_functions),
ALG(PROV_NAMES_AES_128_GCM, ossl_aes128gcm_functions),
ALGC (
PROV_NAMES_AES_128_CBC_HMAC_SHA256,
ossl_aes128cbc_hmac_sha256_functions,
ossl_cipher_capable_aes_cbc_hmac_sha256
),
ALGC (
PROV_NAMES_AES_256_CBC_HMAC_SHA256,
ossl_aes256cbc_hmac_sha256_functions,
ossl_cipher_capable_aes_cbc_hmac_sha256
),
{ { NULL, NULL, NULL }, NULL }
};
static OSSL_ALGORITHM exported_ciphers[OSSL_NELEM(deflt_ciphers)];

View File

@ -140,7 +140,7 @@ GasketSecGetTime (
OUT EFI_TIME_CAPABILITIES *Capabilities OPTIONAL
);
EFI_STATUS
VOID
EFIAPI
GasketSecSetTime (
IN EFI_TIME *Time

View File

@ -92,7 +92,6 @@ GCD_ATTRIBUTE_CONVERSION_ENTRY mAttributeConversionTable[] = {
{ EFI_RESOURCE_ATTRIBUTE_TESTED, EFI_MEMORY_TESTED, FALSE },
{ EFI_RESOURCE_ATTRIBUTE_PERSISTABLE, EFI_MEMORY_NV, TRUE },
{ EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE, EFI_MEMORY_MORE_RELIABLE, TRUE },
{ EFI_RESOURCE_ATTRIBUTE_SPECIAL_PURPOSE, EFI_MEMORY_SP, TRUE },
{ 0, 0, FALSE }
};

View File

@ -152,7 +152,6 @@ SmiManage (
PERF_FUNCTION_BEGIN ();
mSmiManageCallingDepth++;
WillReturn = FALSE;
Status = EFI_NOT_FOUND;
ReturnStatus = Status;
if (HandlerType == NULL) {

View File

@ -1,7 +1,7 @@
/** @file
Definitions for data structures used in S3 resume.
Copyright (c) 2011 - 2024, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2011 - 2023, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -30,6 +30,7 @@ typedef struct {
EFI_PHYSICAL_ADDRESS ReturnContext1;
EFI_PHYSICAL_ADDRESS ReturnContext2;
EFI_PHYSICAL_ADDRESS ReturnStackPointer;
EFI_PHYSICAL_ADDRESS MpService2Ppi;
EFI_PHYSICAL_ADDRESS Smst;
} SMM_S3_RESUME_STATE;

View File

@ -29,7 +29,8 @@ typedef enum {
EdkiiPlatformLogoDisplayAttributeCenterBottom,
EdkiiPlatformLogoDisplayAttributeLeftBottom,
EdkiiPlatformLogoDisplayAttributeCenterLeft,
EdkiiPlatformLogoDisplayAttributeCenter
EdkiiPlatformLogoDisplayAttributeCenter,
EdkiiPlatformLogoDisplayAttributeMicrosoft,
} EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE;
/**

View File

@ -216,7 +216,7 @@ TranslateBmpToGopBlt (
if ((BmpHeader->Size != BmpImageSize) ||
(BmpHeader->Size < BmpHeader->ImageOffset) ||
(BmpHeader->Size - BmpHeader->ImageOffset != DataSize))
(BmpHeader->Size - BmpHeader->ImageOffset < DataSize))
{
DEBUG ((DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BmpImage... \n"));
DEBUG ((DEBUG_ERROR, " BmpHeader->Size: 0x%x\n", BmpHeader->Size));

View File

@ -196,6 +196,12 @@ BootLogoEnableLogo (
DestY = SizeOfY - Image.Height;
break;
case EdkiiPlatformLogoDisplayAttributeMicrosoft:
// Position the logo so that its center is 38.2% from the top.
DestX = (SizeOfX - Image.Width) / 2;
DestY = (SizeOfY * 382) / 1000 - Image.Height / 2;
break;
default:
ASSERT (FALSE);
continue;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 315 KiB

View File

@ -26,7 +26,7 @@ EFI_HII_HANDLE mHiiHandle;
LOGO_ENTRY mLogos[] = {
{
IMAGE_TOKEN (IMG_LOGO),
EdkiiPlatformLogoDisplayAttributeCenter,
EdkiiPlatformLogoDisplayAttributeMicrosoft,
0,
0
}

View File

@ -4,7 +4,7 @@
# and libraries instances, which are used for those modules.
#
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
# Copyright (c) 2007 - 2024, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2016, Linaro Ltd. All rights reserved.<BR>
# (C) Copyright 2016 - 2019 Hewlett Packard Enterprise Development LP<BR>
# Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
@ -465,9 +465,6 @@
gEdk2JedecSfdpSpiDxeDriverGuid = { 0xBE71701E, 0xB63C, 0x4574, { 0x9C, 0x5C, 0x36, 0x29, 0xE8, 0xEA, 0xC4, 0x14 }}
gEdk2JedecSfdpSpiSmmDriverGuid = { 0x95A1E915, 0x195C, 0x477C, { 0x92, 0x6F, 0x7E, 0x24, 0x67, 0xC1, 0xB3, 0x1F }}
## This GUID will be used to save MTRR_SETTINGS at EndOfDxe by LockBox and restore at S3 boot PEI phase for s3 usage.
gEdkiiS3MtrrSettingGuid = { 0xd77baa84, 0xb332, 0x4463, { 0x9f, 0x1d, 0xce, 0x81, 0x00, 0xfe, 0x7f, 0x35 }}
[Ppis]
## Include/Ppi/FirmwareVolumeShadowPpi.h
gEdkiiPeiFirmwareVolumeShadowPpiGuid = { 0x7dfe756c, 0xed8d, 0x4d77, {0x9e, 0xc4, 0x39, 0x9a, 0x8a, 0x81, 0x51, 0x16 } }

View File

@ -2101,9 +2101,8 @@ ExtractConfigRequest (
//
// Header->VarStoreId == 0 means no storage for this question.
//
if (Header->VarStoreId == 0) {
continue;
}
ASSERT (Header->VarStoreId != 0);
DEBUG ((DEBUG_INFO, "Varstore Id: 0x%x\n", Header->VarStoreId));
Storage = FindStorageFromVarId (FormPackage, Header->VarStoreId);
ASSERT (Storage != NULL);

View File

@ -1288,6 +1288,7 @@ HiiDrawImage (
UINTN BufferLen;
UINT16 Width;
UINT16 Height;
UINTN Xpos;
UINTN Ypos;
UINTN OffsetY1;
UINTN OffsetY2;
@ -1389,11 +1390,9 @@ HiiDrawImage (
for (Ypos = 0; Ypos < Height; Ypos++) {
OffsetY1 = Image->Width * Ypos;
OffsetY2 = Width * Ypos;
CopyMem (
&BltBuffer[OffsetY2],
&Image->Bitmap[OffsetY1],
Width * sizeof (*BltBuffer)
);
for (Xpos = 0; Xpos < Width; Xpos++) {
BltBuffer[OffsetY2 + Xpos] = Image->Bitmap[OffsetY1 + Xpos];
}
}
}

View File

@ -1,18 +0,0 @@
/** @file
IPMI 2.0 definitions from the IPMI Specification Version 2.0, Revision 1.1.
Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef IPMI_NET_FN_OEM_H_
#define IPMI_NET_FN_OEM_H_
//
// Net function definition for OEM/Group command
//
#define IPMI_NETFN_OEM 0x2E
#define IPMI_NETFN_OEM_GROUP 0x2F
#endif

View File

@ -10,7 +10,6 @@
and Appendix H, Sub-function Assignments.
Copyright (c) 1999 - 2015, Intel Corporation. All rights reserved.<BR>
Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
@ -43,50 +42,5 @@ typedef struct {
UINT8 OEMEvData3;
} IPMI_PLATFORM_EVENT_MESSAGE_DATA_REQUEST;
//
// Definitions for Set Sensor Thresholds command
//
#define IPMI_SENSOR_SET_SENSOR_THRESHOLDS 0x26
typedef union {
struct _SENSOR_BITS {
UINT8 LowerNonCriticalThreshold : 1;
UINT8 LowerCriticalThreshold : 1;
UINT8 LowerNonRecoverableThreshold : 1;
UINT8 UpperNonCriticalThreshold : 1;
UINT8 UpperCriticalThreshold : 1;
UINT8 UpperNonRecoverableThreshold : 1;
UINT8 Reserved : 2;
} Bits;
UINT8 Uint8;
} SENSOR_BITS;
typedef struct _IPMI_SENSOR_SET_SENSOR_THRESHOLD_REQUEST_DATA {
UINT8 SensorNumber;
SENSOR_BITS SetBitEnable;
UINT8 LowerNonCriticalThreshold;
UINT8 LowerCriticalThreshold;
UINT8 LowerNonRecoverableThreshold;
UINT8 UpperNonCriticalThreshold;
UINT8 UpperCriticalThreshold;
UINT8 UpperNonRecoverableThreshold;
} IPMI_SENSOR_SET_SENSOR_THRESHOLD_REQUEST_DATA;
//
// Definitions for Get Sensor Thresholds command
//
#define IPMI_SENSOR_GET_SENSOR_THRESHOLDS 0x27
typedef struct _IPMI_SENSOR_GET_SENSOR_THRESHOLD_RESPONSE_DATA {
UINT8 CompletionCode;
SENSOR_BITS GetBitEnable;
UINT8 LowerNonCriticalThreshold;
UINT8 LowerCriticalThreshold;
UINT8 LowerNonRecoverableThreshold;
UINT8 UpperNonCriticalThreshold;
UINT8 UpperCriticalThreshold;
UINT8 UpperNonRecoverableThreshold;
} IPMI_SENSOR_GET_SENSOR_THRESHOLD_RESPONSE_DATA;
#pragma pack()
#endif

View File

@ -46,9 +46,9 @@ CPUID Signature Information
CPUID Extended Topology Enumeration
@note
Reference: AMD64 Architecture Programmer's Manual Volume 3: General-Purpose and System Instructions,
Reference: AMD64 Architecture Programmers Manual Volume 3: General-Purpose and System Instructions,
Revision 3.35 Appendix E,
E.4.24 Function 8000_0026-Extended CPU Topology:
E.4.24 Function 8000_0026Extended CPU Topology:
CPUID Fn8000_0026 reports extended topology information for logical processors, including
asymmetric and heterogenous topology descriptions. Individual logical processors may report
different values in systems with asynchronous and heterogeneous topologies.

View File

@ -5733,9 +5733,9 @@ typedef union {
/// [Bit 7:4] TME Policy/Encryption Algorithm: Only algorithms enumerated in
/// IA32_TME_CAPABILITY are allowed.
/// For example:
/// 0000 - AES-XTS-128.
/// 0001 - AES-XTS-128 with integrity.
/// 0010 - AES-XTS-256.
/// 0000 AES-XTS-128.
/// 0001 AES-XTS-128 with integrity.
/// 0010 AES-XTS-256.
/// Other values are invalid.
///
UINT32 TmePolicy : 4;
@ -5756,7 +5756,7 @@ typedef union {
/// Similar to enumeration, this is an encoded value.
/// Writing a value greater than MK_TME_MAX_KEYID_BITS will result in #GP.
/// Writing a non-zero value to this field will #GP if bit 1 of EAX (Hardware
/// Encryption Enable) is not also set to 1, as encryption hardware must be
/// Encryption Enable) is not also set to 1, as encryption hardware must be
/// enabled to use MKTME.
/// Example: To support 255 keys, this field would be set to a value of 8.
///

View File

@ -509,7 +509,7 @@ TcpDestroyService (
//
// Destroy the instance of the hashing protocol for this controller.
//
Status = Hash2ServiceBinding->DestroyChild (Hash2ServiceBinding, mHash2ServiceHandle);
Status = Hash2ServiceBinding->DestroyChild (Hash2ServiceBinding, &mHash2ServiceHandle);
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}

View File

@ -9,7 +9,7 @@ number of CPUs reported by the MP Services Protocol, so this module does not
support hot plug CPUs. This module can be copied into a CPU specific package
and customized if these additional features are required.
Copyright (c) 2013 - 2024, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2013 - 2021, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2015 - 2020, Red Hat, Inc.
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -26,7 +26,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
#include <Library/MemoryAllocationLib.h>
#include <Library/MtrrLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/LockBoxLib.h>
#include <Protocol/MpService.h>
#include <Guid/EventGroup.h>
@ -131,16 +130,6 @@ CpuS3DataOnEndOfDxe (
DEBUG ((DEBUG_VERBOSE, "%a\n", __func__));
MtrrGetAllMtrrs (&AcpiCpuDataEx->MtrrTable);
//
// Save MTRR in lockbox
//
Status = SaveLockBox (
&gEdkiiS3MtrrSettingGuid,
&AcpiCpuDataEx->MtrrTable,
sizeof (MTRR_SETTINGS)
);
ASSERT_EFI_ERROR (Status);
//
// Close event, so it will not be invoked again.
//

View File

@ -9,7 +9,7 @@
# support hot plug CPUs. This module can be copied into a CPU specific package
# and customized if these additional features are required.
#
# Copyright (c) 2013-2024, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2013-2016, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2015-2020, Red Hat, Inc.
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
@ -46,11 +46,9 @@
MtrrLib
UefiBootServicesTableLib
UefiDriverEntryPoint
LockBoxLib
[Guids]
gEfiEndOfDxeEventGroupGuid ## CONSUMES ## Event
gEdkiiS3MtrrSettingGuid
[Protocols]
gEfiMpServiceProtocolGuid ## CONSUMES

View File

@ -1,10 +0,0 @@
##
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
# MorLock support
##
SecurityPkg/Tcg/MemoryOverwriteControl/TcgMor.inf
!if $(SMM_REQUIRE) == TRUE
SecurityPkg/Tcg/MemoryOverwriteRequestControlLock/TcgMorLockSmm.inf
!endif

View File

@ -1,10 +0,0 @@
##
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
# MorLock support
##
INF SecurityPkg/Tcg/MemoryOverwriteControl/TcgMor.inf
!if $(SMM_REQUIRE) == TRUE
INF SecurityPkg/Tcg/MemoryOverwriteRequestControlLock/TcgMorLockSmm.inf
!endif

View File

@ -643,8 +643,6 @@ ValidateHobList (
EFI_RESOURCE_ATTRIBUTE_PERSISTABLE |
EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTED |
EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE |
EFI_RESOURCE_ATTRIBUTE_ENCRYPTED|
EFI_RESOURCE_ATTRIBUTE_SPECIAL_PURPOSE |
EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE))) != 0)
{
DEBUG ((DEBUG_ERROR, "HOB: Unknow ResourceDescriptor ResourceAttribute type. Type: 0x%08x\n", Hob.ResourceDescriptor->ResourceAttribute));

View File

@ -1,46 +0,0 @@
## @file
#
# Copyright (c) 2014-2018, Linaro Ltd. All rights reserved.<BR>
# Copyright (c) 2024 Loongson Technology Corporation Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
[Defines]
INF_VERSION = 1.29
BASE_NAME = NorFlashQemuLib
FILE_GUID = E225C90F-6CB9-8AF3-095B-2668FC633A57
MODULE_TYPE = DXE_DRIVER
VERSION_STRING = 1.0
LIBRARY_CLASS = NorFlashQemuLib|DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER UEFI_APPLICATION
[Sources]
FdtNorFlashQemuLib.c
[Packages]
EmbeddedPkg/EmbeddedPkg.dec
MdePkg/MdePkg.dec
MdeModulePkg/MdeModulePkg.dec
OvmfPkg/OvmfPkg.dec
[LibraryClasses]
BaseLib
DebugLib
UefiBootServicesTableLib
[Protocols]
gFdtClientProtocolGuid ## CONSUMES
[Depex]
gFdtClientProtocolGuid
[Pcd]
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase
gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase

View File

@ -633,7 +633,6 @@ PlatformAddressWidthFromCpuid (
{
UINT32 RegEax, RegEbx, RegEcx, RegEdx, Max;
UINT8 PhysBits;
UINT8 GuestPhysBits;
CHAR8 Signature[13];
IA32_CR4 Cr4;
BOOLEAN Valid = FALSE;
@ -656,17 +655,13 @@ PlatformAddressWidthFromCpuid (
if (Max >= 0x80000008) {
AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);
PhysBits = (UINT8)RegEax;
GuestPhysBits = (UINT8)(RegEax >> 16);
PhysBits = (UINT8)RegEax;
} else {
PhysBits = 36;
GuestPhysBits = 0;
PhysBits = 36;
}
if (!QemuQuirk) {
Valid = TRUE;
} else if (GuestPhysBits) {
Valid = TRUE;
} else if (PhysBits >= 41) {
Valid = TRUE;
} else if (AsciiStrCmp (Signature, "GenuineIntel") == 0) {
@ -683,21 +678,15 @@ PlatformAddressWidthFromCpuid (
DEBUG ((
DEBUG_INFO,
"%a: Signature: '%a', PhysBits: %d, GuestPhysBits: %d, QemuQuirk: %a, la57: %a, Valid: %a\n",
"%a: Signature: '%a', PhysBits: %d, QemuQuirk: %a, la57: %a, Valid: %a\n",
__func__,
Signature,
PhysBits,
GuestPhysBits,
QemuQuirk ? "On" : "Off",
Cr4.Bits.LA57 ? "On" : "Off",
Valid ? "Yes" : "No"
));
if (GuestPhysBits && (PhysBits > GuestPhysBits)) {
DEBUG ((DEBUG_INFO, "%a: limit PhysBits to %d (GuestPhysBits)\n", __func__, GuestPhysBits));
PhysBits = GuestPhysBits;
}
if (Valid) {
/*
* Due to the sign extension we can use only the lower half of the
@ -706,7 +695,7 @@ PlatformAddressWidthFromCpuid (
* and a 56 bit wide address space with 5 paging levels.
*/
if (Cr4.Bits.LA57) {
if ((PhysBits > 48) && !GuestPhysBits) {
if (PhysBits > 48) {
/*
* Some Intel CPUs support 5-level paging, have more than 48
* phys-bits but support only 4-level EPT, which effectively
@ -716,11 +705,11 @@ PlatformAddressWidthFromCpuid (
* problem: They can handle guest phys-bits larger than 48
* only in case the host runs in 5-level paging mode.
*
* GuestPhysBits is used to communicate that kind of
* limitations from hypervisor to guest. If GuestPhysBits is
* not set play safe and limit phys-bits to 48.
* Until we have some way to communicate that kind of
* limitations from hypervisor to guest, limit phys-bits
* to 48 unconditionally.
*/
DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 48 (5-level paging, no GuestPhysBits)\n", __func__));
DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 48 (5-level paging)\n", __func__));
PhysBits = 48;
}
} else {

View File

@ -881,7 +881,6 @@
MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf
!include OvmfPkg/Include/Dsc/ShellComponents.dsc.inc
!include OvmfPkg/Include/Dsc/MorLock.dsc.inc
!if $(SECURE_BOOT_ENABLE) == TRUE
SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf

View File

@ -359,7 +359,6 @@ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
!include OvmfPkg/Include/Fdf/OvmfTpmDxe.fdf.inc
!include OvmfPkg/Include/Fdf/ShellDxe.fdf.inc
!include OvmfPkg/Include/Fdf/MorLock.fdf.inc
!if $(LOAD_X64_ON_IA32_ENABLE) == TRUE
INF OvmfPkg/CompatImageLoaderDxe/CompatImageLoaderDxe.inf

Some files were not shown because too many files have changed in this diff Show More