-
Notifications
You must be signed in to change notification settings - Fork 43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Generic script to retrieve the contents of UEFI Variables accessible at runtime #880
Open
Flickdm
wants to merge
2
commits into
tianocore:master
Choose a base branch
from
Flickdm:feature/add_script_to_pull_uefi_variables
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
import argparse | ||
import ctypes | ||
import logging | ||
import os | ||
import sys | ||
|
||
import tomllib | ||
|
||
# Some of these libraries are windows only, so we need to import them conditionally | ||
if sys.platform == "win32": | ||
import pywintypes | ||
import win32api | ||
import win32process | ||
import win32security | ||
|
||
if sys.platform == "win32": | ||
KERNEL32 = ctypes.windll.kernel32 | ||
EFI_VAR_MAX_BUFFER_SIZE = 1024 * 1024 | ||
|
||
ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) | ||
VAR_DEBUG_DIR = os.path.join(ROOT_DIR, "VAR_DEBUG") | ||
|
||
################################################################################################### | ||
# Classes | ||
################################################################################################### | ||
|
||
|
||
class FirmwareVariables(object): | ||
"""Class to interact with firmware variables.""" | ||
|
||
def __init__(self) -> None: | ||
"""Constructor.""" | ||
# enable required SeSystemEnvironmentPrivilege privilege | ||
privilege = win32security.LookupPrivilegeValue( | ||
None, "SeSystemEnvironmentPrivilege" | ||
) | ||
|
||
token = win32security.OpenProcessToken( | ||
win32process.GetCurrentProcess(), | ||
win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES, | ||
) | ||
|
||
win32security.AdjustTokenPrivileges( | ||
token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] | ||
) | ||
|
||
win32api.CloseHandle(token) | ||
|
||
try: | ||
self._GetFirmwareEnvironmentVariable = ( | ||
KERNEL32.GetFirmwareEnvironmentVariableW | ||
) | ||
self._GetFirmwareEnvironmentVariable.restype = ctypes.c_int | ||
self._GetFirmwareEnvironmentVariable.argtypes = [ | ||
ctypes.c_wchar_p, | ||
ctypes.c_wchar_p, | ||
ctypes.c_void_p, | ||
ctypes.c_int, | ||
] | ||
except AttributeError: | ||
self._GetFirmwareEnvironmentVariable = None | ||
logging.warning("Get function doesn't exist") | ||
|
||
def get_variable(self, name: str, guid: str) -> bytes: | ||
"""Gets a firmware variable. | ||
|
||
Args: | ||
name (str): Name of the variable to get | ||
guid (str): GUID of the variable to get | ||
|
||
Returns: | ||
The value of the variable | ||
""" | ||
if self._GetFirmwareEnvironmentVariable is None: | ||
raise NotImplementedError( | ||
"GetFirmwareEnvironmentVariable is not implemented" | ||
) | ||
|
||
buffer = ctypes.create_string_buffer(EFI_VAR_MAX_BUFFER_SIZE) | ||
buffer_size = ctypes.c_int(EFI_VAR_MAX_BUFFER_SIZE) | ||
result = self._GetFirmwareEnvironmentVariable(name, guid, buffer, buffer_size) | ||
if result == 0: | ||
last_error = win32api.GetLastError() | ||
|
||
raise pywintypes.error( | ||
last_error, | ||
"GetFirmwareEnvironmentVariable", | ||
win32api.FormatMessage(last_error), | ||
) | ||
|
||
return buffer.raw[:result] | ||
|
||
def main(): | ||
Check failure on line 93 in edk2toolext/windows/variables/access_variables.py GitHub Actions / CI / RunRuff (ANN201)
|
||
|
||
parser = argparse.ArgumentParser(description="Access UEFI Variables") | ||
|
||
# Read an Ini configuration file | ||
parser.add_argument( | ||
"-c", | ||
"--config", | ||
help="config to read", | ||
required=True, | ||
) | ||
|
||
args = parser.parse_args() | ||
|
||
# remove existing folder and create a new one | ||
if os.path.exists(VAR_DEBUG_DIR): | ||
import shutil | ||
|
||
shutil.rmtree(VAR_DEBUG_DIR) | ||
|
||
os.makedirs(VAR_DEBUG_DIR, exist_ok=True) | ||
|
||
logging.basicConfig( | ||
level=logging.INFO, | ||
format="%(asctime)s [%(levelname)s] %(message)s", | ||
handlers=[ | ||
logging.FileHandler(os.path.join(VAR_DEBUG_DIR, "Variables_Debug.log")), | ||
logging.StreamHandler() | ||
] | ||
) | ||
|
||
with open(args.config, "rb") as f: | ||
config = tomllib.load(f) | ||
|
||
for section in config.keys(): | ||
logging.info(f"Parsing [{section}]") | ||
|
||
for key in config[section]: | ||
if key == "variables": | ||
logging.info(f"Getting variables for {section}") | ||
|
||
for var in config[section][key]: | ||
try: | ||
firmware = FirmwareVariables() | ||
logging.info(f"Getting variable {var['name']} from {var['namespace']}") | ||
value = firmware.get_variable(var["name"], var["namespace"]) | ||
|
||
with open(os.path.join(VAR_DEBUG_DIR, f"{var['name']}.bin"), "wb") as f: | ||
f.write(value) | ||
logging.info(f"Saved: {os.path.join(VAR_DEBUG_DIR, f"{var['name']}.bin")}") | ||
except Exception as e: | ||
logging.error(f"Error: {e}") | ||
|
||
if __name__ == "__main__": | ||
|
||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# | ||
# This file is only meant to be used as a example for the Variables.ini file | ||
# These are real variables expected to exist in the UEFI firmware however other | ||
# variables may be accessed by the tool assuming the variable is marked with | ||
# the RUNTIME attr | ||
# | ||
|
||
[SECUREBOOT] | ||
|
||
[[SECUREBOOT.variables]] | ||
|
||
name = "PK" | ||
namespace = "{8be4df61-93ca-11d2-aa0d-00e098032b8c}" | ||
|
||
[[SECUREBOOT.variables]] | ||
|
||
name = "KEK" | ||
namespace = "{8be4df61-93ca-11d2-aa0d-00e098032b8c}" | ||
|
||
[[SECUREBOOT.variables]] | ||
|
||
name = "db" | ||
namespace = "{d719b2cb-3d3a-4596-a3bc-dad00e67656f}" | ||
|
||
[[SECUREBOOT.variables]] | ||
|
||
name = "dbx" | ||
namespace = "{d719b2cb-3d3a-4596-a3bc-dad00e67656f}" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This can be moved to a more generic location - this was left here as a way of making the script standalone