aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/CODE_OF_CONDUCT.md133
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.yml54
-rw-r--r--.github/ISSUE_TEMPLATE/config.yml1
-rw-r--r--.github/ISSUE_TEMPLATE/feature_request.yml25
-rw-r--r--.github/ISSUE_TEMPLATE/question.yml13
-rw-r--r--.github/img/BSOD.png (renamed from Misc/BSOD.png)bin3293 -> 3293 bytes
-rw-r--r--.github/img/EfiGuard.graphml410
-rw-r--r--.github/img/EfiGuard.svg (renamed from Misc/EfiGuard.svg)0
-rw-r--r--.github/img/Win7SecureBoot.pngbin0 -> 11666 bytes
-rw-r--r--Application/EfiDSEFix/src/EfiDSEFix.cpp165
-rw-r--r--Application/EfiDSEFix/src/EfiDSEFix.exe.manifest2
-rw-r--r--Application/EfiDSEFix/src/EfiDSEFix.vcxproj10
-rw-r--r--Application/EfiDSEFix/src/main.cpp68
-rw-r--r--Application/EfiDSEFix/src/sysinfo.cpp6
-rw-r--r--Application/Loader/Loader.c288
-rw-r--r--Application/Loader/Loader.inf10
-rw-r--r--Application/Loader/Loader.vcxproj4
-rw-r--r--EfiGuard.props4
-rw-r--r--EfiGuardDxe/EfiGuardDxe.c107
-rw-r--r--EfiGuardDxe/EfiGuardDxe.h5
-rw-r--r--EfiGuardDxe/EfiGuardDxe.inf5
-rw-r--r--EfiGuardDxe/EfiGuardDxe.vcxproj12
-rw-r--r--EfiGuardDxe/EfiGuardDxe.vcxproj.filters13
-rw-r--r--EfiGuardDxe/PatchNtoskrnl.c85
-rw-r--r--EfiGuardDxe/PatchWinload.c91
-rw-r--r--EfiGuardDxe/VisualUefi.c2
-rw-r--r--EfiGuardDxe/X64/Cet.asm37
-rw-r--r--EfiGuardDxe/X64/Cet.nasm36
-rw-r--r--EfiGuardDxe/util.c112
-rw-r--r--EfiGuardDxe/util.h50
-rw-r--r--EfiGuardPkg.dec9
-rw-r--r--EfiGuardPkg.dsc21
-rw-r--r--Include/Guid/LegacyBios.h24
-rw-r--r--Include/Protocol/EfiGuard.h14
-rw-r--r--Include/Protocol/LegacyBios.h1531
-rw-r--r--Misc/Win7SecureBoot.pngbin14419 -> 0 bytes
-rw-r--r--README.md58
37 files changed, 3021 insertions, 384 deletions
diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..409ec62
--- /dev/null
+++ b/.github/CODE_OF_CONDUCT.md
@@ -0,0 +1,133 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+mattiwatti@gmail.com.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
+
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..82834ef
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,54 @@
+name: Bug report
+description: Report bugs or other issues
+labels: ["bug"]
+
+body:
+ - type: markdown
+ attributes:
+ value: Before filing this bug, [please check if it hasn't already been reported](https://github.com/Mattiwatti/EfiGuard/issues?q=is%3Aissue+label%3Abug). If it has, please add useful information to the existing issue instead.
+
+ - type: input
+ id: os
+ attributes:
+ label: Operating system
+ placeholder: Windows 11 x64 build 22621
+ validations:
+ required: true
+
+ - type: textarea
+ id: description
+ attributes:
+ label: Issue description
+ description: Briefly describe your issue here.
+ validations:
+ required: true
+
+ - type: textarea
+ id: repro
+ attributes:
+ label: Steps to reproduce
+ description: Describe in small and detailed steps how to reproduce the issue.
+ value: |
+ 1.
+ 2.
+ validations:
+ required: true
+
+ - type: textarea
+ id: logs
+ attributes:
+ label: Logs
+ description: If you can provide relevant logs (e.g. of `analyze -v`), please paste them here. The output of `EfiDSEFix -i` is also often helpful when diagnosing EfiGuard issues.
+ placeholder: Paste logs here
+ render: shell
+ validations:
+ required: false
+
+ - type: textarea
+ id: attachments
+ attributes:
+ label: Attachments
+ description: If you can provide crash dumps, photos or screenshots that may help to investigate the issue, please add them here.
+ placeholder: Drag and drop files here
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..0086358
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1 @@
+blank_issues_enabled: true
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..844b990
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,25 @@
+name: Feature request
+description: Suggest features, modifications or ideas
+labels: ["feature"]
+
+body:
+ - type: markdown
+ attributes:
+ value: Before filing this request, [please check if it hasn't already been suggested before](https://github.com/Mattiwatti/EfiGuard/issues?q=is%3Aissue+label%3Afeature). If it has, please add to the existing issue instead.
+
+ - type: textarea
+ id: description
+ attributes:
+ label: Feature description
+ description: Briefly describe your idea, suggestion or proposed feature.
+ validations:
+ required: true
+
+ - type: textarea
+ id: implementation
+ attributes:
+ label: Implementation
+ description: Thoughts on possible implementation details go here (optional).
+ placeholder: Suggest how to implement the feature.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
new file mode 100644
index 0000000..d2442d8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -0,0 +1,13 @@
+name: Question
+description: Questions about EfiGuard
+labels: ["question"]
+
+body:
+ - type: textarea
+ id: description
+ attributes:
+ label: Question description
+ description: What is your question? Please make sure it is related to EfiGuard.
+ placeholder: Ask your question here.
+ validations:
+ required: true
diff --git a/Misc/BSOD.png b/.github/img/BSOD.png
index b19f938..b19f938 100644
--- a/Misc/BSOD.png
+++ b/.github/img/BSOD.png
Binary files differ
diff --git a/.github/img/EfiGuard.graphml b/.github/img/EfiGuard.graphml
new file mode 100644
index 0000000..a7ff148
--- /dev/null
+++ b/.github/img/EfiGuard.graphml
@@ -0,0 +1,410 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
+ <!--Created by yEd 3.23.1-->
+ <key attr.name="Description" attr.type="string" for="graph" id="d0">
+ <default xml:space="preserve"><![CDATA[EfiGuard]]></default>
+ </key>
+ <key attr.name="DiagramDescription" attr.type="string" for="graph" id="d1">
+ <default xml:space="preserve"/>
+ </key>
+ <key attr.name="CreationDescription" attr.type="string" for="graph" id="d2">
+ <default xml:space="preserve"/>
+ </key>
+ <key attr.name="Author" attr.type="string" for="graph" id="d3">
+ <default xml:space="preserve"><![CDATA[Matti]]></default>
+ </key>
+ <key attr.name="License" attr.type="string" for="graph" id="d4">
+ <default xml:space="preserve"/>
+ </key>
+ <key for="port" id="d5" yfiles.type="portgraphics"/>
+ <key for="port" id="d6" yfiles.type="portgeometry"/>
+ <key for="port" id="d7" yfiles.type="portuserdata"/>
+ <key attr.name="url" attr.type="string" for="node" id="d8"/>
+ <key attr.name="description" attr.type="string" for="node" id="d9"/>
+ <key for="node" id="d10" yfiles.type="nodegraphics"/>
+ <key for="graphml" id="d11" yfiles.type="resources"/>
+ <key attr.name="url" attr.type="string" for="edge" id="d12"/>
+ <key attr.name="description" attr.type="string" for="edge" id="d13"/>
+ <key for="edge" id="d14" yfiles.type="edgegraphics"/>
+ <graph edgedefault="directed" id="G">
+ <data key="d4" xml:space="preserve"><![CDATA[GPLv3]]></data>
+ <node id="n0">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="45.076530612244824" x="-175.5" y="452.34913217623495"/>
+ <y:Fill hasColor="false" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="46.03515625" x="51.40589126275506" xml:space="preserve" y="6.0">optional<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="-0.5" labelRatioY="0.0" nodeRatioX="0.5" nodeRatioY="0.011686197916666696" offsetX="6.329360650510239" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n1">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="65.0" width="107.39652870493995" x="194.15086782376468" y="121.5"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="78.033203125" x="14.681662789969977" xml:space="preserve" y="15.798828125">EFI
+Boot Services<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n2">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="65.0" width="107.39652870493995" x="396.5754339118823" y="121.5"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="98.03125" x="4.682639352470005" xml:space="preserve" y="15.798828125">EFI
+Runtime Services<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="roundrectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n3">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="454.0" y="278.0"/>
+ <y:Fill color="#FFFF99" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="63.361328125" x="15.8193359375" xml:space="preserve" y="17.6494140625">Winload.efi<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n4">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="320.0" y="278.0"/>
+ <y:Fill color="#FFFF99" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="65.359375" x="14.8203125" xml:space="preserve" y="17.6494140625">Bootmgr.efi<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n5">
+ <data key="d10">
+ <y:GenericNode configuration="com.yworks.flowchart.decision">
+ <y:Geometry height="34.69826435246998" width="69.39652870493995" x="210.0" y="287.650867823765"/>
+ <y:Fill color="#E8EEF7" color2="#B7C9E3" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="47.34765625" x="11.024436227469977" xml:space="preserve" y="7.998546238735003">WinPE?<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:StyleProperties>
+ <y:Property class="java.lang.Boolean" name="y.view.ShadowNodePainter.SHADOW_PAINTING" value="true"/>
+ </y:StyleProperties>
+ </y:GenericNode>
+ </data>
+ </node>
+ <node id="n6">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="75.5" y="278.0"/>
+ <y:Fill color="#FFFF99" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="73.36328125" x="10.818359375" xml:space="preserve" y="17.6494140625">Bootmgfw.efi<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n7">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="-59.0" y="278.0"/>
+ <y:Fill color="#CCFFFF" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="57.373046875" x="18.8134765625" xml:space="preserve" y="17.6494140625">Loader.efi<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n8">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="-193.5" y="278.0"/>
+ <y:Fill color="#FFCC00" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="61.357421875" x="16.8212890625" xml:space="preserve" y="10.298828125">EFI DXE
+Dispatcher<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n9">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="65.0" width="120.0" x="-71.5" y="121.5"/>
+ <y:Fill color="#000000" transparent="false"/>
+ <y:BorderStyle color="#333300" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="14" fontStyle="bold" hasBackgroundColor="false" hasLineColor="false" height="21.1513671875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#FFFFFF" verticalTextPosition="bottom" visible="true" width="109.02734375" x="5.486328125" xml:space="preserve" y="21.92431640625">EfiGuardDxe.efi<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n10">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="82.64842105263163" width="120.0" x="588.0" y="263.6757894736842"/>
+ <y:Fill color="#FFFF99" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="70.69140625" x="24.654296875" xml:space="preserve" y="24.623038651315824">
+Ntoskrnl.exe<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n11">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="588.0" y="263.6757894736842"/>
+ <y:Fill color="#3C679B" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#FFFFFF" verticalTextPosition="bottom" visible="true" width="21.337890625" x="4.3310546875" xml:space="preserve" y="5.6494140625">PG<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n12">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="30.0" width="30.0" x="618.0" y="263.6757894736842"/>
+ <y:Fill color="#3C679B" transparent="false"/>
+ <y:BorderStyle color="#000000" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#FFFFFF" verticalTextPosition="bottom" visible="true" width="28.673828125" x="0.6630859375" xml:space="preserve" y="5.6494140625">DSE<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n13">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="599.0" y="127.0"/>
+ <y:Fill color="#B7C9E3" transparent="false"/>
+ <y:BorderStyle color="#000000" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="42.68359375" x="26.158203125" xml:space="preserve" y="17.6494140625">HAL.dll<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n14">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="54.0" width="95.0" x="600.5" y="429.0"/>
+ <y:Fill color="#CCFFFF" transparent="false"/>
+ <y:BorderStyle color="#000000" type="dashed" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="81.35546875" x="6.822265625" xml:space="preserve" y="17.6494140625">EfiDSEFix.exe<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ <y:DropShadow color="#B3A691" offsetX="3" offsetY="3"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n15">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="1.0" width="901.5" x="-193.5" y="367.4596219520765"/>
+ <y:Fill color="#000000" transparent="false"/>
+ <y:BorderStyle hasColor="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="c" textColor="#000000" verticalTextPosition="bottom" visible="false" width="98.03125" x="401.734375" xml:space="preserve" y="-8.8505859375">UM-KM boundary</y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <node id="n16">
+ <data key="d10">
+ <y:ShapeNode>
+ <y:Geometry height="59.69826435246998" width="90.0" x="-188.5" y="338.1104897758415"/>
+ <y:Fill hasColor="false" transparent="false"/>
+ <y:BorderStyle hasColor="false" raised="false" type="line" width="1.0"/>
+ <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="72.0390625" x="8.98046875" xml:space="preserve" y="5.797374363735003">Kernel mode
+
+User mode<y:LabelModel><y:SmartNodeLabelModel distance="4.0"/></y:LabelModel><y:ModelParameter><y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="0.0" nodeRatioX="0.0" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/></y:ModelParameter></y:NodeLabel>
+ <y:Shape type="rectangle"/>
+ </y:ShapeNode>
+ </data>
+ </node>
+ <edge id="e0" source="n8" target="n9">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e1" source="n9" target="n8">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e2" source="n8" target="n7">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="-47.5" ty="0.0"/>
+ <y:LineStyle color="#000000" type="dashed" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e3" source="n7" target="n9">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="26.6875" x="5.65625" xml:space="preserve" y="-54.10058593750003">load<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="19.0" distanceToCenter="true" position="right" ratio="0.48407613597487015" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e4" source="n7" target="n6">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e5" source="n9" target="n1">
+ <data key="d14">
+ <y:SplineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="3.0"/>
+ <y:Arrows source="none" target="white_delta_bar"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="30.021484375" x="43.81469172438233" xml:space="preserve" y="0.6494140625">hook<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="10.0" distanceToCenter="true" position="right" ratio="0.3674611216793603" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ </y:SplineEdge>
+ </data>
+ </edge>
+ <edge id="e6" source="n1" target="n6">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="5.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="33.35546875" x="-72.6705149141558" xml:space="preserve" y="27.33786969399395">patch<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="19.7744190126584" distanceToCenter="true" position="right" ratio="0.35535919768994795" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ <y:StyleProperties>
+ <y:Property name="FramedEdgePainter.fillColor"/>
+ </y:StyleProperties>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e7" source="n10" target="n13">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="standard" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e8" source="n13" target="n2">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="standard" target="standard"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e9" source="n14" target="n10">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="1.0"/>
+ <y:Arrows source="standard" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="40.005859375" x="1.9970703125" xml:space="preserve" y="-43.688480674342145">syscall<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="22.0" distanceToCenter="true" position="right" ratio="0.3703094100258961" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ <edge id="e10" source="n5" target="n3">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">
+ <y:Point x="244.69826435246998" y="353.7882653061225"/>
+ <y:Point x="501.5" y="353.7882653061225"/>
+ </y:Path>
+ <y:LineStyle color="#000000" type="line" width="4.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="19.33984375" x="2.3300850311809427" xml:space="preserve" y="7.503055430631889">No<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="12.000000000000027" distanceToCenter="true" position="left" ratio="0.148887647823401" segment="0"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e11" source="n5" target="n4">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="4.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="24.677734375" x="-1.0267722686237448" xml:space="preserve" y="-20.3505859375">Yes<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="11.0" distanceToCenter="true" position="left" ratio="-6.037131539969948" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e12" source="n6" target="n5">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="4.0"/>
+ <y:Arrows source="none" target="standard"/>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e13" source="n4" target="n3">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="4.0"/>
+ <y:Arrows source="none" target="standard"/>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e14" source="n3" target="n10">
+ <data key="d14">
+ <y:GenericEdge configuration="com.yworks.edge.framed">
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
+ <y:LineStyle color="#000000" type="line" width="4.0"/>
+ <y:Arrows source="none" target="standard"/>
+ <y:EdgeLabel alignment="center" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" horizontalTextPosition="center" iconTextGap="4" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" verticalTextPosition="bottom" visible="true" width="33.35546875" x="3.322265625" xml:space="preserve" y="-25.3505859375">patch<y:LabelModel><y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/></y:LabelModel><y:ModelParameter><y:SmartEdgeLabelModelParameter angle="6.283185307179586" distance="16.0" distanceToCenter="true" position="left" ratio="0.5" segment="-1"/></y:ModelParameter><y:PreferredPlacementDescriptor angle="0.0" angleOffsetOnRightSide="0" angleReference="absolute" angleRotationOnRightSide="co" distance="-1.0" frozen="true" placement="anywhere" side="anywhere" sideReference="relative_to_edge_flow"/></y:EdgeLabel>
+ </y:GenericEdge>
+ </data>
+ </edge>
+ <edge id="e15" source="n9" target="n2">
+ <data key="d14">
+ <y:PolyLineEdge>
+ <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">
+ <y:Point x="-11.5" y="88.70000000000005"/>
+ <y:Point x="450.27369826435233" y="88.70000000000005"/>
+ </y:Path>
+ <y:LineStyle color="#000000" type="dashed" width="3.0"/>
+ <y:Arrows source="none" target="white_delta_bar"/>
+ <y:BendStyle smoothed="false"/>
+ </y:PolyLineEdge>
+ </data>
+ </edge>
+ </graph>
+ <data key="d11">
+ <y:Resources/>
+ </data>
+</graphml>
diff --git a/Misc/EfiGuard.svg b/.github/img/EfiGuard.svg
index d344fb2..d344fb2 100644
--- a/Misc/EfiGuard.svg
+++ b/.github/img/EfiGuard.svg
diff --git a/.github/img/Win7SecureBoot.png b/.github/img/Win7SecureBoot.png
new file mode 100644
index 0000000..24d04cd
--- /dev/null
+++ b/.github/img/Win7SecureBoot.png
Binary files differ
diff --git a/Application/EfiDSEFix/src/EfiDSEFix.cpp b/Application/EfiDSEFix/src/EfiDSEFix.cpp
index 924f759..03bfbba 100644
--- a/Application/EfiDSEFix/src/EfiDSEFix.cpp
+++ b/Application/EfiDSEFix/src/EfiDSEFix.cpp
@@ -31,11 +31,11 @@ FindKernelModule(
for (ULONG i = 0; i < Modules->NumberOfModules; ++i)
{
- RTL_PROCESS_MODULE_INFORMATION Module = Modules->Modules[i];
- if (_stricmp(ModuleName, reinterpret_cast<PCHAR>(Module.FullPathName) + Module.OffsetToFileName) == 0)
+ const PRTL_PROCESS_MODULE_INFORMATION Module = &Modules->Modules[i];
+ if (_stricmp(ModuleName, reinterpret_cast<PCHAR>(Module->FullPathName) + Module->OffsetToFileName) == 0)
{
- *ModuleBase = reinterpret_cast<ULONG_PTR>(Module.ImageBase);
- Status = Module.ImageBase == nullptr ? STATUS_NOT_FOUND : STATUS_SUCCESS;
+ *ModuleBase = reinterpret_cast<ULONG_PTR>(Module->ImageBase);
+ Status = Module->ImageBase == nullptr ? STATUS_NOT_FOUND : STATUS_SUCCESS;
break;
}
}
@@ -48,7 +48,7 @@ Exit:
// For Windows Vista/7. Credits: DSEFix by hfiref0x
static
LONG
-QueryCiEnabled(
+FindCiEnabled(
_In_ PVOID MappedBase,
_In_ SIZE_T SizeOfImage,
_In_ ULONG_PTR KernelBase,
@@ -73,7 +73,7 @@ QueryCiEnabled(
// For Windows 8 and worse. Credits: DSEFix by hfiref0x
static
LONG
-QueryCiOptions(
+FindCiOptions(
_In_ PVOID MappedBase,
_In_ ULONG_PTR CiDllBase,
_Out_ PULONG_PTR gCiOptionsAddress
@@ -183,34 +183,8 @@ QueryCiOptions(
}
static
-BOOLEAN
-QueryVbsEnabled(
- )
-{
- SYSTEM_CODEINTEGRITY_INFORMATION CodeIntegrityInfo = { sizeof(SYSTEM_CODEINTEGRITY_INFORMATION) };
- NTSTATUS Status = NtQuerySystemInformation(SystemCodeIntegrityInformation,
- &CodeIntegrityInfo,
- sizeof(CodeIntegrityInfo),
- nullptr);
- if (NT_SUCCESS(Status) &&
- (CodeIntegrityInfo.CodeIntegrityOptions & (CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED | CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED)) != 0)
- return TRUE;
-
- SYSTEM_ISOLATED_USER_MODE_INFORMATION IumInfo = { 0 };
- Status = NtQuerySystemInformation(SystemIsolatedUserModeInformation,
- &IumInfo,
- sizeof(IumInfo),
- nullptr);
- if (NT_SUCCESS(Status) &&
- (IumInfo.SecureKernelRunning || IumInfo.HvciEnabled))
- return TRUE;
-
- return FALSE;
-}
-
-static
NTSTATUS
-AnalyzeCi(
+FindCiOptionsVariable(
_Out_ PVOID *CiOptionsAddress
)
{
@@ -243,7 +217,7 @@ AnalyzeCi(
goto Exit;
ULONG_PTR gCiOptionsAddress;
- const LONG Relative = QueryCiOptions(MappedBase, CiDllBase, &gCiOptionsAddress);
+ const LONG Relative = FindCiOptions(MappedBase, CiDllBase, &gCiOptionsAddress);
if (Relative != 0)
{
*CiOptionsAddress = reinterpret_cast<PVOID>(gCiOptionsAddress);
@@ -263,7 +237,7 @@ AnalyzeCi(
goto Exit;
ULONG_PTR gCiEnabledAddress;
- const LONG Relative = QueryCiEnabled(MappedBase, ViewSize, KernelBase, &gCiEnabledAddress);
+ const LONG Relative = FindCiEnabled(MappedBase, ViewSize, KernelBase, &gCiEnabledAddress);
if (Relative != 0)
{
*CiOptionsAddress = reinterpret_cast<PVOID>(gCiEnabledAddress);
@@ -281,47 +255,29 @@ Exit:
}
static
-NTSTATUS
-SetSystemEnvironmentPrivilege(
- _In_ BOOLEAN Enable,
- _Out_opt_ PBOOLEAN WasEnabled
- )
-{
- if (WasEnabled != nullptr)
- *WasEnabled = FALSE;
-
- BOOLEAN SeSystemEnvironmentWasEnabled;
- const NTSTATUS Status = RtlAdjustPrivilege(SE_SYSTEM_ENVIRONMENT_PRIVILEGE,
- Enable,
- FALSE,
- &SeSystemEnvironmentWasEnabled);
-
- if (NT_SUCCESS(Status) && WasEnabled != nullptr)
- *WasEnabled = SeSystemEnvironmentWasEnabled;
-
- return Status;
-}
-
-static
-NTSTATUS
-SetDebugPrivilege(
- _In_ BOOLEAN Enable,
- _Out_opt_ PBOOLEAN WasEnabled
+BOOLEAN
+IsVbsEnabled(
)
{
- if (WasEnabled != nullptr)
- *WasEnabled = FALSE;
-
- BOOLEAN SeDebugWasEnabled;
- const NTSTATUS Status = RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE,
- Enable,
- FALSE,
- &SeDebugWasEnabled);
+ SYSTEM_CODEINTEGRITY_INFORMATION CodeIntegrityInfo = { sizeof(SYSTEM_CODEINTEGRITY_INFORMATION) };
+ NTSTATUS Status = NtQuerySystemInformation(SystemCodeIntegrityInformation,
+ &CodeIntegrityInfo,
+ sizeof(CodeIntegrityInfo),
+ nullptr);
+ if (NT_SUCCESS(Status) &&
+ (CodeIntegrityInfo.CodeIntegrityOptions & (CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED | CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED)) != 0)
+ return TRUE;
- if (NT_SUCCESS(Status) && WasEnabled != nullptr)
- *WasEnabled = SeDebugWasEnabled;
+ SYSTEM_ISOLATED_USER_MODE_INFORMATION IumInfo = { 0 };
+ Status = NtQuerySystemInformation(SystemIsolatedUserModeInformation,
+ &IumInfo,
+ sizeof(IumInfo),
+ nullptr);
+ if (NT_SUCCESS(Status) &&
+ (IumInfo.SecureKernelRunning || IumInfo.HvciEnabled))
+ return TRUE;
- return Status;
+ return FALSE;
}
NTSTATUS
@@ -330,24 +286,9 @@ TestSetVariableHook(
{
UINT16 Mz;
- // Enable privileges in case we were called directly from the CLI with --check
- BOOLEAN SeSystemEnvironmentWasEnabled, SeDebugWasEnabled;
- NTSTATUS Status = SetSystemEnvironmentPrivilege(TRUE, &SeSystemEnvironmentWasEnabled);
- if (!NT_SUCCESS(Status))
+ if (IsVbsEnabled())
{
- Printf(L"Fatal error: failed to acquire SE_SYSTEM_ENVIRONMENT_PRIVILEGE. Make sure you are running as administrator.\n");
- return Status;
- }
- Status = SetDebugPrivilege(TRUE, &SeDebugWasEnabled);
- if (!NT_SUCCESS(Status))
- {
- Printf(L"Fatal error: failed to acquire SE_DEBUG_PRIVILEGE. Make sure you are running as administrator.\n");
- return Status;
- }
-
- if (QueryVbsEnabled())
- {
- Printf(L"Fatal error: VBS (Virtualization Based Security) is enabled and running on this system.\n"
+ Printf(L"Error: VBS (Virtualization Based Security) is enabled and running on this system.\n"
"Attempting to read or write to or from kernel space using EFI runtime services will result in a bugcheck.\n"
"Either the EfiGuard DXE driver is not loaded, or it failed to disable VBS during boot.\n"
"Not continuing.\n");
@@ -356,19 +297,18 @@ TestSetVariableHook(
// Find some kernel address to read
ULONG_PTR HalBase;
- Status = FindKernelModule("hal.dll", &HalBase);
+ NTSTATUS Status = FindKernelModule("hal.dll", &HalBase);
if (!NT_SUCCESS(Status))
return Status;
- // Set up the struct for a backdoor kernel mode read. See TriggerExploit for explanations
+ // Set up the struct for a backdoor kernel mode read. See WriteToCiOptions for explanations
EFIGUARD_BACKDOOR_DATA BackdoorData;
RtlZeroMemory(&BackdoorData, sizeof(BackdoorData));
BackdoorData.CookieValue = EFIGUARD_BACKDOOR_COOKIE_VALUE;
BackdoorData.KernelAddress = reinterpret_cast<PVOID>(HalBase);
BackdoorData.u.Qword = UINT64_MAX; // Bogus value to verify write-back after the read operation
- BackdoorData.IsMemCopy = FALSE;
- BackdoorData.IsReadOperation = TRUE;
BackdoorData.Size = sizeof(UINT16);
+ BackdoorData.ReadOnly = TRUE;
// Call SetVariable()
UNICODE_STRING VariableName = RTL_CONSTANT_STRING(EFIGUARD_BACKDOOR_VARIABLE_NAME);
@@ -397,7 +337,7 @@ TestSetVariableHook(
if (!NT_SUCCESS(Status))
{
Printf(L"The EfiGuard DXE driver is either not loaded in SETVARIABLE_HOOK mode, or it is malfunctioning.\n");
- goto Exit;
+ return Status;
}
// Check if hal.dll still starts with "MZ"
@@ -409,16 +349,12 @@ TestSetVariableHook(
Status = STATUS_INVALID_IMAGE_NOT_MZ; // Literally
}
-Exit:
- SetSystemEnvironmentPrivilege(SeSystemEnvironmentWasEnabled, nullptr);
- SetDebugPrivilege(SeDebugWasEnabled, nullptr);
-
return Status;
}
static
NTSTATUS
-TriggerExploit(
+WriteToCiOptions(
_In_ PVOID CiVariableAddress,
_In_ ULONG CiOptionsValue,
_Out_opt_ PULONG OldCiOptionsValue,
@@ -447,9 +383,8 @@ TriggerExploit(
BackdoorData.u.s.Dword = static_cast<UINT32>(CiOptionsValue);
else if (CiPatchSize == sizeof(UINT8))
BackdoorData.u.s.Byte = static_cast<UINT8>(CiOptionsValue);
- BackdoorData.IsMemCopy = FALSE; // This is a scalar operation, not memcpy
- BackdoorData.IsReadOperation = ReadOnly; // Specify whether this is a read or a write operation
- BackdoorData.Size = CiPatchSize; // This value determines the field (Byte/Word/Dword/Qword) that the value to write will be read from, and written to on return
+ BackdoorData.Size = CiPatchSize; // Determines which field the value will be read/written from/to
+ BackdoorData.ReadOnly = ReadOnly; // Whether this is a read or read + write
// Call NtSetSystemEnvironmentValueEx -> [...] -> hal!HalSetEnvironmentVariableEx -> hal!HalEfiSetEnvironmentVariable -> EfiRT->SetVariable.
// On Windows >= 8 it is possible to use SetFirmwareEnvironmentVariableExW. We use the syscall directly because it exists on Windows 7 and Vista.
@@ -475,6 +410,8 @@ TriggerExploit(
*OldCiOptionsValue = OldCiOptions;
}
+ RtlZeroMemory(&BackdoorData, sizeof(BackdoorData));
+
return STATUS_SUCCESS;
}
@@ -488,38 +425,18 @@ AdjustCiOptions(
if (OldCiOptionsValue != nullptr)
*OldCiOptionsValue = CODEINTEGRITY_OPTION_ENABLED;
- // Enable privileges
- BOOLEAN SeSystemEnvironmentWasEnabled, SeDebugWasEnabled;
- NTSTATUS Status = SetSystemEnvironmentPrivilege(TRUE, &SeSystemEnvironmentWasEnabled);
- if (!NT_SUCCESS(Status))
- {
- Printf(L"Fatal error: failed to acquire SE_SYSTEM_ENVIRONMENT_PRIVILEGE. Make sure you are running as administrator.\n");
- return Status;
- }
- Status = SetDebugPrivilege(TRUE, &SeDebugWasEnabled);
- if (!NT_SUCCESS(Status))
- {
- Printf(L"Fatal error: failed to acquire SE_DEBUG_PRIVILEGE. Make sure you are running as administrator.\n");
- return Status;
- }
-
// Find CI!g_CiOptions/nt!g_CiEnabled
PVOID CiOptionsAddress;
- Status = AnalyzeCi(&CiOptionsAddress);
+ NTSTATUS Status = FindCiOptionsVariable(&CiOptionsAddress);
if (!NT_SUCCESS(Status))
return Status;
Printf(L"%ls at 0x%p.\n", (NtCurrentPeb()->OSBuildNumber >= 9200 ? L"CI!g_CiOptions" : L"nt!g_CiEnabled"), CiOptionsAddress);
// Enable/disable CI
- Status = TriggerExploit(CiOptionsAddress,
+ Status = WriteToCiOptions(CiOptionsAddress,
CiOptionsValue,
OldCiOptionsValue,
ReadOnly);
-
- // Revert privileges
- SetSystemEnvironmentPrivilege(SeSystemEnvironmentWasEnabled, nullptr);
- SetDebugPrivilege(SeDebugWasEnabled, nullptr);
-
return Status;
}
diff --git a/Application/EfiDSEFix/src/EfiDSEFix.exe.manifest b/Application/EfiDSEFix/src/EfiDSEFix.exe.manifest
index af2f7de..16afbf5 100644
--- a/Application/EfiDSEFix/src/EfiDSEFix.exe.manifest
+++ b/Application/EfiDSEFix/src/EfiDSEFix.exe.manifest
@@ -3,7 +3,7 @@
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
- <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
diff --git a/Application/EfiDSEFix/src/EfiDSEFix.vcxproj b/Application/EfiDSEFix/src/EfiDSEFix.vcxproj
index 44675b5..c588f60 100644
--- a/Application/EfiDSEFix/src/EfiDSEFix.vcxproj
+++ b/Application/EfiDSEFix/src/EfiDSEFix.vcxproj
@@ -26,6 +26,8 @@
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v143</PlatformToolset>
<SpectreMitigation>false</SpectreMitigation>
+ <VcpkgEnabled>false</VcpkgEnabled>
+ <EnableStdModules>false</EnableStdModules>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release (native subsystem)|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
@@ -34,6 +36,8 @@
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v143</PlatformToolset>
<SpectreMitigation>false</SpectreMitigation>
+ <VcpkgEnabled>false</VcpkgEnabled>
+ <EnableStdModules>false</EnableStdModules>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
@@ -62,7 +66,7 @@
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<LanguageStandard>stdcpplatest</LanguageStandard>
- <AdditionalOptions>/Gw /utf-8 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalOptions>/Gw /utf-8 /Zc:threadSafeInit- %(AdditionalOptions)</AdditionalOptions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DisableSpecificWarnings>4201</DisableSpecificWarnings>
<ExceptionHandling>false</ExceptionHandling>
@@ -71,6 +75,7 @@
<AdditionalIncludeDirectories>$(SolutionDir)Include;$(SolutionDir)../MdePkg/Include;$(SolutionDir)../MdePkg/Include/X64;$(SolutionDir)../MdeModulePkg/Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<IntrinsicFunctions>true</IntrinsicFunctions>
<BuildStlModules>false</BuildStlModules>
+ <EnableModules>false</EnableModules>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -101,7 +106,7 @@
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<LanguageStandard>stdcpplatest</LanguageStandard>
- <AdditionalOptions>/Gw /utf-8 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalOptions>/Gw /utf-8 /Zc:threadSafeInit- %(AdditionalOptions)</AdditionalOptions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DisableSpecificWarnings>4201</DisableSpecificWarnings>
<ExceptionHandling>false</ExceptionHandling>
@@ -110,6 +115,7 @@
<AdditionalIncludeDirectories>$(SolutionDir)Include;$(SolutionDir)../MdePkg/Include;$(SolutionDir)../MdePkg/Include/X64;$(SolutionDir)../MdeModulePkg/Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<IntrinsicFunctions>true</IntrinsicFunctions>
<BuildStlModules>false</BuildStlModules>
+ <EnableModules>false</EnableModules>
</ClCompile>
<Link>
<SubSystem>Native</SubSystem>
diff --git a/Application/EfiDSEFix/src/main.cpp b/Application/EfiDSEFix/src/main.cpp
index 50e336a..8cd8cb9 100644
--- a/Application/EfiDSEFix/src/main.cpp
+++ b/Application/EfiDSEFix/src/main.cpp
@@ -9,13 +9,13 @@ PrintUsage(
{
const BOOLEAN Win8OrHigher = (RtlNtMajorVersion() >= 6 && RtlNtMinorVersion() >= 2) || RtlNtMajorVersion() > 6;
const PCWCHAR CiOptionsName = Win8OrHigher ? L"g_CiOptions" : L"g_CiEnabled";
- Printf(L"\nUsage: %ls [COMMAND]\n\n"
- L"Commands:\n\n"
- L"-c, --check%17lsTest backdoor hook\n"
- L"-r, --read%18lsRead current %ls value\n"
- L"-d, --disable%15lsDisable DSE\n"
- L"-e, --enable%ls%2ls(Re)enable DSE\n"
- L"-i, --info%18lsDump system info\n",
+ Printf(L"\nUsage: %ls <COMMAND>\n\n"
+ L"Commands:\n"
+ L" -c, --check%17lsTest EFI SetVariable hook\n"
+ L" -r, --read%18lsRead current %ls value\n"
+ L" -d, --disable%15lsDisable DSE\n"
+ L" -e, --enable%ls%2ls(Re)enable DSE\n"
+ L" -i, --info%18lsDump system info\n",
ProgramName, L"", L"",
CiOptionsName, L"",
(Win8OrHigher ? L" [g_CiOptions]" : L" "),
@@ -26,14 +26,31 @@ int wmain(int argc, wchar_t** argv)
{
NT_ASSERT(argc != 0);
- if (argc == 1 || argc > 3 ||
- (argc == 3 && wcstoul(argv[2], nullptr, 16) == 0))
+ if (argc <= 1 || argc > 3 ||
+ (argc == 3 && wcstoul(argv[2], nullptr, 16) == 0) ||
+ wcsncmp(argv[1], L"-h", sizeof(L"-h") / sizeof(WCHAR) - 1) == 0 ||
+ wcsncmp(argv[1], L"--help", sizeof(L"--help") / sizeof(WCHAR) - 1) == 0)
{
// Print help text
PrintUsage(argv[0]);
return 0;
}
+ // All remaining commands require admin privileges
+ BOOLEAN SeSystemEnvironmentWasEnabled, SeDebugWasEnabled;
+ NTSTATUS Status = RtlAdjustPrivilege(SE_SYSTEM_ENVIRONMENT_PRIVILEGE, TRUE, FALSE, &SeSystemEnvironmentWasEnabled);
+ if (!NT_SUCCESS(Status))
+ {
+ Printf(L"Error: failed to acquire SE_SYSTEM_ENVIRONMENT_PRIVILEGE.\n%ls must be run as Administrator.\n", argv[0]);
+ return Status;
+ }
+ Status = RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &SeDebugWasEnabled);
+ if (!NT_SUCCESS(Status))
+ {
+ Printf(L"Error: failed to acquire SE_DEBUG_PRIVILEGE.\n%ls must be run as Administrator.\n", argv[0]);
+ return Status;
+ }
+
// Parse command line params
const BOOLEAN Win8OrHigher = (RtlNtMajorVersion() >= 6 && RtlNtMinorVersion() >= 2) || RtlNtMajorVersion() > 6;
const ULONG EnabledCiOptionsValue = Win8OrHigher ? 0x6 : CODEINTEGRITY_OPTION_ENABLED;
@@ -41,15 +58,6 @@ int wmain(int argc, wchar_t** argv)
ULONG CiOptionsValue;
BOOLEAN ReadOnly = FALSE;
- if (wcsncmp(argv[1], L"-c", sizeof(L"-c") / sizeof(WCHAR) - 1) == 0 ||
- wcsncmp(argv[1], L"--check", sizeof(L"--check") / sizeof(WCHAR) - 1) == 0)
- {
- Printf(L"Checking for working EFI SetVariable() backdoor...\n");
- const NTSTATUS Status = TestSetVariableHook();
- if (NT_SUCCESS(Status)) // Any errors have already been printed
- Printf(L"Success!\n");
- return Status;
- }
if (wcsncmp(argv[1], L"-r", sizeof(L"-r") / sizeof(WCHAR) - 1) == 0 ||
wcsncmp(argv[1], L"--read", sizeof(L"--read") / sizeof(WCHAR) - 1) == 0)
{
@@ -77,20 +85,31 @@ int wmain(int argc, wchar_t** argv)
Printf(L"(Re)enabling DSE...\n");
}
}
+ else if (wcsncmp(argv[1], L"-c", sizeof(L"-c") / sizeof(WCHAR) - 1) == 0 ||
+ wcsncmp(argv[1], L"--check", sizeof(L"--check") / sizeof(WCHAR) - 1) == 0)
+ {
+ Printf(L"Checking for working EFI SetVariable hook...\n");
+ Status = TestSetVariableHook();
+ if (NT_SUCCESS(Status)) // Any errors have already been printed
+ Printf(L"Success.\n");
+ goto Exit;
+ }
else if (wcsncmp(argv[1], L"-i", sizeof(L"-i") / sizeof(WCHAR) - 1) == 0 ||
wcsncmp(argv[1], L"--info", sizeof(L"--info") / sizeof(WCHAR) - 1) == 0)
{
- return DumpSystemInformation();
+ Status = DumpSystemInformation();
+ goto Exit;
}
else
{
PrintUsage(argv[0]);
- return STATUS_INVALID_PARAMETER;
+ Status = STATUS_INVALID_PARAMETER;
+ goto Exit;
}
- // Trigger EFI driver exploit and write new value to g_CiOptions/g_CiEnabled
+ // Call EFI runtime SetVariable service and write new value to g_CiOptions/g_CiEnabled
ULONG OldCiOptionsValue;
- const NTSTATUS Status = AdjustCiOptions(CiOptionsValue, &OldCiOptionsValue, ReadOnly);
+ Status = AdjustCiOptions(CiOptionsValue, &OldCiOptionsValue, ReadOnly);
// Print result
if (!NT_SUCCESS(Status))
@@ -105,6 +124,11 @@ int wmain(int argc, wchar_t** argv)
Printf(L"Successfully %ls DSE. Original", CiOptionsValue == 0 ? L"disabled" : L"(re)enabled");
Printf(L" %ls value: 0x%lX\n", CiOptionsName, OldCiOptionsValue);
}
+
+Exit:
+ RtlAdjustPrivilege(SE_SYSTEM_ENVIRONMENT_PRIVILEGE, SeSystemEnvironmentWasEnabled, FALSE, &SeSystemEnvironmentWasEnabled);
+ RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, SeDebugWasEnabled, FALSE, &SeDebugWasEnabled);
+
return Status;
}
diff --git a/Application/EfiDSEFix/src/sysinfo.cpp b/Application/EfiDSEFix/src/sysinfo.cpp
index 6b236e4..a0ad289 100644
--- a/Application/EfiDSEFix/src/sysinfo.cpp
+++ b/Application/EfiDSEFix/src/sysinfo.cpp
@@ -75,10 +75,10 @@ DumpSystemInformation(
Printf(L"SystemModuleInformation: %08lX\n\n", Status);
else
{
- const RTL_PROCESS_MODULE_INFORMATION Ntoskrnl = ModuleInfo->Modules[0];
+ const PRTL_PROCESS_MODULE_INFORMATION Ntoskrnl = &ModuleInfo->Modules[0];
Printf(L"SystemModuleInformation:\n\t- Kernel: %S (%S)\n\n",
- reinterpret_cast<PCCH>(Ntoskrnl.FullPathName + Ntoskrnl.OffsetToFileName),
- reinterpret_cast<PCCH>(Ntoskrnl.FullPathName));
+ reinterpret_cast<PCCH>(Ntoskrnl->FullPathName + Ntoskrnl->OffsetToFileName),
+ reinterpret_cast<PCCH>(Ntoskrnl->FullPathName));
}
RtlFreeHeap(RtlProcessHeap(), 0, ModuleInfo);
}
diff --git a/Application/Loader/Loader.c b/Application/Loader/Loader.c
index 665b2fe..aab4a5c 100644
--- a/Application/Loader/Loader.c
+++ b/Application/Loader/Loader.c
@@ -5,9 +5,11 @@
#include <Protocol/SimpleFileSystem.h>
#include <Protocol/LoadedImage.h>
#include <Protocol/LegacyBios.h>
+#include <Library/PcdLib.h>
#include <Library/UefiLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
+#include <Library/ReportStatusCodeLib.h>
#include <Library/DevicePathLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiBootManagerLib.h>
@@ -15,16 +17,6 @@
//
-// Define whether the loader should prompt for driver configuration or not.
-// If this is 0, the defaults are used and Windows will be booted with no user interaction.
-// This can be overridden on the command line with -D CONFIGURE_DRIVER=[0|1]
-//
-#ifndef CONFIGURE_DRIVER
-#define CONFIGURE_DRIVER 0
-#endif
-
-
-//
// Paths to the driver to try
//
#ifndef EFIGUARD_DRIVER_FILENAME
@@ -36,6 +28,13 @@ STATIC CHAR16* mDriverPaths[] = {
L"\\" EFIGUARD_DRIVER_FILENAME
};
+STATIC EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *mTextInputEx = NULL;
+
+VOID
+EFIAPI
+BmRepairAllControllers(
+ IN UINTN ReconnectRepairCount
+ );
VOID
EFIAPI
@@ -43,23 +42,65 @@ BmSetMemoryTypeInformationVariable(
IN BOOLEAN Boot
);
+BOOLEAN
+EFIAPI
+BmIsAutoCreateBootOption(
+ IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
+ );
STATIC
-BOOLEAN
+VOID
+ResetTextInput(
+ VOID
+ )
+{
+ if (mTextInputEx != NULL)
+ mTextInputEx->Reset(mTextInputEx, FALSE);
+ else
+ gST->ConIn->Reset(gST->ConIn, FALSE);
+}
+
+STATIC
+UINT16
EFIAPI
WaitForKey(
VOID
)
{
- EFI_INPUT_KEY Key = { 0, 0 };
+ EFI_KEY_DATA KeyData = { 0 };
UINTN Index = 0;
- gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &Index);
- gST->ConIn->ReadKeyStroke(gST->ConIn, &Key);
-
- return Key.ScanCode != SCAN_ESC;
+ if (mTextInputEx != NULL)
+ {
+ gBS->WaitForEvent(1, &mTextInputEx->WaitForKeyEx, &Index);
+ mTextInputEx->ReadKeyStrokeEx(mTextInputEx, &KeyData);
+ }
+ else
+ {
+ gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &Index);
+ gST->ConIn->ReadKeyStroke(gST->ConIn, &KeyData.Key);
+ }
+ return KeyData.Key.ScanCode;
}
-#if CONFIGURE_DRIVER
+STATIC
+UINT16
+EFIAPI
+WaitForKeyWithTimeout(
+ IN UINTN Milliseconds
+ )
+{
+ ResetTextInput();
+ gBS->Stall(Milliseconds * 1000);
+
+ EFI_KEY_DATA KeyData = { 0 };
+ if (mTextInputEx != NULL)
+ mTextInputEx->ReadKeyStrokeEx(mTextInputEx, &KeyData);
+ else
+ gST->ConIn->ReadKeyStroke(gST->ConIn, &KeyData.Key);
+
+ ResetTextInput();
+ return KeyData.Key.ScanCode;
+}
STATIC
UINT16
@@ -76,12 +117,20 @@ PromptInput(
{
SelectedChar = CHAR_NULL;
- EFI_INPUT_KEY Key = { 0, 0 };
+ EFI_KEY_DATA KeyData = { 0 };
UINTN Index = 0;
- gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &Index);
- gST->ConIn->ReadKeyStroke(gST->ConIn, &Key);
+ if (mTextInputEx != NULL)
+ {
+ gBS->WaitForEvent(1, &mTextInputEx->WaitForKeyEx, &Index);
+ mTextInputEx->ReadKeyStrokeEx(mTextInputEx, &KeyData);
+ }
+ else
+ {
+ gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &Index);
+ gST->ConIn->ReadKeyStroke(gST->ConIn, &KeyData.Key);
+ }
- if (Key.UnicodeChar == CHAR_LINEFEED || Key.UnicodeChar == CHAR_CARRIAGE_RETURN)
+ if (KeyData.Key.UnicodeChar == CHAR_LINEFEED || KeyData.Key.UnicodeChar == CHAR_CARRIAGE_RETURN)
{
SelectedChar = DefaultSelection;
break;
@@ -89,9 +138,9 @@ PromptInput(
for (UINTN i = 0; i < NumAcceptedChars; ++i)
{
- if (Key.UnicodeChar == AcceptedChars[i])
+ if (KeyData.Key.UnicodeChar == AcceptedChars[i])
{
- SelectedChar = Key.UnicodeChar;
+ SelectedChar = KeyData.Key.UnicodeChar;
break;
}
}
@@ -104,8 +153,43 @@ PromptInput(
return SelectedChar;
}
-#endif
+STATIC
+CONST CHAR16*
+EFIAPI
+StriStr(
+ IN CONST CHAR16 *String1,
+ IN CONST CHAR16 *String2
+ )
+{
+ if (*String2 == L'\0')
+ return String1;
+
+ while (*String1 != L'\0')
+ {
+ CONST CHAR16* FirstMatch = String1;
+ CONST CHAR16* String2Ptr = String2;
+ CHAR16 String1Char = CharToUpper(*String1);
+ CHAR16 String2Char = CharToUpper(*String2Ptr);
+
+ while (String1Char == String2Char && String1Char != L'\0')
+ {
+ String1++;
+ String2Ptr++;
+
+ String1Char = CharToUpper(*String1);
+ String2Char = CharToUpper(*String2Ptr);
+ }
+
+ if (String2Char == L'\0')
+ return FirstMatch;
+ if (String1Char == L'\0')
+ return NULL;
+
+ String1 = FirstMatch + 1;
+ }
+ return NULL;
+}
//
// Try to find a file by browsing each device
@@ -156,7 +240,8 @@ LocateFile(
EFI_FILE_READ_ONLY);
if (!EFI_ERROR(Status))
{
- VolumeHandle->Close(FileHandle);
+ FileHandle->Close(FileHandle);
+ VolumeHandle->Close(VolumeHandle);
*DevicePath = FileDevicePath(Handles[i], ImagePath);
CHAR16 *PathString = ConvertDevicePathToText(*DevicePath, TRUE, TRUE);
DEBUG((DEBUG_INFO, "[LOADER] Found file at %S.\r\n", PathString));
@@ -164,9 +249,10 @@ LocateFile(
FreePool(PathString);
break;
}
+ VolumeHandle->Close(VolumeHandle);
}
- FreePool(Handles);
+ FreePool((VOID*)Handles);
return Status;
}
@@ -219,9 +305,8 @@ SetHighestAvailableTextMode(
STATIC
EFI_STATUS
EFIAPI
-StartAndConfigureDriver(
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE* SystemTable
+StartEfiGuard(
+ IN BOOLEAN InteractiveConfiguration
)
{
EFIGUARD_DRIVER_PROTOCOL* EfiGuardDriverProtocol;
@@ -251,7 +336,7 @@ StartAndConfigureDriver(
EFI_HANDLE DriverHandle = NULL;
Status = gBS->LoadImage(FALSE, // Request is not from boot manager
- ImageHandle,
+ gImageHandle,
DriverDevicePath,
NULL,
0,
@@ -268,58 +353,65 @@ StartAndConfigureDriver(
Print(L"[LOADER] StartImage failed: %llx (%r).\r\n", Status, Status);
goto Exit;
}
-
- Status = gBS->LocateProtocol(&gEfiGuardDriverProtocolGuid,
- NULL,
- (VOID**)&EfiGuardDriverProtocol);
- if (EFI_ERROR(Status))
- {
- Print(L"[LOADER] LocateProtocol failed: %llx (%r).\r\n", Status, Status);
- goto Exit;
- }
}
else
{
+ ASSERT_EFI_ERROR(Status);
Print(L"[LOADER] The driver is already loaded.\r\n");
- Status = EFI_ALREADY_STARTED;
+ }
+
+ Status = gBS->LocateProtocol(&gEfiGuardDriverProtocolGuid,
+ NULL,
+ (VOID**)&EfiGuardDriverProtocol);
+ if (EFI_ERROR(Status))
+ {
+ Print(L"[LOADER] LocateProtocol failed: %llx (%r).\r\n", Status, Status);
goto Exit;
}
-#if CONFIGURE_DRIVER
- //
- // Interactive driver configuration
- //
- Print(L"\r\nChoose the type of DSE bypass to use, or press ENTER for default:\r\n"
- L" [1] No DSE bypass\r\n [2] Boot time DSE bypass\r\n [3] Runtime SetVariable hook (default)\r\n ");
- CONST UINT16 AcceptedDseBypasses[] = { L'1', L'2', L'3' };
- CONST UINT16 SelectedDseBypass = PromptInput(AcceptedDseBypasses,
- sizeof(AcceptedDseBypasses) / sizeof(UINT16),
- L'3');
-
- Print(L"Wait for a keypress to continue after each patch stage? (for debugging)\n"
- L" [1] Yes\r\n [2] No (default)\r\n ");
- CONST UINT16 YesNo[] = { L'1', L'2' };
- CONST UINT16 SelectedWaitForKeyPress = PromptInput(YesNo,
- sizeof(YesNo) / sizeof(UINT16),
- L'2');
-
- EFIGUARD_CONFIGURATION_DATA ConfigData;
- if (SelectedDseBypass == L'1')
- ConfigData.DseBypassMethod = DSE_DISABLE_NONE;
- else if (SelectedDseBypass == L'2')
- ConfigData.DseBypassMethod = DSE_DISABLE_AT_BOOT;
- else
- ConfigData.DseBypassMethod = DSE_DISABLE_SETVARIABLE_HOOK;
- ConfigData.WaitForKeyPress = (BOOLEAN)(SelectedWaitForKeyPress == L'1');
+ if (InteractiveConfiguration)
+ {
+ //
+ // Interactive driver configuration
+ //
+ Print(L"\r\nChoose the type of DSE bypass to use, or press ENTER for default:\r\n"
+ L" [1] Runtime SetVariable hook (default)\r\n [2] Boot time DSE bypass\r\n [3] No DSE bypass\r\n ");
+ CONST UINT16 AcceptedDseBypasses[] = { L'1', L'2', L'3' };
+ CONST UINT16 SelectedDseBypass = PromptInput(AcceptedDseBypasses,
+ sizeof(AcceptedDseBypasses) / sizeof(UINT16),
+ L'1');
+
+ Print(L"Wait for a keypress to continue after each patch stage?\n"
+ L" [1] No (default)\r\n [2] Yes (for debugging)\r\n ");
+ CONST UINT16 NoYes[] = { L'1', L'2' };
+ CONST UINT16 SelectedWaitForKeyPress = PromptInput(NoYes,
+ sizeof(NoYes) / sizeof(UINT16),
+ L'1');
+
+ EFIGUARD_CONFIGURATION_DATA ConfigData;
+ switch (SelectedDseBypass)
+ {
+ case L'1':
+ default:
+ ConfigData.DseBypassMethod = DSE_DISABLE_SETVARIABLE_HOOK;
+ break;
+ case L'2':
+ ConfigData.DseBypassMethod = DSE_DISABLE_AT_BOOT;
+ break;
+ case L'3':
+ ConfigData.DseBypassMethod = DSE_DISABLE_NONE;
+ break;
+ }
+ ConfigData.WaitForKeyPress = (BOOLEAN)(SelectedWaitForKeyPress == L'2');
- //
- // Send the configuration data to the driver
- //
- Status = EfiGuardDriverProtocol->Configure(&ConfigData);
+ //
+ // Send the configuration data to the driver
+ //
+ Status = EfiGuardDriverProtocol->Configure(&ConfigData);
- if (EFI_ERROR(Status))
- Print(L"[LOADER] Driver Configure() returned error %llx (%r).\r\n", Status, Status);
-#endif
+ if (EFI_ERROR(Status))
+ Print(L"[LOADER] Driver Configure() returned error %llx (%r).\r\n", Status, Status);
+ }
Exit:
if (DriverDevicePath != NULL)
@@ -406,8 +498,7 @@ TryBootOptionsInOrder(
// but for some types of boots the filename will always be bootx64.efi, so this can't be avoided.
if (!MaybeWindows &&
ConvertedPath != NULL &&
- (StrStr(ConvertedPath, L"bootmgfw.efi") != NULL || StrStr(ConvertedPath, L"BOOTMGFW.EFI") != NULL ||
- StrStr(ConvertedPath, L"bootx64.efi") != NULL || StrStr(ConvertedPath, L"BOOTX64.EFI") != NULL))
+ (StriStr(ConvertedPath, L"bootmgfw.efi") != NULL || StriStr(ConvertedPath, L"bootx64.efi") != NULL))
{
MaybeWindows = TRUE;
}
@@ -426,7 +517,9 @@ TryBootOptionsInOrder(
// Print what we're booting
if (ConvertedPath != NULL)
{
- Print(L"Booting %Sdevice path %S...\r\n", IsLegacy ? L"legacy " : L"", ConvertedPath);
+ Print(L"Booting \"%S\"...\r\n -> %S = %S\r\n",
+ (BootOptions[Index].Description != NULL ? BootOptions[Index].Description : L"<null description>"),
+ IsLegacy ? L"Legacy path" : L"Path", ConvertedPath);
FreePool(ConvertedPath);
}
@@ -449,6 +542,13 @@ TryBootOptionsInOrder(
// Signal the EVT_SIGNAL_READY_TO_BOOT event
EfiSignalEventReadyToBoot();
+ REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_READY_TO_BOOT_EVENT));
+
+ // Repair system through DriverHealth protocol
+ BmRepairAllControllers(0);
+
+ // Save the memory map in the MemoryTypeInformation variable for resuming from ACPI S4 (hibernate)
+ BmSetMemoryTypeInformationVariable((BootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_BOOT);
// Handle BBS entries
if (IsLegacy)
@@ -470,18 +570,12 @@ TryBootOptionsInOrder(
return !EFI_ERROR(BootOptions[Index].Status);
}
- // So again, DO NOT call this abortion:
- //BmSetMemoryTypeInformationVariable((BOOLEAN)((BootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_BOOT));
- //
- // OK, maybe call it after all, but pretend this is *not* a boot entry, so that the system will not go into an infinite boot (reset) loop.
- // This may or may not fix hibernation related issues (S4 entry/resume). See https://github.com/Mattiwatti/EfiGuard/issues/12
- BmSetMemoryTypeInformationVariable(FALSE);
-
// Ensure the image path is connected end-to-end by Dispatch()ing any required drivers through DXE services
EfiBootManagerConnectDevicePath(BootOptions[Index].FilePath, NULL);
// Instead of creating a ramdisk and reading the file into it (¿que?), just pass the path we saved earlier.
// This is the point where the driver kicks in via its LoadImage hook.
+ REPORT_STATUS_CODE(EFI_PROGRESS_CODE, PcdGet32(PcdProgressCodeOsLoaderLoad));
EFI_HANDLE ImageHandle = NULL;
Status = gBS->LoadImage(TRUE,
gImageHandle,
@@ -500,6 +594,7 @@ TryBootOptionsInOrder(
gBS->UnloadImage(ImageHandle);
Print(L"LoadImage error %llx (%r)\r\n", Status, Status);
+ BootOptions[Index].Status = Status;
continue;
}
@@ -514,8 +609,11 @@ TryBootOptionsInOrder(
ASSERT_EFI_ERROR(Status);
// Set image load options from the boot option
- ImageInfo->LoadOptionsSize = BootOptions[Index].OptionalDataSize;
- ImageInfo->LoadOptions = BootOptions[Index].OptionalData;
+ if (!BmIsAutoCreateBootOption(&BootOptions[Index]))
+ {
+ ImageInfo->LoadOptionsSize = BootOptions[Index].OptionalDataSize;
+ ImageInfo->LoadOptions = BootOptions[Index].OptionalData;
+ }
// "Clean to NULL because the image is loaded directly from the firmware's boot manager." (EDK2) Good call, I agree
ImageInfo->ParentHandle = NULL;
@@ -524,6 +622,7 @@ TryBootOptionsInOrder(
gBS->SetWatchdogTimer((UINTN)(5 * 60), 0x0000, 0x00, NULL);
// Start the image and set the return code in the boot option status
+ REPORT_STATUS_CODE(EFI_PROGRESS_CODE, PcdGet32(PcdProgressCodeOsLoaderStart));
Status = gBS->StartImage(ImageHandle,
&BootOptions[Index].ExitDataSize,
&BootOptions[Index].ExitData);
@@ -579,19 +678,28 @@ UefiMain(
gBS->SetWatchdogTimer(0, 0, 0, NULL);
//
- // Locate, load, start and configure the driver
+ // Query the console input handle for the Simple Text Input Ex protocol
//
- CONST EFI_STATUS DriverStatus = StartAndConfigureDriver(ImageHandle, SystemTable);
- if (DriverStatus == EFI_ALREADY_STARTED)
- return EFI_SUCCESS;
+ gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&mTextInputEx);
+ //
+ // Allow user to configure the driver by pressing a hotkey
+ //
+ Print(L"Press <HOME> to configure EfiGuard...\r\n");
+ CONST BOOLEAN InteractiveConfiguration = WaitForKeyWithTimeout(1500) == SCAN_HOME;
+
+ //
+ // Locate, load, start and configure the driver
+ //
+ CONST EFI_STATUS DriverStatus = StartEfiGuard(InteractiveConfiguration);
if (EFI_ERROR(DriverStatus))
{
Print(L"\r\nERROR: driver load failed with status %llx (%r).\r\n"
L"Press any key to continue, or press ESC to return to the firmware or shell.\r\n",
DriverStatus, DriverStatus);
- if (!WaitForKey())
+ if (WaitForKey() == SCAN_ESC)
{
+ gBS->Exit(gImageHandle, DriverStatus, 0, NULL);
return DriverStatus;
}
}
diff --git a/Application/Loader/Loader.inf b/Application/Loader/Loader.inf
index e817bd5..8d98034 100644
--- a/Application/Loader/Loader.inf
+++ b/Application/Loader/Loader.inf
@@ -14,13 +14,13 @@
MdePkg/MdePkg.dec
EfiGuardPkg/EfiGuardPkg.dec
MdeModulePkg/MdeModulePkg.dec
- OvmfPkg/OvmfPkg.dec
[LibraryClasses]
UefiApplicationEntryPoint
UefiBootServicesTableLib
DebugLib
UefiLib
+ ReportStatusCodeLib
DevicePathLib
PrintLib
UefiBootManagerLib
@@ -28,6 +28,8 @@
[Guids]
## SOMETIMES_PRODUCES ## Variable:L"BootCurrent" (The boot option of current boot)
gEfiGlobalVariableGuid
+ ## SOMETIMES_PRODUCES ## Variable:L"MemoryTypeInformation."
+ gEfiMemoryTypeInformationGuid ## SOMETIMES_PRODUCES
gEfiEventReadyToBootGuid ## SOMETIMES_PRODUCES
gEfiHobListGuid ## CONSUMES
gEfiDxeServicesTableGuid ## CONSUMES
@@ -52,9 +54,15 @@
gEfiUsbIoProtocolGuid ## CONSUMES
gEfiFirmwareVolume2ProtocolGuid ## CONSUMES
gEfiSimpleTextInProtocolGuid ## CONSUMES
+ gEfiSimpleTextInputExProtocolGuid ## CONSUMES
gEfiSimpleTextOutProtocolGuid ## CONSUMES
gEfiLegacyBiosProtocolGuid ## CONSUMES
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange ## SOMETIMES_CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdProgressCodeOsLoaderLoad ## SOMETIMES_CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdProgressCodeOsLoaderStart ## SOMETIMES_CONSUMES
+
[BuildOptions.Common]
*:DEBUG_*_*_PP_FLAGS = -D EFI_DEBUG
*:DEBUG_*_*_CC_FLAGS = -D EFI_DEBUG
diff --git a/Application/Loader/Loader.vcxproj b/Application/Loader/Loader.vcxproj
index 512b624..9254ab7 100644
--- a/Application/Loader/Loader.vcxproj
+++ b/Application/Loader/Loader.vcxproj
@@ -19,13 +19,15 @@
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
+ <VcpkgEnabled>false</VcpkgEnabled>
+ <EnableStdModules>false</EnableStdModules>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<Import Project="$(SolutionDir)\EfiGuard.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ItemDefinitionGroup>
<ClCompile>
- <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">CONFIGURE_DRIVER=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_PCD_GET_MODE_32_PcdProgressCodeOsLoaderLoad=0x3058000;_PCD_GET_MODE_32_PcdProgressCodeOsLoaderStart=0x3058001;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)Include;$(EDK_PATH)\OvmfPkg\Csm\Include</AdditionalIncludeDirectories>
</ClCompile>
<Link>
diff --git a/EfiGuard.props b/EfiGuard.props
index aa2c7ce..4fbad77 100644
--- a/EfiGuard.props
+++ b/EfiGuard.props
@@ -42,7 +42,7 @@
<StringPooling>true</StringPooling>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<ForceConformanceInForLoopScope />
- <AdditionalOptions>/Gs32768 /Gw /utf-8 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalOptions>/Gs32768 /Gw /utf-8 /Zc:threadSafeInit- %(AdditionalOptions)</AdditionalOptions>
<ErrorReporting />
<FloatingPointModel />
<DiagnosticsFormat>Caret</DiagnosticsFormat>
@@ -68,7 +68,7 @@
<UACUIAccess />
<TypeLibraryResourceID />
<AdditionalOptions>/ALIGN:0x200 /FILEALIGN:0x200 /SECTION:.pdata,!D /SECTION:.xdata,!D /OPT:ICF=10 /IGNORE:4254 /IGNORE:4281 /NOVCFEATURE /NOCOFFGRPINFO /PDBALTPATH:%_PDB% %(AdditionalOptions)</AdditionalOptions>
- <MergeSections>.rdata=.text</MergeSections>
+ <MergeSections>.rdata=.data</MergeSections>
<LinkErrorReporting />
<ProfileGuidedDatabase />
<EntryPointSymbol>EfiMain</EntryPointSymbol>
diff --git a/EfiGuardDxe/EfiGuardDxe.c b/EfiGuardDxe/EfiGuardDxe.c
index 170a433..74dbf37 100644
--- a/EfiGuardDxe/EfiGuardDxe.c
+++ b/EfiGuardDxe/EfiGuardDxe.c
@@ -54,6 +54,7 @@ EFI_HANDLE gBootmgfwHandle = NULL;
//
// EFI runtime globals
//
+EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL* gTextInputEx = NULL;
EFI_EVENT gEfiExitBootServicesEvent = NULL;
BOOLEAN gEfiAtRuntime = FALSE;
EFI_EVENT gEfiVirtualNotifyEvent = NULL;
@@ -155,8 +156,7 @@ HookedLoadImage(
// We only have a filename to go on at this point. We will determine the final 'is this bootmgfw.efi?' status after the image has been loaded
CONST BOOLEAN MaybeBootmgfw = ImagePath != NULL
- ? (StrStr(ImagePath, L"bootmgfw.efi") != NULL || StrStr(ImagePath, L"BOOTMGFW.EFI") != NULL ||
- StrStr(ImagePath, L"bootx64.efi") != NULL || StrStr(ImagePath, L"BOOTX64.EFI") != NULL)
+ ? StriStr(ImagePath, L"bootmgfw.efi") != NULL || StriStr(ImagePath, L"Bootmgfw_ms.vc") != NULL || StriStr(ImagePath, L"bootx64.efi") != NULL
: FALSE;
CONST BOOLEAN IsBoot = (MaybeBootmgfw || (BootPolicy == TRUE && SourceBuffer == NULL));
@@ -220,11 +220,6 @@ HookedLoadImage(
LoadedImage->ImageBase,
LoadedImage->ImageSize);
}
- else
- {
- // A non-Windows OS is being booted. Unload ourselves
- EfiGuardUnload(gImageHandle);
- }
}
}
@@ -248,7 +243,12 @@ HookedSetVariable(
)
{
// We should not be hooking the runtime table after ExitBootServices() unless this is the selected DSE bypass method
- ASSERT(!gEfiAtRuntime || gDriverConfig.DseBypassMethod == DSE_DISABLE_SETVARIABLE_HOOK);
+ ASSERT(!gEfiAtRuntime || (gDriverConfig.DseBypassMethod == DSE_DISABLE_SETVARIABLE_HOOK && gBootmgfwHandle != NULL));
+
+ if (StrCmp(VariableName, L"SecureBoot") == 0)
+ {
+ return EFI_WRITE_PROTECTED;
+ }
// Do we have a match for the variable name and vendor GUID?
if (gEfiAtRuntime && gEfiGoneVirtual &&
@@ -274,52 +274,52 @@ HookedSetVariable(
BackdoorData->Size > 0 &&
(UINTN)BackdoorData->KernelAddress >= (UINTN)MM_SYSTEM_RANGE_START)
{
- if (BackdoorData->IsMemCopy && BackdoorData->u.UserBuffer != NULL)
- {
- if (BackdoorData->IsReadOperation) // Copy kernel buffer to user address
- CopyMem(BackdoorData->u.UserBuffer, BackdoorData->KernelAddress, BackdoorData->Size);
- else // Copy user buffer to kernel address
- CopyMem(BackdoorData->KernelAddress, BackdoorData->u.UserBuffer, BackdoorData->Size);
- }
- else
+ // For scalars, copy user value to kernel memory and put the old value in BackdoorData->u.XXX
+ switch (BackdoorData->Size)
{
- // Copy user scalar to kernel memory, and put the old value in BackdoorData->u.XXX
- switch (BackdoorData->Size)
+ case 1:
{
- case 1:
- {
- CONST UINT8 NewByte = (UINT8)BackdoorData->u.s.Byte;
- BackdoorData->u.s.Byte = *(UINT8*)BackdoorData->KernelAddress;
- if (!BackdoorData->IsReadOperation)
- *(UINT8*)BackdoorData->KernelAddress = NewByte;
- break;
- }
- case 2:
- {
- CONST UINT16 NewWord = (UINT16)BackdoorData->u.s.Word;
- BackdoorData->u.s.Word = *(UINT16*)BackdoorData->KernelAddress;
- if (!BackdoorData->IsReadOperation)
- *(UINT16*)BackdoorData->KernelAddress = NewWord;
- break;
- }
- case 4:
- {
- CONST UINT32 NewDword = (UINT32)BackdoorData->u.s.Dword;
- BackdoorData->u.s.Dword = *(UINT32*)BackdoorData->KernelAddress;
- if (!BackdoorData->IsReadOperation)
- *(UINT32*)BackdoorData->KernelAddress = NewDword;
- break;
- }
- case 8:
+ CONST UINT8 NewByte = (UINT8)BackdoorData->u.s.Byte;
+ BackdoorData->u.s.Byte = *(UINT8*)BackdoorData->KernelAddress;
+ if (!BackdoorData->ReadOnly)
+ CopyWpMem(BackdoorData->KernelAddress, &NewByte, sizeof(NewByte));
+ break;
+ }
+ case 2:
+ {
+ CONST UINT16 NewWord = (UINT16)BackdoorData->u.s.Word;
+ BackdoorData->u.s.Word = *(UINT16*)BackdoorData->KernelAddress;
+ if (!BackdoorData->ReadOnly)
+ CopyWpMem(BackdoorData->KernelAddress, &NewWord, sizeof(NewWord));
+ break;
+ }
+ case 4:
+ {
+ CONST UINT32 NewDword = (UINT32)BackdoorData->u.s.Dword;
+ BackdoorData->u.s.Dword = *(UINT32*)BackdoorData->KernelAddress;
+ if (!BackdoorData->ReadOnly)
+ CopyWpMem(BackdoorData->KernelAddress, &NewDword, sizeof(NewDword));
+ break;
+ }
+ case 8:
+ {
+ CONST UINT64 NewQword = BackdoorData->u.Qword;
+ BackdoorData->u.Qword = *(UINT64*)BackdoorData->KernelAddress;
+ if (!BackdoorData->ReadOnly)
+ CopyWpMem(BackdoorData->KernelAddress, &NewQword, sizeof(NewQword));
+ break;
+ }
+ default:
+ {
+ // Arbitrary size memcpy
+ if (BackdoorData->u.UserBuffer != NULL)
{
- CONST UINT64 NewQword = BackdoorData->u.Qword;
- BackdoorData->u.Qword = *(UINT64*)BackdoorData->KernelAddress;
- if (!BackdoorData->IsReadOperation)
- *(UINT64*)BackdoorData->KernelAddress = NewQword;
- break;
+ if (BackdoorData->ReadOnly)
+ CopyWpMem(BackdoorData->u.UserBuffer, BackdoorData->KernelAddress, BackdoorData->Size);
+ else
+ CopyWpMem(BackdoorData->KernelAddress, BackdoorData->u.UserBuffer, BackdoorData->Size);
}
- default:
- break; // Invalid size; do nothing
+ break;
}
}
@@ -402,7 +402,7 @@ ExitBootServicesEvent(
// If the DSE bypass method is *not* DSE_DISABLE_SETVARIABLE_HOOK, perform some cleanup now. In principle this should allow
// linking with /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER, because our driver image may be freed after this callback returns.
// Using DSE_DISABLE_SETVARIABLE_HOOK requires linking with /SUBSYSTEM:EFI_RUNTIME_DRIVER, because the image must not be freed.
- if (gDriverConfig.DseBypassMethod != DSE_DISABLE_SETVARIABLE_HOOK)
+ if (gDriverConfig.DseBypassMethod != DSE_DISABLE_SETVARIABLE_HOOK || gBootmgfwHandle == NULL)
{
// Uninstall our installed driver protocols
gBS->UninstallMultipleProtocolInterfaces(gImageHandle,
@@ -572,6 +572,11 @@ EfiGuardInitialize(
}
//
+ // Query the console input handle for the Simple Text Input Ex protocol
+ //
+ gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&gTextInputEx);
+
+ //
// Install EfiGuard driver protocol
//
Status = gBS->InstallProtocolInterface(&gImageHandle,
diff --git a/EfiGuardDxe/EfiGuardDxe.h b/EfiGuardDxe/EfiGuardDxe.h
index 5d87513..e1e1d53 100644
--- a/EfiGuardDxe/EfiGuardDxe.h
+++ b/EfiGuardDxe/EfiGuardDxe.h
@@ -36,6 +36,11 @@ extern EFIGUARD_CONFIGURATION_DATA gDriverConfig;
extern EFI_HANDLE gBootmgfwHandle;
//
+// Simple Text Input Ex protocol pointer. May be NULL
+//
+extern EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL* gTextInputEx;
+
+//
// TRUE if ExitBootServices() has been called
//
extern BOOLEAN gEfiAtRuntime;
diff --git a/EfiGuardDxe/EfiGuardDxe.inf b/EfiGuardDxe/EfiGuardDxe.inf
index 67df756..438fff8 100644
--- a/EfiGuardDxe/EfiGuardDxe.inf
+++ b/EfiGuardDxe/EfiGuardDxe.inf
@@ -26,6 +26,9 @@
Zydis/src/Utils.c
Zydis/src/Zydis.c
+[Sources.X64]
+ X64/Cet.nasm
+
[Packages]
MdePkg/MdePkg.dec
EfiGuardPkg/EfiGuardPkg.dec
@@ -50,6 +53,8 @@
gEfiDevicePathUtilitiesProtocolGuid ## CONSUMES
gEfiLoadedImageProtocolGuid ## CONSUMES
gEfiShellProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiSimpleTextInProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiSimpleTextInputExProtocolGuid ## SOMETIMES_CONSUMES
[Guids]
gEfiGlobalVariableGuid ## SOMETIMES_PRODUCES
diff --git a/EfiGuardDxe/EfiGuardDxe.vcxproj b/EfiGuardDxe/EfiGuardDxe.vcxproj
index 0b95d46..19db278 100644
--- a/EfiGuardDxe/EfiGuardDxe.vcxproj
+++ b/EfiGuardDxe/EfiGuardDxe.vcxproj
@@ -19,10 +19,16 @@
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
+ <VcpkgEnabled>false</VcpkgEnabled>
+ <EnableStdModules>false</EnableStdModules>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<Import Project="$(SolutionDir)\EfiGuard.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="PropertySheets">
+ <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
+ <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
+ </ImportGroup>
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>ZYAN_NO_LIBC;ZYCORE_STATIC_BUILD;ZYDIS_STATIC_BUILD;ZYDIS_DISABLE_ENCODER;ZYDIS_DISABLE_FORMATTER;ZYDIS_DISABLE_AVX512;ZYDIS_DISABLE_KNC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
@@ -73,6 +79,12 @@
<ClCompile Include="Zydis\src\Zydis.c" />
</ItemGroup>
<ItemGroup>
+ <MASM Include="X64\Cet.asm" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="X64\Cet.nasm" />
+ </ItemGroup>
+ <ItemGroup>
<ClInclude Include="..\Include\Protocol\EfiGuard.h" />
<ClInclude Include="arc.h" />
<ClInclude Include="EfiGuardDxe.h" />
diff --git a/EfiGuardDxe/EfiGuardDxe.vcxproj.filters b/EfiGuardDxe/EfiGuardDxe.vcxproj.filters
index ef7eb16..e2bcab6 100644
--- a/EfiGuardDxe/EfiGuardDxe.vcxproj.filters
+++ b/EfiGuardDxe/EfiGuardDxe.vcxproj.filters
@@ -21,6 +21,9 @@
<Filter Include="Header Files\Zydis\Internal">
<UniqueIdentifier>{09843B9B-51DC-4418-9585-2ED4BD3F1643}</UniqueIdentifier>
</Filter>
+ <Filter Include="Source Files\X64">
+ <UniqueIdentifier>{4cd0c7c8-71ff-4d6d-bb2d-a9e65cc3d7ce}</UniqueIdentifier>
+ </Filter>
<Filter Include="Header Files\Protocol">
<UniqueIdentifier>{aa6da080-fea5-447e-8722-35a98038eb4e}</UniqueIdentifier>
</Filter>
@@ -97,6 +100,16 @@
</ClCompile>
</ItemGroup>
<ItemGroup>
+ <MASM Include="X64\Cet.asm">
+ <Filter>Source Files\X64</Filter>
+ </MASM>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="X64\Cet.nasm">
+ <Filter>Source Files\X64</Filter>
+ </None>
+ </ItemGroup>
+ <ItemGroup>
<ClInclude Include="EfiGuardDxe.h">
<Filter>Header Files</Filter>
</ClInclude>
diff --git a/EfiGuardDxe/PatchNtoskrnl.c b/EfiGuardDxe/PatchNtoskrnl.c
index a852dcb..2e2d20e 100644
--- a/EfiGuardDxe/PatchNtoskrnl.c
+++ b/EfiGuardDxe/PatchNtoskrnl.c
@@ -35,7 +35,7 @@ STATIC CONST UINT8 SigKeInitAmd64SpecificState[] = {
// This function is present since Windows 8.1 and is responsible for executing all functions in the KiVerifyXcptRoutines array.
// One of these functions, KiVerifyXcpt15, will indirectly initialize a PatchGuard context from its exception handler.
STATIC CONST UINT8 SigKiVerifyScopesExecute[] = {
- 0x48, 0x83, 0xCC, 0xCC, 0x00, // and [REG+XX], 0
+ 0x83, 0xCC, 0xCC, 0x00, // and d/qword ptr [REG+XX], 0
0x48, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE // mov rax, 0FEFFFFFFFFFFFFFFh
};
@@ -57,10 +57,11 @@ STATIC CONST UINT8 SigKiMcaDeferredRecoveryService[] = {
// If int 20h is issued from kernel mode, the PatchGuard verification routine KiSwInterruptDispatch is called.
STATIC CONST UINT8 SigKiSwInterrupt[] = {
0xFB, // sti
- 0x48, 0x8D, 0xCC, 0xCC, // lea rcx, XX
+ 0x48, 0x8D, 0xCC, 0xCC, // lea REG, [REG-XX]
0xE8, 0xCC, 0xCC, 0xCC, 0xCC, // call KiSwInterruptDispatch
0xFA // cli
};
+STATIC CONST UINTN SigKiSwInterruptCallOffset = 5, SigKiSwInterruptCliOffset = 10;
#endif
#endif
@@ -69,7 +70,7 @@ STATIC CONST UINT8 SigKiSwInterrupt[] = {
// This signature is only for the Windows 10 RS3+ version. I could add more signatures but this is a pretty superficial patch anyway.
STATIC CONST UINT8 SigSeCodeIntegrityQueryInformation[] = {
0x48, 0x83, 0xEC, // sub rsp, XX
- 0xCC, 0x48, 0x83, 0x3D, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, // cmp cs:qword_14035E638, 0
+ 0xCC, 0x48, 0x83, 0x3D, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, // cmp ds:qword_xxxx, 0
0x4D, 0x8B, 0xC8, // mov r9, r8
0x4C, 0x8B, 0xD1, // mov r10, rcx
0x74, 0xCC // jz XX
@@ -295,7 +296,7 @@ DisablePatchGuard(
#ifndef EAC_COMPAT_MODE
// Search for callers of KiMcaDeferredRecoveryService (only exists on Windows >= 8.1)
UINT8* KiMcaDeferredRecoveryServiceCallers[2];
- ZeroMem(KiMcaDeferredRecoveryServiceCallers, sizeof(KiMcaDeferredRecoveryServiceCallers));
+ ZeroMem((VOID*)KiMcaDeferredRecoveryServiceCallers, sizeof(KiMcaDeferredRecoveryServiceCallers));
if (BuildNumber >= 9600)
{
StartRva = TextSection->VirtualAddress;
@@ -367,11 +368,20 @@ DisablePatchGuard(
}
}
- // Search for KiSwInterrupt (only exists on Windows >= 10)
- UINT8* KiSwInterruptPatternAddress = NULL;
+ // We need KiSwInterruptDispatch to call ExAllocatePool2 for our preferred method to work, because we rely on it to
+ // return null for zero pool tags. Windows 10 20H1 does export ExAllocatePool2, but without using it where we need it.
+ CONST BOOLEAN FindGlobalPgContext = BuildNumber >= 20348 && GetProcedureAddress((UINTN)ImageBase, NtHeaders, "ExAllocatePool2") != NULL;
+
+ // Search for KiSwInterrupt[Dispatch] and optionally its global PatchGuard context (named g_PgContext here). Both of these only exist on Windows >= 10
+ UINT8* KiSwInterruptPatternAddress = NULL, *gPgContext = NULL;
if (BuildNumber >= 10240)
{
+ StartRva = TextSection->VirtualAddress;
+ SizeOfRawData = TextSection->SizeOfRawData;
+ StartVa = ImageBase + StartRva;
+
PRINT_KERNEL_PATCH_MSG(L"== Searching for nt!KiSwInterrupt pattern in .text ==\r\n");
+ UINT8* KiSwInterruptDispatchAddress = NULL;
CONST EFI_STATUS FindKiSwInterruptStatus = FindPattern(SigKiSwInterrupt,
0xCC,
sizeof(SigKiSwInterrupt),
@@ -380,14 +390,55 @@ DisablePatchGuard(
(VOID**)&KiSwInterruptPatternAddress);
if (EFI_ERROR(FindKiSwInterruptStatus))
{
- // This is not a fatal error as the system can still boot without patching KiSwInterrupt.
+ // This is not a fatal error as the system can still boot without patching g_PgContext or KiSwInterrupt.
// However note that in this case, any attempt to issue int 20h from kernel mode later will result in a bugcheck.
PRINT_KERNEL_PATCH_MSG(L" Failed to find KiSwInterrupt. Skipping patch.\r\n");
}
else
{
+ ASSERT(SigKiSwInterrupt[SigKiSwInterruptCallOffset] == 0xE8 && SigKiSwInterrupt[SigKiSwInterruptCliOffset] == 0xFA);
+ CONST INT32 Relative = *(INT32*)(KiSwInterruptPatternAddress + SigKiSwInterruptCallOffset + 1);
+ KiSwInterruptDispatchAddress = KiSwInterruptPatternAddress + SigKiSwInterruptCliOffset + Relative;
+
PRINT_KERNEL_PATCH_MSG(L" Found KiSwInterrupt pattern at 0x%llX.\r\n", (UINTN)KiSwInterruptPatternAddress);
}
+
+ if (KiSwInterruptDispatchAddress != NULL && FindGlobalPgContext)
+ {
+ // Start decode loop
+ Context.Length = 128;
+ Context.Offset = 0;
+ while ((Context.InstructionAddress = (ZyanU64)(KiSwInterruptDispatchAddress + Context.Offset),
+ Status = ZydisDecoderDecodeFull(&Context.Decoder,
+ (VOID*)Context.InstructionAddress,
+ Context.Length - Context.Offset,
+ &Context.Instruction,
+ Context.Operands)) != ZYDIS_STATUS_NO_MORE_DATA)
+ {
+ if (!ZYAN_SUCCESS(Status))
+ {
+ Context.Offset++;
+ continue;
+ }
+
+ // Check if this is 'mov REG, ds:g_PgContext'
+ if (Context.Instruction.operand_count == 2 &&
+ Context.Instruction.mnemonic == ZYDIS_MNEMONIC_MOV &&
+ (Context.Instruction.attributes & ZYDIS_ATTRIB_ACCEPTS_SEGMENT) != 0 &&
+ Context.Operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER &&
+ Context.Operands[1].type == ZYDIS_OPERAND_TYPE_MEMORY && Context.Operands[1].mem.base == ZYDIS_REGISTER_RIP &&
+ (Context.Operands[1].mem.segment == ZYDIS_REGISTER_CS || Context.Operands[1].mem.segment == ZYDIS_REGISTER_DS))
+ {
+ if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&Context.Instruction, &Context.Operands[1], Context.InstructionAddress, (ZyanU64*)&gPgContext)))
+ {
+ PRINT_KERNEL_PATCH_MSG(L" Found g_PgContext at 0x%llX.\r\n", (UINTN)gPgContext);
+ break;
+ }
+ }
+
+ Context.Offset += Context.Instruction.length;
+ }
+ }
}
#endif
@@ -406,8 +457,15 @@ DisablePatchGuard(
CopyWpMem(KiMcaDeferredRecoveryServiceCallers[0], &No, sizeof(No));
CopyWpMem(KiMcaDeferredRecoveryServiceCallers[1], &No, sizeof(No));
}
- if (KiSwInterruptPatternAddress != NULL)
+ if (gPgContext != NULL)
+ {
+ CONST UINT64 NewPgContextAddress = (UINT64)ImageBase + InitSection->VirtualAddress; // Address in discardable section
+ CopyWpMem(gPgContext, &NewPgContextAddress, sizeof(NewPgContextAddress));
+ }
+ else if (KiSwInterruptPatternAddress != NULL)
+ {
SetWpMem(KiSwInterruptPatternAddress, sizeof(SigKiSwInterrupt), 0x90); // 11 x nop
+ }
#endif
// Print info
@@ -432,7 +490,12 @@ DisablePatchGuard(
(UINT32)(KiMcaDeferredRecoveryServiceCallers[0] - ImageBase),
(UINT32)(KiMcaDeferredRecoveryServiceCallers[1] - ImageBase));
}
- if (KiSwInterruptPatternAddress != NULL)
+ if (gPgContext != NULL)
+ {
+ PRINT_KERNEL_PATCH_MSG(L" Patched g_PgContext [RVA: 0x%X].\r\n",
+ (UINT32)(gPgContext - ImageBase));
+ }
+ else if (KiSwInterruptPatternAddress != NULL)
{
PRINT_KERNEL_PATCH_MSG(L" Patched KiSwInterrupt [RVA: 0x%X].\r\n",
(UINT32)(KiSwInterruptPatternAddress - ImageBase));
@@ -821,9 +884,7 @@ PatchNtoskrnl(
Section++;
}
- ASSERT(InitSection != NULL);
- ASSERT(TextSection != NULL);
- ASSERT(PageSection != NULL);
+ ASSERT(InitSection != NULL && TextSection != NULL && PageSection != NULL);
#ifndef DO_NOT_DISABLE_PATCHGUARD
// Patch INIT and .text sections to disable PatchGuard
diff --git a/EfiGuardDxe/PatchWinload.c b/EfiGuardDxe/PatchWinload.c
index 197ca75..0fbda68 100644
--- a/EfiGuardDxe/PatchWinload.c
+++ b/EfiGuardDxe/PatchWinload.c
@@ -8,12 +8,11 @@ UINT8 gOslFwpKernelSetupPhase1Backup[sizeof(gHookTemplate)] = { 0 };
// Signature for winload!OslFwpKernelSetupPhase1+XX, where the value of XX needs to be determined by backtracking.
-// Windows 10 only. On older OSes, and on Windows 10 as fallback, OslFwpKernelSetupPhase1 is found via xrefs to EfipGetRsdt
+// Windows 10 RS4 and later only. On older OSes, and on Windows 10 as fallback, OslFwpKernelSetupPhase1 is found via xrefs to EfipGetRsdt
STATIC CONST UINT8 SigOslFwpKernelSetupPhase1[] = {
- 0xE8, 0xCC, 0xCC, 0xCC, 0xCC, // call BlpArchSwitchContext
- 0x48, 0x8B, 0x05, 0xCC, 0xCC, 0xCC, 0xCC, // mov rax, gBS
- 0xCC, 0x8B, 0xCC, // mov rdx, XX
- 0x48, 0x8B, 0x0D, 0xCC, 0xCC, 0xCC, 0xCC // mov rcx, EfiImageHandle
+ 0x89, 0xCC, 0x24, 0x01, 0x00, 0x00, // mov [REG+124h], r32
+ 0xE8, 0xCC, 0xCC, 0xCC, 0xCC, // call BlBdStop
+ 0xCC, 0x8B, 0xCC // mov r32, r/m32
};
STATIC UNICODE_STRING ImgpFilterValidationFailureMessage = RTL_CONSTANT_STRING(L"*** Windows is unable to verify the signature of"); // newline, etc etc...
@@ -405,7 +404,7 @@ FindOslFwpKernelSetupPhase1(
IN PEFI_IMAGE_NT_HEADERS NtHeaders,
IN PEFI_IMAGE_SECTION_HEADER CodeSection,
IN PEFI_IMAGE_SECTION_HEADER PatternSection,
- IN BOOLEAN TryPatternMatch,
+ IN UINT16 BuildNumber,
OUT UINT8** OslFwpKernelSetupPhase1Address
)
{
@@ -415,9 +414,9 @@ FindOslFwpKernelSetupPhase1(
CONST UINT32 CodeSizeOfRawData = CodeSection->SizeOfRawData;
CONST UINT8* PatternStartVa = ImageBase + PatternSection->VirtualAddress;
- if (TryPatternMatch)
+ if (BuildNumber >= 17134)
{
- // On Windows 10, try simple pattern matching first since it will most likely work
+ // On Windows 10 RS4 and later, try simple pattern matching first since it will most likely work
UINT8* Found = NULL;
CONST EFI_STATUS Status = FindPattern(SigOslFwpKernelSetupPhase1,
0xCC,
@@ -437,14 +436,69 @@ FindOslFwpKernelSetupPhase1(
}
}
+ // Initialize Zydis
+ Print(L"\r\n== Disassembling .text to find OslFwpKernelSetupPhase1 ==\r\n");
+ ZYDIS_CONTEXT Context;
+ ZyanStatus Status = ZydisInit(NtHeaders, &Context);
+ if (!ZYAN_SUCCESS(Status))
+ {
+ Print(L"Failed to initialize disassembler engine.\r\n");
+ return EFI_LOAD_ERROR;
+ }
+
+ CONST VOID* BlBdStop = GetProcedureAddress((UINTN)ImageBase, NtHeaders, "BlBdStop");
+ if (BuildNumber >= 17134 && BlBdStop != NULL)
+ {
+ Context.Length = CodeSizeOfRawData;
+ Context.Offset = 6;
+
+ // Start decode loop
+ while ((Context.InstructionAddress = (ZyanU64)(CodeStartVa + Context.Offset),
+ Status = ZydisDecoderDecodeFull(&Context.Decoder,
+ (VOID*)Context.InstructionAddress,
+ Context.Length - Context.Offset,
+ &Context.Instruction,
+ Context.Operands)) != ZYDIS_STATUS_NO_MORE_DATA)
+ {
+ if (!ZYAN_SUCCESS(Status))
+ {
+ Context.Offset++;
+ continue;
+ }
+
+ // Check if this is 'call BlBdStop'
+ if (Context.Instruction.operand_count == 4 &&
+ Context.Operands[0].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && Context.Operands[0].imm.is_relative == ZYAN_TRUE &&
+ Context.Instruction.mnemonic == ZYDIS_MNEMONIC_CALL)
+ {
+ ZyanU64 OperandAddress = 0;
+ if (ZYAN_SUCCESS(ZydisCalcAbsoluteAddress(&Context.Instruction, &Context.Operands[0], Context.InstructionAddress, &OperandAddress)) &&
+ OperandAddress == (UINTN)BlBdStop)
+ {
+ // Check if the preceding instruction is 'mov [REG+124h], r32'
+ CONST UINT8* CallBlBdStopAddress = (UINT8*)Context.InstructionAddress;
+ if ((CallBlBdStopAddress[-6] == 0x89 || CallBlBdStopAddress[-6] == 0x8B) &&
+ *(UINT32*)(&CallBlBdStopAddress[-4]) == 0x124 &&
+ (*OslFwpKernelSetupPhase1Address = BacktrackToFunctionStart(ImageBase, NtHeaders, CallBlBdStopAddress)) != NULL)
+ {
+ Print(L" Found OslFwpKernelSetupPhase1 at 0x%llX.\r\n\r\n", (UINTN)(*OslFwpKernelSetupPhase1Address));
+ return EFI_SUCCESS;
+ }
+ }
+ }
+
+ Context.Offset += Context.Instruction.length;
+ }
+ }
+
+ // On RS4 and later, the previous method really should have worked
+ ASSERT(BuildNumber < 17134);
+
// On older versions, use some convoluted but robust logic to find OslFwpKernelSetupPhase1 by matching xrefs to EfipGetRsdt.
// This of course implies finding EfipGetRsdt first. After that, find all calls to this function, and for each, calculate
// the distance from the start of the function to the call. OslFwpKernelSetupPhase1 is reliably (Vista through 10)
// the function that has the smallest value for this distance, i.e. the call happens very early in the function.
- CHAR8 SectionName[EFI_IMAGE_SIZEOF_SHORT_NAME + 1];
- CopyMem(SectionName, PatternSection->Name, EFI_IMAGE_SIZEOF_SHORT_NAME);
- SectionName[EFI_IMAGE_SIZEOF_SHORT_NAME] = '\0';
- Print(L"\r\n== Searching for EfipGetRsdt pattern in %a ==\r\n", SectionName);
+ Print(L"\r\n== Searching for EfipGetRsdt pattern in .text ==\r\n");
// Search for EFI ACPI 2.0 table GUID: { 8868e871-e4f1-11d3-bc22-0080c73c8881 }
UINT8* PatternAddress = NULL;
@@ -468,16 +522,6 @@ FindOslFwpKernelSetupPhase1(
Print(L"\r\n== Disassembling .text to find EfipGetRsdt ==\r\n");
UINT8* LeaEfiAcpiTableGuidAddress = NULL;
-
- // Initialize Zydis
- ZYDIS_CONTEXT Context;
- ZyanStatus Status = ZydisInit(NtHeaders, &Context);
- if (!ZYAN_SUCCESS(Status))
- {
- Print(L"Failed to initialize disassembler engine.\r\n");
- return EFI_LOAD_ERROR;
- }
-
Context.Length = CodeSizeOfRawData;
Context.Offset = 0;
@@ -534,7 +578,6 @@ FindOslFwpKernelSetupPhase1(
}
Print(L" Found EfipGetRsdt at 0x%llX.\r\n", (UINTN)EfipGetRsdt);
- Print(L"\r\n== Disassembling .text to find OslFwpKernelSetupPhase1 ==\r\n");
UINT8* CallEfipGetRsdtAddress = NULL;
// Start decode loop
@@ -673,7 +716,7 @@ PatchWinload(
NtHeaders,
CodeSection,
PatternSection,
- BuildNumber >= 10240,
+ BuildNumber,
(UINT8**)&gOriginalOslFwpKernelSetupPhase1);
if (EFI_ERROR(Status))
{
diff --git a/EfiGuardDxe/VisualUefi.c b/EfiGuardDxe/VisualUefi.c
index e1f76db..9795faf 100644
--- a/EfiGuardDxe/VisualUefi.c
+++ b/EfiGuardDxe/VisualUefi.c
@@ -5,6 +5,7 @@
#include <Uefi.h>
#include <Protocol/DriverSupportedEfiVersion.h>
+#include <Protocol/SimpleTextInEx.h>
#include <Protocol/EfiGuard.h>
#include <Guid/Acpi.h>
#include <Library/DebugLib.h>
@@ -31,6 +32,7 @@ EFI_GUID gEfiGuardDriverProtocolGuid = EFI_EFIGUARD_DRIVER_PROTOCOL_GUID;
// GUIDs
//
EFI_GUID gEfiDriverSupportedEfiVersionProtocolGuid = EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL_GUID;
+EFI_GUID gEfiSimpleTextInputExProtocolGuid = EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID;
EFI_GUID gEfiAcpi20TableGuid = EFI_ACPI_20_TABLE_GUID;
diff --git a/EfiGuardDxe/X64/Cet.asm b/EfiGuardDxe/X64/Cet.asm
new file mode 100644
index 0000000..74433c2
--- /dev/null
+++ b/EfiGuardDxe/X64/Cet.asm
@@ -0,0 +1,37 @@
+MSR_S_CET EQU 6A2h
+MSR_S_CET_SH_STK_EN EQU 1
+CR4_CET EQU (1 SHL 23)
+N_CR4_CET EQU 23
+
+.code
+
+align 16
+AsmDisableCet PROC
+ mov ecx, MSR_S_CET
+ rdmsr
+ test al, MSR_S_CET_SH_STK_EN
+ jz @F ; if z, shadow stack not enabled
+
+ ; Pop pushed data for 'call'
+ mov rax, 1
+ incsspq rax
+
+@@:
+ mov rax, cr4
+ btr eax, N_CR4_CET ; clear CR4_CET
+ mov cr4, rax
+ ret
+AsmDisableCet ENDP
+
+align 16
+AsmEnableCet PROC
+ mov rax, cr4
+ bts eax, N_CR4_CET ; set CR4_CET
+ mov cr4, rax
+
+ ; Use jmp to skip check for 'ret'
+ pop rax
+ jmp rax
+AsmEnableCet ENDP
+
+end
diff --git a/EfiGuardDxe/X64/Cet.nasm b/EfiGuardDxe/X64/Cet.nasm
new file mode 100644
index 0000000..b93ca16
--- /dev/null
+++ b/EfiGuardDxe/X64/Cet.nasm
@@ -0,0 +1,36 @@
+%define MSR_S_CET 0x6A2
+%define MSR_S_CET_SH_STK_EN 0x1
+%define CR4_CET (1 << 23)
+%define N_CR4_CET 23
+
+DEFAULT REL
+SECTION .text
+
+align 16
+global ASM_PFX(AsmDisableCet)
+ASM_PFX(AsmDisableCet):
+ mov ecx, MSR_S_CET
+ rdmsr
+ test al, MSR_S_CET_SH_STK_EN
+ jz .SsDone ; if z, shadow stack not enabled
+
+ ; Pop pushed data for 'call'
+ mov rax, 1
+ incsspq rax
+
+.SsDone:
+ mov rax, cr4
+ btr eax, N_CR4_CET ; clear CR4_CET
+ mov cr4, rax
+ ret
+
+align 16
+global ASM_PFX(AsmEnableCet)
+ASM_PFX(AsmEnableCet):
+ mov rax, cr4
+ bts eax, N_CR4_CET ; set CR4_CET
+ mov cr4, rax
+
+ ; Use jmp to skip check for 'ret'
+ pop rax
+ jmp rax
diff --git a/EfiGuardDxe/util.c b/EfiGuardDxe/util.c
index 17686ef..78424e5 100644
--- a/EfiGuardDxe/util.c
+++ b/EfiGuardDxe/util.c
@@ -119,6 +119,40 @@ PrintKernelPatchInfo(
}
}
+VOID
+EFIAPI
+DisableWriteProtect(
+ OUT BOOLEAN *WpEnabled,
+ OUT BOOLEAN *CetEnabled
+ )
+{
+ CONST UINTN Cr0 = AsmReadCr0();
+ *WpEnabled = (Cr0 & CR0_WP) != 0;
+ *CetEnabled = (AsmReadCr4() & CR4_CET) != 0;
+
+ if (*WpEnabled)
+ {
+ if (*CetEnabled)
+ AsmDisableCet();
+ AsmWriteCr0(Cr0 & ~CR0_WP);
+ }
+}
+
+VOID
+EFIAPI
+EnableWriteProtect(
+ IN BOOLEAN WpEnabled,
+ IN BOOLEAN CetEnabled
+ )
+{
+ if (WpEnabled)
+ {
+ AsmWriteCr0(AsmReadCr0() | CR0_WP);
+ if (CetEnabled)
+ AsmEnableCet();
+ }
+}
+
VOID*
EFIAPI
CopyWpMem(
@@ -127,16 +161,12 @@ CopyWpMem(
IN UINTN Length
)
{
- CONST UINTN Cr0 = AsmReadCr0();
- CONST BOOLEAN WpSet = (Cr0 & CR0_WP) != 0;
- if (WpSet)
- AsmWriteCr0(Cr0 & ~CR0_WP);
+ BOOLEAN WpEnabled, CetEnabled;
+ DisableWriteProtect(&WpEnabled, &CetEnabled);
VOID* Result = CopyMem(Destination, Source, Length);
- if (WpSet)
- AsmWriteCr0(Cr0);
-
+ EnableWriteProtect(WpEnabled, CetEnabled);
return Result;
}
@@ -148,16 +178,12 @@ SetWpMem(
IN UINT8 Value
)
{
- CONST UINTN Cr0 = AsmReadCr0();
- CONST BOOLEAN WpSet = (Cr0 & CR0_WP) != 0;
- if (WpSet)
- AsmWriteCr0(Cr0 & ~CR0_WP);
+ BOOLEAN WpEnabled, CetEnabled;
+ DisableWriteProtect(&WpEnabled, &CetEnabled);
VOID* Result = SetMem(Destination, Length, Value);
- if (WpSet)
- AsmWriteCr0(Cr0);
-
+ EnableWriteProtect(WpEnabled, CetEnabled);
return Result;
}
@@ -199,6 +225,43 @@ StrniCmp(
return UpperFirstChar - UpperSecondChar;
}
+CONST CHAR16*
+EFIAPI
+StriStr(
+ IN CONST CHAR16 *String1,
+ IN CONST CHAR16 *String2
+ )
+{
+ if (*String2 == L'\0')
+ return String1;
+
+ while (*String1 != L'\0')
+ {
+ CONST CHAR16* FirstMatch = String1;
+ CONST CHAR16* String2Ptr = String2;
+ CHAR16 String1Char = CharToUpper(*String1);
+ CHAR16 String2Char = CharToUpper(*String2Ptr);
+
+ while (String1Char == String2Char && String1Char != L'\0')
+ {
+ String1++;
+ String2Ptr++;
+
+ String1Char = CharToUpper(*String1);
+ String2Char = CharToUpper(*String2Ptr);
+ }
+
+ if (String2Char == L'\0')
+ return FirstMatch;
+
+ if (String1Char == L'\0')
+ return NULL;
+
+ String1 = FirstMatch + 1;
+ }
+ return NULL;
+}
+
BOOLEAN
EFIAPI
WaitForKey(
@@ -206,27 +269,28 @@ WaitForKey(
)
{
// Hack: because we call this at TPL_NOTIFY in ExitBootServices, we cannot use WaitForEvent()
- // in that scenario because it requires TPL == TPL_APPLICATION. So check the TPL
+ // in that scenario because it requires TPL <= TPL_APPLICATION. So check the TPL
CONST EFI_TPL Tpl = EfiGetCurrentTpl();
- EFI_INPUT_KEY Key = { 0, 0 };
+ EFI_KEY_DATA KeyData = { 0 };
EFI_STATUS Status = EFI_NOT_READY;
while (Status == EFI_NOT_READY)
{
- // Can we call WaitForEvent()?
UINTN Index = 0;
- if (Tpl == TPL_APPLICATION)
- gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &Index); // Yep
+ if (Tpl <= TPL_APPLICATION)
+ gBS->WaitForEvent(1, (VOID**)(gTextInputEx != NULL ? gTextInputEx->WaitForKeyEx : gST->ConIn->WaitForKey), &Index);
else
- RtlStall(1); // Nope; burn CPU. // TODO: find a way to parallelize this to achieve GeForce FX 5800 temperatures
+ RtlStall(1); // WaitForEvent() unavailable, burn CPU
// At TPL_APPLICATION, we will always get EFI_SUCCESS (barring hardware failures). At higher TPLs we may also get EFI_NOT_READY
- Status = gST->ConIn->ReadKeyStroke(gST->ConIn, &Key);
+ Status = gTextInputEx != NULL
+ ? gTextInputEx->ReadKeyStrokeEx(gTextInputEx, &KeyData)
+ : gST->ConIn->ReadKeyStroke(gST->ConIn, &KeyData.Key);
}
ASSERT_EFI_ERROR(Status);
- return (BOOLEAN)(Key.ScanCode != SCAN_ESC);
+ return KeyData.Key.ScanCode != SCAN_ESC;
}
INT32
@@ -475,8 +539,8 @@ BacktrackToFunctionStart(
if (High >= Low)
{
- // If the function entry specifies indirection, get the address of the master function entry
- if ((FunctionEntry->u.UnwindData & RUNTIME_FUNCTION_INDIRECT) != 0)
+ // If the function entry specifies indirection, get the address of its master function entry
+ while ((FunctionEntry->u.UnwindData & RUNTIME_FUNCTION_INDIRECT) != 0)
{
FunctionEntry = (PIMAGE_RUNTIME_FUNCTION_ENTRY)(FunctionEntry->u.UnwindData + ImageBase - 1);
}
diff --git a/EfiGuardDxe/util.h b/EfiGuardDxe/util.h
index 00294df..bbdf4d1 100644
--- a/EfiGuardDxe/util.h
+++ b/EfiGuardDxe/util.h
@@ -8,6 +8,7 @@
#define CR0_WP ((UINTN)0x00010000) // CR0.WP
#define CR0_PG ((UINTN)0x80000000) // CR0.PG
+#define CR4_CET ((UINTN)0x00800000) // CR4.CET
#define CR4_LA57 ((UINTN)0x00001000) // CR4.LA57
#define MSR_EFER ((UINTN)0xC0000080) // Extended Function Enable Register
#define EFER_LMA ((UINTN)0x00000400) // Long Mode Active
@@ -66,6 +67,45 @@ PrintKernelPatchInfo(
);
//
+// Disables CET.
+//
+VOID
+EFIAPI
+AsmDisableCet(
+ VOID
+ );
+
+//
+// Enables CET.
+//
+VOID
+EFIAPI
+AsmEnableCet(
+ VOID
+ );
+
+//
+// Disables write protection if it is currently enabled.
+// Returns the current CET and WP states for use when calling EnableWriteProtect().
+//
+VOID
+EFIAPI
+DisableWriteProtect(
+ OUT BOOLEAN *WpEnabled,
+ OUT BOOLEAN *CetEnabled
+ );
+
+//
+// Enables write protection if it was previously enabled.
+//
+VOID
+EFIAPI
+EnableWriteProtect(
+ IN BOOLEAN WpEnabled,
+ IN BOOLEAN CetEnabled
+ );
+
+//
// Wrapper for CopyMem() that disables write protection prior to copying if needed.
//
VOID*
@@ -108,6 +148,16 @@ StrniCmp(
);
//
+// Case-insensitive string search.
+//
+CONST CHAR16*
+EFIAPI
+StriStr(
+ IN CONST CHAR16 *String1,
+ IN CONST CHAR16 *String2
+ );
+
+//
// Waits for a key to be pressed before continuing execution.
// Returns FALSE if ESC was pressed to abort, TRUE otherwise.
//
diff --git a/EfiGuardPkg.dec b/EfiGuardPkg.dec
index 4d8c783..1cb4309 100644
--- a/EfiGuardPkg.dec
+++ b/EfiGuardPkg.dec
@@ -15,4 +15,11 @@
[Protocols]
## Include/Protocol/EfiGuard.h
- gEfiGuardDriverProtocolGuid = { 0x51e4785b, 0xb1e4, 0x4fda, { 0xaf, 0x5f, 0x94, 0x2e, 0xc0, 0x15, 0xf1, 0x7 }}
+ gEfiGuardDriverProtocolGuid = { 0xa2b65550, 0x8675, 0x48ac, {0xbd, 0xe6, 0x02, 0xa5, 0x3b, 0xc2, 0x02, 0x3c }}
+
+ ## Originally in OvmfPkg/Csm/Include/Protocol/LegacyBios.h
+ gEfiLegacyBiosProtocolGuid = { 0xdb9a1e3d, 0x45cb, 0x4abb, {0x85, 0x3b, 0xe5, 0x38, 0x7f, 0xdb, 0x2e, 0x2d }}
+
+[Guids]
+ ## Originally in OvmfPkg/Csm/Include/Guid/LegacyBios.h
+ gEfiLegacyBiosGuid = { 0x2e3044ac, 0x879f, 0x490f, {0x97, 0x60, 0xbb, 0xdf, 0xaf, 0x69, 0x5f, 0x50 }}
diff --git a/EfiGuardPkg.dsc b/EfiGuardPkg.dsc
index d2bf50f..cd28911 100644
--- a/EfiGuardPkg.dsc
+++ b/EfiGuardPkg.dsc
@@ -65,6 +65,17 @@
VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf
+[PcdsFixedAtBuild]
+!if $(TARGET) == DEBUG
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x07
+!endif
+
+ # Enable error and progress status code reporting
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x03
+
+ # See https://edk2-devel.narkive.com/sSVnhXxV/edk2-bdssetmemorytypeinformationvariable
+ gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
+
[Components]
# DXE driver
EfiGuardPkg/EfiGuardDxe/EfiGuardDxe.inf
@@ -74,6 +85,7 @@
[BuildOptions.Common]
*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES
+
!if $(CONFIGURE_DRIVER) == 1
*_*_*_CC_FLAGS = -D CONFIGURE_DRIVER=1
!endif
@@ -92,12 +104,17 @@
INTEL:*_*_*_CC_FLAGS = /utf-8
GCC:*_*_*_CC_FLAGS = -finput-charset=UTF-8
+ # https://github.com/Mattiwatti/EfiGuard/issues/134
+ # https://github.com/tianocore/edk2/issues/10547
+ MSFT:*_*_*_CC_FLAGS = /GS-
+ GCC:*_*_*_CC_FLAGS = -fno-stack-protector
+
# Pre-emptive strike for when this horrible option inevitably becomes the default
MSFT:*_*_*_CC_FLAGS = /Qspectre-
# Use sane linker flags instead of EDK2 defaults
- MSFT:*_*_*_DLINK_FLAGS = /ALIGN:0x1000 /FILEALIGN:0x200 /SECTION:.pdata,!D /SECTION:.xdata,!D /MERGE:.rdata=.text /DEBUG:FULL /NOVCFEATURE /NOCOFFGRPINFO /PDBALTPATH:%_PDB%
- INTEL:*_*_*_DLINK_FLAGS = /ALIGN:0x1000 /FILEALIGN:0x200 /SECTION:.pdata,!D /SECTION:.xdata,!D /MERGE:.rdata=.text /DEBUG:FULL /NOVCFEATURE /NOCOFFGRPINFO /PDBALTPATH:%_PDB%
+ MSFT:*_*_*_DLINK_FLAGS = /ALIGN:0x1000 /FILEALIGN:0x200 /SECTION:.pdata,!D /SECTION:.xdata,!D /DEBUG:FULL /NOVCFEATURE /NOCOFFGRPINFO /PDBALTPATH:%_PDB%
+ INTEL:*_*_*_DLINK_FLAGS = /ALIGN:0x1000 /FILEALIGN:0x200 /SECTION:.pdata,!D /SECTION:.xdata,!D /DEBUG:FULL /NOVCFEATURE /NOCOFFGRPINFO /PDBALTPATH:%_PDB%
!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANGPDB"
GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000
!else if $(TOOL_CHAIN_TAG) == "CLANGPDB"
diff --git a/Include/Guid/LegacyBios.h b/Include/Guid/LegacyBios.h
new file mode 100644
index 0000000..9f5a971
--- /dev/null
+++ b/Include/Guid/LegacyBios.h
@@ -0,0 +1,24 @@
+#ifndef _LEGACY_BIOS_H_
+#define _LEGACY_BIOS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+///
+/// The Global ID for the Legacy BIOS GUID that must be installed onto the ImageHandle
+/// of any module follows the EFI Driver Model and uses the Int86() or FarCall()
+/// services of the Legacy BIOS Protocol to produce a standard UEFI I/O Protocol.
+///
+#define EFI_LEGACY_BIOS_GUID \
+ { \
+ 0x2e3044ac, 0x879f, 0x490f, {0x97, 0x60, 0xbb, 0xdf, 0xaf, 0x69, 0x5f, 0x50 } \
+ }
+
+extern EFI_GUID gEfiLegacyBiosGuid;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/Include/Protocol/EfiGuard.h b/Include/Protocol/EfiGuard.h
index d3f386e..df77d11 100644
--- a/Include/Protocol/EfiGuard.h
+++ b/Include/Protocol/EfiGuard.h
@@ -12,7 +12,7 @@ extern "C" {
//
#define EFI_EFIGUARD_DRIVER_PROTOCOL_GUID \
{ \
- 0x51e4785b, 0xb1e4, 0x4fda, { 0xaf, 0x5f, 0x94, 0x2e, 0xc0, 0x15, 0xf1, 0x7 } \
+ 0xa2b65550, 0x8675, 0x48ac, { 0xbd, 0xe6, 0x02, 0xa5, 0x3b, 0xc2, 0x02, 0x3c } \
}
//
@@ -58,16 +58,21 @@ typedef enum _EFIGUARD_DSE_BYPASS_TYPE {
// (1) one of the Byte through Qword fields (depending on size) will contain the value at KernelAddress, or
// (2) the memcpy performed will be in the opposite direction, i.e. from KernelAddress to UserBuffer.
//
-#define EFIGUARD_BACKDOOR_VARIABLE_NAME L"roodkcaBdrauGifE" // "EfiGuardBackdoor" // TODO: randomize?
+#define EFIGUARD_BACKDOOR_VARIABLE_NAME L"GLM" // "MLG" // TODO: randomize?
#define EFIGUARD_BACKDOOR_VARIABLE_GUID &gEfiGlobalVariableGuid
#define EFIGUARD_BACKDOOR_VARIABLE_ATTRIBUTES (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS)
#define EFIGUARD_BACKDOOR_VARIABLE_DATASIZE sizeof(EFIGUARD_BACKDOOR_DATA)
-#define EFIGUARD_BACKDOOR_COOKIE_VALUE (0xDEADC0DE)
+#define EFIGUARD_BACKDOOR_COOKIE_VALUE (0xBEEFBEEF)
typedef struct _EFIGUARD_BACKDOOR_DATA {
+ UINT8 garbage_00[8];
+
UINTN CookieValue; // Currently must be EFIGUARD_BACKDOOR_COOKIE_VALUE
+
+ UINT8 garbage_01[128];
+
VOID* KernelAddress;
union {
@@ -82,9 +87,8 @@ typedef struct _EFIGUARD_BACKDOOR_DATA {
VOID* UserBuffer;
} u;
- BOOLEAN IsMemCopy;
- BOOLEAN IsReadOperation;
UINT32 Size;
+ BOOLEAN ReadOnly;
} EFIGUARD_BACKDOOR_DATA;
diff --git a/Include/Protocol/LegacyBios.h b/Include/Protocol/LegacyBios.h
new file mode 100644
index 0000000..7285f4f
--- /dev/null
+++ b/Include/Protocol/LegacyBios.h
@@ -0,0 +1,1531 @@
+#ifndef _EFI_LEGACY_BIOS_H_
+#define _EFI_LEGACY_BIOS_H_
+
+///
+///
+///
+#pragma pack(1)
+
+typedef UINT8 SERIAL_MODE;
+typedef UINT8 PARALLEL_MODE;
+
+#define EFI_COMPATIBILITY16_TABLE_SIGNATURE SIGNATURE_32 ('I', 'F', 'E', '$')
+
+///
+/// There is a table located within the traditional BIOS in either the 0xF000:xxxx or 0xE000:xxxx
+/// physical address range. It is located on a 16-byte boundary and provides the physical address of the
+/// entry point for the Compatibility16 functions. These functions provide the platform-specific
+/// information that is required by the generic EfiCompatibility code. The functions are invoked via
+/// thunking by using EFI_LEGACY_BIOS_PROTOCOL.FarCall86() with the 32-bit physical
+/// entry point.
+///
+typedef struct {
+ ///
+ /// The string "$EFI" denotes the start of the EfiCompatibility table. Byte 0 is "I," byte
+ /// 1 is "F," byte 2 is "E," and byte 3 is "$" and is normally accessed as a DWORD or UINT32.
+ ///
+ UINT32 Signature;
+
+ ///
+ /// The value required such that byte checksum of TableLength equals zero.
+ ///
+ UINT8 TableChecksum;
+
+ ///
+ /// The length of this table.
+ ///
+ UINT8 TableLength;
+
+ ///
+ /// The major EFI revision for which this table was generated.
+ ///
+ UINT8 EfiMajorRevision;
+
+ ///
+ /// The minor EFI revision for which this table was generated.
+ ///
+ UINT8 EfiMinorRevision;
+
+ ///
+ /// The major revision of this table.
+ ///
+ UINT8 TableMajorRevision;
+
+ ///
+ /// The minor revision of this table.
+ ///
+ UINT8 TableMinorRevision;
+
+ ///
+ /// Reserved for future usage.
+ ///
+ UINT16 Reserved;
+
+ ///
+ /// The segment of the entry point within the traditional BIOS for Compatibility16 functions.
+ ///
+ UINT16 Compatibility16CallSegment;
+
+ ///
+ /// The offset of the entry point within the traditional BIOS for Compatibility16 functions.
+ ///
+ UINT16 Compatibility16CallOffset;
+
+ ///
+ /// The segment of the entry point within the traditional BIOS for EfiCompatibility
+ /// to invoke the PnP installation check.
+ ///
+ UINT16 PnPInstallationCheckSegment;
+
+ ///
+ /// The Offset of the entry point within the traditional BIOS for EfiCompatibility
+ /// to invoke the PnP installation check.
+ ///
+ UINT16 PnPInstallationCheckOffset;
+
+ ///
+ /// EFI system resources table. Type EFI_SYSTEM_TABLE is defined in the IntelPlatform
+ /// Innovation Framework for EFI Driver Execution Environment Core Interface Specification (DXE CIS).
+ ///
+ UINT32 EfiSystemTable;
+
+ ///
+ /// The address of an OEM-provided identifier string. The string is null terminated.
+ ///
+ UINT32 OemIdStringPointer;
+
+ ///
+ /// The 32-bit physical address where ACPI RSD PTR is stored within the traditional
+ /// BIOS. The remained of the ACPI tables are located at their EFI addresses. The size
+ /// reserved is the maximum for ACPI 2.0. The EfiCompatibility will fill in the ACPI
+ /// RSD PTR with either the ACPI 1.0b or 2.0 values.
+ ///
+ UINT32 AcpiRsdPtrPointer;
+
+ ///
+ /// The OEM revision number. Usage is undefined but provided for OEM module usage.
+ ///
+ UINT16 OemRevision;
+
+ ///
+ /// The 32-bit physical address where INT15 E820 data is stored within the traditional
+ /// BIOS. The EfiCompatibility code will fill in the E820Pointer value and copy the
+ /// data to the indicated area.
+ ///
+ UINT32 E820Pointer;
+
+ ///
+ /// The length of the E820 data and is filled in by the EfiCompatibility code.
+ ///
+ UINT32 E820Length;
+
+ ///
+ /// The 32-bit physical address where the $PIR table is stored in the traditional BIOS.
+ /// The EfiCompatibility code will fill in the IrqRoutingTablePointer value and
+ /// copy the data to the indicated area.
+ ///
+ UINT32 IrqRoutingTablePointer;
+
+ ///
+ /// The length of the $PIR table and is filled in by the EfiCompatibility code.
+ ///
+ UINT32 IrqRoutingTableLength;
+
+ ///
+ /// The 32-bit physical address where the MP table is stored in the traditional BIOS.
+ /// The EfiCompatibility code will fill in the MpTablePtr value and copy the data
+ /// to the indicated area.
+ ///
+ UINT32 MpTablePtr;
+
+ ///
+ /// The length of the MP table and is filled in by the EfiCompatibility code.
+ ///
+ UINT32 MpTableLength;
+
+ ///
+ /// The segment of the OEM-specific INT table/code.
+ ///
+ UINT16 OemIntSegment;
+
+ ///
+ /// The offset of the OEM-specific INT table/code.
+ ///
+ UINT16 OemIntOffset;
+
+ ///
+ /// The segment of the OEM-specific 32-bit table/code.
+ ///
+ UINT16 Oem32Segment;
+
+ ///
+ /// The offset of the OEM-specific 32-bit table/code.
+ ///
+ UINT16 Oem32Offset;
+
+ ///
+ /// The segment of the OEM-specific 16-bit table/code.
+ ///
+ UINT16 Oem16Segment;
+
+ ///
+ /// The offset of the OEM-specific 16-bit table/code.
+ ///
+ UINT16 Oem16Offset;
+
+ ///
+ /// The segment of the TPM binary passed to 16-bit CSM.
+ ///
+ UINT16 TpmSegment;
+
+ ///
+ /// The offset of the TPM binary passed to 16-bit CSM.
+ ///
+ UINT16 TpmOffset;
+
+ ///
+ /// A pointer to a string identifying the independent BIOS vendor.
+ ///
+ UINT32 IbvPointer;
+
+ ///
+ /// This field is NULL for all systems not supporting PCI Express. This field is the base
+ /// value of the start of the PCI Express memory-mapped configuration registers and
+ /// must be filled in prior to EfiCompatibility code issuing the Compatibility16 function
+ /// Compatibility16InitializeYourself().
+ /// Compatibility16InitializeYourself() is defined in Compatibility16
+ /// Functions.
+ ///
+ UINT32 PciExpressBase;
+
+ ///
+ /// Maximum PCI bus number assigned.
+ ///
+ UINT8 LastPciBus;
+
+ ///
+ /// Start Address of Upper Memory Area (UMA) to be set as Read/Write. If
+ /// UmaAddress is a valid address in the shadow RAM, it also indicates that the region
+ /// from 0xC0000 to (UmaAddress - 1) can be used for Option ROM.
+ ///
+ UINT32 UmaAddress;
+
+ ///
+ /// Upper Memory Area size in bytes to be set as Read/Write. If zero, no UMA region
+ /// will be set as Read/Write (i.e. all Shadow RAM is set as Read-Only).
+ ///
+ UINT32 UmaSize;
+
+ ///
+ /// Start Address of high memory that can be used for permanent allocation. If zero,
+ /// high memory is not available for permanent allocation.
+ ///
+ UINT32 HiPermanentMemoryAddress;
+
+ ///
+ /// Size of high memory that can be used for permanent allocation in bytes. If zero,
+ /// high memory is not available for permanent allocation.
+ ///
+ UINT32 HiPermanentMemorySize;
+} EFI_COMPATIBILITY16_TABLE;
+
+///
+/// Functions provided by the CSM binary which communicate between the EfiCompatibility
+/// and Compatibility16 code.
+///
+/// Inconsistent with the specification here:
+/// The member's name started with "Compatibility16" [defined in Intel Framework
+/// Compatibility Support Module Specification / 0.97 version]
+/// has been changed to "Legacy16" since keeping backward compatible.
+///
+typedef enum {
+ ///
+ /// Causes the Compatibility16 code to do any internal initialization required.
+ /// Input:
+ /// AX = Compatibility16InitializeYourself
+ /// ES:BX = Pointer to EFI_TO_COMPATIBILITY16_INIT_TABLE
+ /// Return:
+ /// AX = Return Status codes
+ ///
+ Legacy16InitializeYourself = 0x0000,
+
+ ///
+ /// Causes the Compatibility16 BIOS to perform any drive number translations to match the boot sequence.
+ /// Input:
+ /// AX = Compatibility16UpdateBbs
+ /// ES:BX = Pointer to EFI_TO_COMPATIBILITY16_BOOT_TABLE
+ /// Return:
+ /// AX = Returned status codes
+ ///
+ Legacy16UpdateBbs = 0x0001,
+
+ ///
+ /// Allows the Compatibility16 code to perform any final actions before booting. The Compatibility16
+ /// code is read/write.
+ /// Input:
+ /// AX = Compatibility16PrepareToBoot
+ /// ES:BX = Pointer to EFI_TO_COMPATIBILITY16_BOOT_TABLE structure
+ /// Return:
+ /// AX = Returned status codes
+ ///
+ Legacy16PrepareToBoot = 0x0002,
+
+ ///
+ /// Causes the Compatibility16 BIOS to boot. The Compatibility16 code is Read/Only.
+ /// Input:
+ /// AX = Compatibility16Boot
+ /// Output:
+ /// AX = Returned status codes
+ ///
+ Legacy16Boot = 0x0003,
+
+ ///
+ /// Allows the Compatibility16 code to get the last device from which a boot was attempted. This is
+ /// stored in CMOS and is the priority number of the last attempted boot device.
+ /// Input:
+ /// AX = Compatibility16RetrieveLastBootDevice
+ /// Output:
+ /// AX = Returned status codes
+ /// BX = Priority number of the boot device.
+ ///
+ Legacy16RetrieveLastBootDevice = 0x0004,
+
+ ///
+ /// Allows the Compatibility16 code rehook INT13, INT18, and/or INT19 after dispatching a legacy OpROM.
+ /// Input:
+ /// AX = Compatibility16DispatchOprom
+ /// ES:BX = Pointer to EFI_DISPATCH_OPROM_TABLE
+ /// Output:
+ /// AX = Returned status codes
+ /// BX = Number of non-BBS-compliant devices found. Equals 0 if BBS compliant.
+ ///
+ Legacy16DispatchOprom = 0x0005,
+
+ ///
+ /// Finds a free area in the 0xFxxxx or 0xExxxx region of the specified length and returns the address
+ /// of that region.
+ /// Input:
+ /// AX = Compatibility16GetTableAddress
+ /// BX = Allocation region
+ /// 00 = Allocate from either 0xE0000 or 0xF0000 64 KB blocks.
+ /// Bit 0 = 1 Allocate from 0xF0000 64 KB block
+ /// Bit 1 = 1 Allocate from 0xE0000 64 KB block
+ /// CX = Requested length in bytes.
+ /// DX = Required address alignment. Bit mapped. First non-zero bit from the right is the alignment.
+ /// Output:
+ /// AX = Returned status codes
+ /// DS:BX = Address of the region
+ ///
+ Legacy16GetTableAddress = 0x0006,
+
+ ///
+ /// Enables the EfiCompatibility module to do any nonstandard processing of keyboard LEDs or state.
+ /// Input:
+ /// AX = Compatibility16SetKeyboardLeds
+ /// CL = LED status.
+ /// Bit 0 Scroll Lock 0 = Off
+ /// Bit 1 NumLock
+ /// Bit 2 Caps Lock
+ /// Output:
+ /// AX = Returned status codes
+ ///
+ Legacy16SetKeyboardLeds = 0x0007,
+
+ ///
+ /// Enables the EfiCompatibility module to install an interrupt handler for PCI mass media devices that
+ /// do not have an OpROM associated with them. An example is SATA.
+ /// Input:
+ /// AX = Compatibility16InstallPciHandler
+ /// ES:BX = Pointer to EFI_LEGACY_INSTALL_PCI_HANDLER structure
+ /// Output:
+ /// AX = Returned status codes
+ ///
+ Legacy16InstallPciHandler = 0x0008
+} EFI_COMPATIBILITY_FUNCTIONS;
+
+///
+/// EFI_DISPATCH_OPROM_TABLE
+///
+typedef struct {
+ UINT16 PnPInstallationCheckSegment; ///< A pointer to the PnpInstallationCheck data structure.
+ UINT16 PnPInstallationCheckOffset; ///< A pointer to the PnpInstallationCheck data structure.
+ UINT16 OpromSegment; ///< The segment where the OpROM was placed. Offset is assumed to be 3.
+ UINT8 PciBus; ///< The PCI bus.
+ UINT8 PciDeviceFunction; ///< The PCI device * 0x08 | PCI function.
+ UINT8 NumberBbsEntries; ///< The number of valid BBS table entries upon entry and exit. The IBV code may
+ ///< increase this number, if BBS-compliant devices also hook INTs in order to force the
+ ///< OpROM BIOS Setup to be executed.
+ UINT32 BbsTablePointer; ///< A pointer to the BBS table.
+ UINT16 RuntimeSegment; ///< The segment where the OpROM can be relocated to. If this value is 0x0000, this
+ ///< means that the relocation of this run time code is not supported.
+ ///< Inconsistent with specification here:
+ ///< The member's name "OpromDestinationSegment" [defined in Intel Framework Compatibility Support Module Specification / 0.97 version]
+ ///< has been changed to "RuntimeSegment" since keeping backward compatible.
+} EFI_DISPATCH_OPROM_TABLE;
+
+///
+/// EFI_TO_COMPATIBILITY16_INIT_TABLE
+///
+typedef struct {
+ ///
+ /// Starting address of memory under 1 MB. The ending address is assumed to be 640 KB or 0x9FFFF.
+ ///
+ UINT32 BiosLessThan1MB;
+
+ ///
+ /// The starting address of the high memory block.
+ ///
+ UINT32 HiPmmMemory;
+
+ ///
+ /// The length of high memory block.
+ ///
+ UINT32 HiPmmMemorySizeInBytes;
+
+ ///
+ /// The segment of the reverse thunk call code.
+ ///
+ UINT16 ReverseThunkCallSegment;
+
+ ///
+ /// The offset of the reverse thunk call code.
+ ///
+ UINT16 ReverseThunkCallOffset;
+
+ ///
+ /// The number of E820 entries copied to the Compatibility16 BIOS.
+ ///
+ UINT32 NumberE820Entries;
+
+ ///
+ /// The amount of usable memory above 1 MB, e.g., E820 type 1 memory.
+ ///
+ UINT32 OsMemoryAbove1Mb;
+
+ ///
+ /// The start of thunk code in main memory. Memory cannot be used by BIOS or PMM.
+ ///
+ UINT32 ThunkStart;
+
+ ///
+ /// The size of the thunk code.
+ ///
+ UINT32 ThunkSizeInBytes;
+
+ ///
+ /// Starting address of memory under 1 MB.
+ ///
+ UINT32 LowPmmMemory;
+
+ ///
+ /// The length of low Memory block.
+ ///
+ UINT32 LowPmmMemorySizeInBytes;
+} EFI_TO_COMPATIBILITY16_INIT_TABLE;
+
+///
+/// DEVICE_PRODUCER_SERIAL.
+///
+typedef struct {
+ UINT16 Address; ///< I/O address assigned to the serial port.
+ UINT8 Irq; ///< IRQ assigned to the serial port.
+ SERIAL_MODE Mode; ///< Mode of serial port. Values are defined below.
+} DEVICE_PRODUCER_SERIAL;
+
+///
+/// DEVICE_PRODUCER_SERIAL's modes.
+///@{
+#define DEVICE_SERIAL_MODE_NORMAL 0x00
+#define DEVICE_SERIAL_MODE_IRDA 0x01
+#define DEVICE_SERIAL_MODE_ASK_IR 0x02
+#define DEVICE_SERIAL_MODE_DUPLEX_HALF 0x00
+#define DEVICE_SERIAL_MODE_DUPLEX_FULL 0x10
+/// @)
+
+///
+/// DEVICE_PRODUCER_PARALLEL.
+///
+typedef struct {
+ UINT16 Address; ///< I/O address assigned to the parallel port.
+ UINT8 Irq; ///< IRQ assigned to the parallel port.
+ UINT8 Dma; ///< DMA assigned to the parallel port.
+ PARALLEL_MODE Mode; ///< Mode of the parallel port. Values are defined below.
+} DEVICE_PRODUCER_PARALLEL;
+
+///
+/// DEVICE_PRODUCER_PARALLEL's modes.
+///@{
+#define DEVICE_PARALLEL_MODE_MODE_OUTPUT_ONLY 0x00
+#define DEVICE_PARALLEL_MODE_MODE_BIDIRECTIONAL 0x01
+#define DEVICE_PARALLEL_MODE_MODE_EPP 0x02
+#define DEVICE_PARALLEL_MODE_MODE_ECP 0x03
+///@}
+
+///
+/// DEVICE_PRODUCER_FLOPPY
+///
+typedef struct {
+ UINT16 Address; ///< I/O address assigned to the floppy.
+ UINT8 Irq; ///< IRQ assigned to the floppy.
+ UINT8 Dma; ///< DMA assigned to the floppy.
+ UINT8 NumberOfFloppy; ///< Number of floppies in the system.
+} DEVICE_PRODUCER_FLOPPY;
+
+///
+/// LEGACY_DEVICE_FLAGS
+///
+typedef struct {
+ UINT32 A20Kybd : 1; ///< A20 controller by keyboard controller.
+ UINT32 A20Port90 : 1; ///< A20 controlled by port 0x92.
+ UINT32 Reserved : 30; ///< Reserved for future usage.
+} LEGACY_DEVICE_FLAGS;
+
+///
+/// DEVICE_PRODUCER_DATA_HEADER
+///
+typedef struct {
+ DEVICE_PRODUCER_SERIAL Serial[4]; ///< Data for serial port x. Type DEVICE_PRODUCER_SERIAL is defined below.
+ DEVICE_PRODUCER_PARALLEL Parallel[3]; ///< Data for parallel port x. Type DEVICE_PRODUCER_PARALLEL is defined below.
+ DEVICE_PRODUCER_FLOPPY Floppy; ///< Data for floppy. Type DEVICE_PRODUCER_FLOPPY is defined below.
+ UINT8 MousePresent; ///< Flag to indicate if mouse is present.
+ LEGACY_DEVICE_FLAGS Flags; ///< Miscellaneous Boolean state information passed to CSM.
+} DEVICE_PRODUCER_DATA_HEADER;
+
+///
+/// ATAPI_IDENTIFY
+///
+typedef struct {
+ UINT16 Raw[256]; ///< Raw data from the IDE IdentifyDrive command.
+} ATAPI_IDENTIFY;
+
+///
+/// HDD_INFO
+///
+typedef struct {
+ ///
+ /// Status of IDE device. Values are defined below. There is one HDD_INFO structure
+ /// per IDE controller. The IdentifyDrive is per drive. Index 0 is master and index
+ /// 1 is slave.
+ ///
+ UINT16 Status;
+
+ ///
+ /// PCI bus of IDE controller.
+ ///
+ UINT32 Bus;
+
+ ///
+ /// PCI device of IDE controller.
+ ///
+ UINT32 Device;
+
+ ///
+ /// PCI function of IDE controller.
+ ///
+ UINT32 Function;
+
+ ///
+ /// Command ports base address.
+ ///
+ UINT16 CommandBaseAddress;
+
+ ///
+ /// Control ports base address.
+ ///
+ UINT16 ControlBaseAddress;
+
+ ///
+ /// Bus master address.
+ ///
+ UINT16 BusMasterAddress;
+
+ UINT8 HddIrq;
+
+ ///
+ /// Data that identifies the drive data; one per possible attached drive.
+ ///
+ ATAPI_IDENTIFY IdentifyDrive[2];
+} HDD_INFO;
+
+///
+/// HDD_INFO status bits
+///
+#define HDD_PRIMARY 0x01
+#define HDD_SECONDARY 0x02
+#define HDD_MASTER_ATAPI_CDROM 0x04
+#define HDD_SLAVE_ATAPI_CDROM 0x08
+#define HDD_MASTER_IDE 0x20
+#define HDD_SLAVE_IDE 0x40
+#define HDD_MASTER_ATAPI_ZIPDISK 0x10
+#define HDD_SLAVE_ATAPI_ZIPDISK 0x80
+
+///
+/// BBS_STATUS_FLAGS;\.
+///
+typedef struct {
+ UINT16 OldPosition : 4; ///< Prior priority.
+ UINT16 Reserved1 : 4; ///< Reserved for future use.
+ UINT16 Enabled : 1; ///< If 0, ignore this entry.
+ UINT16 Failed : 1; ///< 0 = Not known if boot failure occurred.
+ ///< 1 = Boot attempted failed.
+
+ ///
+ /// State of media present.
+ /// 00 = No bootable media is present in the device.
+ /// 01 = Unknown if a bootable media present.
+ /// 10 = Media is present and appears bootable.
+ /// 11 = Reserved.
+ ///
+ UINT16 MediaPresent : 2;
+ UINT16 Reserved2 : 4; ///< Reserved for future use.
+} BBS_STATUS_FLAGS;
+
+///
+/// BBS_TABLE, device type values & boot priority values.
+///
+typedef struct {
+ ///
+ /// The boot priority for this boot device. Values are defined below.
+ ///
+ UINT16 BootPriority;
+
+ ///
+ /// The PCI bus for this boot device.
+ ///
+ UINT32 Bus;
+
+ ///
+ /// The PCI device for this boot device.
+ ///
+ UINT32 Device;
+
+ ///
+ /// The PCI function for the boot device.
+ ///
+ UINT32 Function;
+
+ ///
+ /// The PCI class for this boot device.
+ ///
+ UINT8 Class;
+
+ ///
+ /// The PCI Subclass for this boot device.
+ ///
+ UINT8 SubClass;
+
+ ///
+ /// Segment:offset address of an ASCIIZ description string describing the manufacturer.
+ ///
+ UINT16 MfgStringOffset;
+
+ ///
+ /// Segment:offset address of an ASCIIZ description string describing the manufacturer.
+ ///
+ UINT16 MfgStringSegment;
+
+ ///
+ /// BBS device type. BBS device types are defined below.
+ ///
+ UINT16 DeviceType;
+
+ ///
+ /// Status of this boot device. Type BBS_STATUS_FLAGS is defined below.
+ ///
+ BBS_STATUS_FLAGS StatusFlags;
+
+ ///
+ /// Segment:Offset address of boot loader for IPL devices or install INT13 handler for
+ /// BCV devices.
+ ///
+ UINT16 BootHandlerOffset;
+
+ ///
+ /// Segment:Offset address of boot loader for IPL devices or install INT13 handler for
+ /// BCV devices.
+ ///
+ UINT16 BootHandlerSegment;
+
+ ///
+ /// Segment:offset address of an ASCIIZ description string describing this device.
+ ///
+ UINT16 DescStringOffset;
+
+ ///
+ /// Segment:offset address of an ASCIIZ description string describing this device.
+ ///
+ UINT16 DescStringSegment;
+
+ ///
+ /// Reserved.
+ ///
+ UINT32 InitPerReserved;
+
+ ///
+ /// The use of these fields is IBV dependent. They can be used to flag that an OpROM
+ /// has hooked the specified IRQ. The OpROM may be BBS compliant as some SCSI
+ /// BBS-compliant OpROMs also hook IRQ vectors in order to run their BIOS Setup
+ ///
+ UINT32 AdditionalIrq13Handler;
+
+ ///
+ /// The use of these fields is IBV dependent. They can be used to flag that an OpROM
+ /// has hooked the specified IRQ. The OpROM may be BBS compliant as some SCSI
+ /// BBS-compliant OpROMs also hook IRQ vectors in order to run their BIOS Setup
+ ///
+ UINT32 AdditionalIrq18Handler;
+
+ ///
+ /// The use of these fields is IBV dependent. They can be used to flag that an OpROM
+ /// has hooked the specified IRQ. The OpROM may be BBS compliant as some SCSI
+ /// BBS-compliant OpROMs also hook IRQ vectors in order to run their BIOS Setup
+ ///
+ UINT32 AdditionalIrq19Handler;
+
+ ///
+ /// The use of these fields is IBV dependent. They can be used to flag that an OpROM
+ /// has hooked the specified IRQ. The OpROM may be BBS compliant as some SCSI
+ /// BBS-compliant OpROMs also hook IRQ vectors in order to run their BIOS Setup
+ ///
+ UINT32 AdditionalIrq40Handler;
+ UINT8 AssignedDriveNumber;
+ UINT32 AdditionalIrq41Handler;
+ UINT32 AdditionalIrq46Handler;
+ UINT32 IBV1;
+ UINT32 IBV2;
+} BBS_TABLE;
+
+///
+/// BBS device type values
+///@{
+#define BBS_FLOPPY 0x01
+#define BBS_HARDDISK 0x02
+#define BBS_CDROM 0x03
+#define BBS_PCMCIA 0x04
+#define BBS_USB 0x05
+#define BBS_EMBED_NETWORK 0x06
+#define BBS_BEV_DEVICE 0x80
+#define BBS_UNKNOWN 0xff
+///@}
+
+///
+/// BBS boot priority values
+///@{
+#define BBS_DO_NOT_BOOT_FROM 0xFFFC
+#define BBS_LOWEST_PRIORITY 0xFFFD
+#define BBS_UNPRIORITIZED_ENTRY 0xFFFE
+#define BBS_IGNORE_ENTRY 0xFFFF
+///@}
+
+///
+/// SMM_ATTRIBUTES
+///
+typedef struct {
+ ///
+ /// Access mechanism used to generate the soft SMI. Defined types are below. The other
+ /// values are reserved for future usage.
+ ///
+ UINT16 Type : 3;
+
+ ///
+ /// The size of "port" in bits. Defined values are below.
+ ///
+ UINT16 PortGranularity : 3;
+
+ ///
+ /// The size of data in bits. Defined values are below.
+ ///
+ UINT16 DataGranularity : 3;
+
+ ///
+ /// Reserved for future use.
+ ///
+ UINT16 Reserved : 7;
+} SMM_ATTRIBUTES;
+
+///
+/// SMM_ATTRIBUTES type values.
+///@{
+#define STANDARD_IO 0x00
+#define STANDARD_MEMORY 0x01
+///@}
+
+///
+/// SMM_ATTRIBUTES port size constants.
+///@{
+#define PORT_SIZE_8 0x00
+#define PORT_SIZE_16 0x01
+#define PORT_SIZE_32 0x02
+#define PORT_SIZE_64 0x03
+///@}
+
+///
+/// SMM_ATTRIBUTES data size constants.
+///@{
+#define DATA_SIZE_8 0x00
+#define DATA_SIZE_16 0x01
+#define DATA_SIZE_32 0x02
+#define DATA_SIZE_64 0x03
+///@}
+
+///
+/// SMM_FUNCTION & relating constants.
+///
+typedef struct {
+ UINT16 Function : 15;
+ UINT16 Owner : 1;
+} SMM_FUNCTION;
+
+///
+/// SMM_FUNCTION Function constants.
+///@{
+#define INT15_D042 0x0000
+#define GET_USB_BOOT_INFO 0x0001
+#define DMI_PNP_50_57 0x0002
+///@}
+
+///
+/// SMM_FUNCTION Owner constants.
+///@{
+#define STANDARD_OWNER 0x0
+#define OEM_OWNER 0x1
+///@}
+
+///
+/// This structure assumes both port and data sizes are 1. SmmAttribute must be
+/// properly to reflect that assumption.
+///
+typedef struct {
+ ///
+ /// Describes the access mechanism, SmmPort, and SmmData sizes. Type
+ /// SMM_ATTRIBUTES is defined below.
+ ///
+ SMM_ATTRIBUTES SmmAttributes;
+
+ ///
+ /// Function Soft SMI is to perform. Type SMM_FUNCTION is defined below.
+ ///
+ SMM_FUNCTION SmmFunction;
+
+ ///
+ /// SmmPort size depends upon SmmAttributes and ranges from2 bytes to 16 bytes.
+ ///
+ UINT8 SmmPort;
+
+ ///
+ /// SmmData size depends upon SmmAttributes and ranges from2 bytes to 16 bytes.
+ ///
+ UINT8 SmmData;
+} SMM_ENTRY;
+
+///
+/// SMM_TABLE
+///
+typedef struct {
+ UINT16 NumSmmEntries; ///< Number of entries represented by SmmEntry.
+ SMM_ENTRY SmmEntry; ///< One entry per function. Type SMM_ENTRY is defined below.
+} SMM_TABLE;
+
+///
+/// UDC_ATTRIBUTES
+///
+typedef struct {
+ ///
+ /// This bit set indicates that the ServiceAreaData is valid.
+ ///
+ UINT8 DirectoryServiceValidity : 1;
+
+ ///
+ /// This bit set indicates to use the Reserve Area Boot Code Address (RACBA) only if
+ /// DirectoryServiceValidity is 0.
+ ///
+ UINT8 RabcaUsedFlag : 1;
+
+ ///
+ /// This bit set indicates to execute hard disk diagnostics.
+ ///
+ UINT8 ExecuteHddDiagnosticsFlag : 1;
+
+ ///
+ /// Reserved for future use. Set to 0.
+ ///
+ UINT8 Reserved : 5;
+} UDC_ATTRIBUTES;
+
+///
+/// UD_TABLE
+///
+typedef struct {
+ ///
+ /// This field contains the bit-mapped attributes of the PARTIES information. Type
+ /// UDC_ATTRIBUTES is defined below.
+ ///
+ UDC_ATTRIBUTES Attributes;
+
+ ///
+ /// This field contains the zero-based device on which the selected
+ /// ServiceDataArea is present. It is 0 for master and 1 for the slave device.
+ ///
+ UINT8 DeviceNumber;
+
+ ///
+ /// This field contains the zero-based index into the BbsTable for the parent device.
+ /// This index allows the user to reference the parent device information such as PCI
+ /// bus, device function.
+ ///
+ UINT8 BbsTableEntryNumberForParentDevice;
+
+ ///
+ /// This field contains the zero-based index into the BbsTable for the boot entry.
+ ///
+ UINT8 BbsTableEntryNumberForBoot;
+
+ ///
+ /// This field contains the zero-based index into the BbsTable for the HDD diagnostics entry.
+ ///
+ UINT8 BbsTableEntryNumberForHddDiag;
+
+ ///
+ /// The raw Beer data.
+ ///
+ UINT8 BeerData[128];
+
+ ///
+ /// The raw data of selected service area.
+ ///
+ UINT8 ServiceAreaData[64];
+} UD_TABLE;
+
+#define EFI_TO_LEGACY_MAJOR_VERSION 0x02
+#define EFI_TO_LEGACY_MINOR_VERSION 0x00
+#define MAX_IDE_CONTROLLER 8
+
+///
+/// EFI_TO_COMPATIBILITY16_BOOT_TABLE
+///
+typedef struct {
+ UINT16 MajorVersion; ///< The EfiCompatibility major version number.
+ UINT16 MinorVersion; ///< The EfiCompatibility minor version number.
+ UINT32 AcpiTable; ///< The location of the RSDT ACPI table. < 4G range.
+ UINT32 SmbiosTable; ///< The location of the SMBIOS table in EFI memory. < 4G range.
+ UINT32 SmbiosTableLength;
+ //
+ // Legacy SIO state
+ //
+ DEVICE_PRODUCER_DATA_HEADER SioData; ///< Standard traditional device information.
+ UINT16 DevicePathType; ///< The default boot type.
+ UINT16 PciIrqMask; ///< Mask of which IRQs have been assigned to PCI.
+ UINT32 NumberE820Entries; ///< Number of E820 entries. The number can change from the
+ ///< Compatibility16InitializeYourself() function.
+ //
+ // Controller & Drive Identify[2] per controller information
+ //
+ HDD_INFO HddInfo[MAX_IDE_CONTROLLER]; ///< Hard disk drive information, including raw Identify Drive data.
+ UINT32 NumberBbsEntries; ///< Number of entries in the BBS table
+ UINT32 BbsTable; ///< A pointer to the BBS table. Type BBS_TABLE is defined below.
+ UINT32 SmmTable; ///< A pointer to the SMM table. Type SMM_TABLE is defined below.
+ UINT32 OsMemoryAbove1Mb; ///< The amount of usable memory above 1 MB, i.e. E820 type 1 memory. This value can
+ ///< differ from the value in EFI_TO_COMPATIBILITY16_INIT_TABLE as more
+ ///< memory may have been discovered.
+ UINT32 UnconventionalDeviceTable; ///< Information to boot off an unconventional device like a PARTIES partition. Type
+ ///< UD_TABLE is defined below.
+} EFI_TO_COMPATIBILITY16_BOOT_TABLE;
+
+///
+/// EFI_LEGACY_INSTALL_PCI_HANDLER
+///
+typedef struct {
+ UINT8 PciBus; ///< The PCI bus of the device.
+ UINT8 PciDeviceFun; ///< The PCI device in bits 7:3 and function in bits 2:0.
+ UINT8 PciSegment; ///< The PCI segment of the device.
+ UINT8 PciClass; ///< The PCI class code of the device.
+ UINT8 PciSubclass; ///< The PCI subclass code of the device.
+ UINT8 PciInterface; ///< The PCI interface code of the device.
+ //
+ // Primary section
+ //
+ UINT8 PrimaryIrq; ///< The primary device IRQ.
+ UINT8 PrimaryReserved; ///< Reserved.
+ UINT16 PrimaryControl; ///< The primary device control I/O base.
+ UINT16 PrimaryBase; ///< The primary device I/O base.
+ UINT16 PrimaryBusMaster; ///< The primary device bus master I/O base.
+ //
+ // Secondary Section
+ //
+ UINT8 SecondaryIrq; ///< The secondary device IRQ.
+ UINT8 SecondaryReserved; ///< Reserved.
+ UINT16 SecondaryControl; ///< The secondary device control I/O base.
+ UINT16 SecondaryBase; ///< The secondary device I/O base.
+ UINT16 SecondaryBusMaster; ///< The secondary device bus master I/O base.
+} EFI_LEGACY_INSTALL_PCI_HANDLER;
+
+//
+// Restore default pack value
+//
+#pragma pack()
+
+#define EFI_LEGACY_BIOS_PROTOCOL_GUID \
+ { \
+ 0xdb9a1e3d, 0x45cb, 0x4abb, {0x85, 0x3b, 0xe5, 0x38, 0x7f, 0xdb, 0x2e, 0x2d } \
+ }
+
+typedef struct _EFI_LEGACY_BIOS_PROTOCOL EFI_LEGACY_BIOS_PROTOCOL;
+
+///
+/// Flags returned by CheckPciRom().
+///
+#define NO_ROM 0x00
+#define ROM_FOUND 0x01
+#define VALID_LEGACY_ROM 0x02
+#define ROM_WITH_CONFIG 0x04 ///< Not defined in the Framework CSM Specification.
+
+///
+/// The following macros do not appear in the Framework CSM Specification and
+/// are kept for backward compatibility only. They convert 32-bit address (_Adr)
+/// to Segment:Offset 16-bit form.
+///
+///@{
+#define EFI_SEGMENT(_Adr) (UINT16) ((UINT16) (((UINTN) (_Adr)) >> 4) & 0xf000)
+#define EFI_OFFSET(_Adr) (UINT16) (((UINT16) ((UINTN) (_Adr))) & 0xffff)
+///@}
+
+#define CARRY_FLAG 0x01
+
+///
+/// EFI_EFLAGS_REG
+///
+typedef struct {
+ UINT32 CF : 1;
+ UINT32 Reserved1 : 1;
+ UINT32 PF : 1;
+ UINT32 Reserved2 : 1;
+ UINT32 AF : 1;
+ UINT32 Reserved3 : 1;
+ UINT32 ZF : 1;
+ UINT32 SF : 1;
+ UINT32 TF : 1;
+ UINT32 IF : 1;
+ UINT32 DF : 1;
+ UINT32 OF : 1;
+ UINT32 IOPL : 2;
+ UINT32 NT : 1;
+ UINT32 Reserved4 : 2;
+ UINT32 VM : 1;
+ UINT32 Reserved5 : 14;
+} EFI_EFLAGS_REG;
+
+///
+/// EFI_DWORD_REGS
+///
+typedef struct {
+ UINT32 EAX;
+ UINT32 EBX;
+ UINT32 ECX;
+ UINT32 EDX;
+ UINT32 ESI;
+ UINT32 EDI;
+ EFI_EFLAGS_REG EFlags;
+ UINT16 ES;
+ UINT16 CS;
+ UINT16 SS;
+ UINT16 DS;
+ UINT16 FS;
+ UINT16 GS;
+ UINT32 EBP;
+ UINT32 ESP;
+} EFI_DWORD_REGS;
+
+///
+/// EFI_FLAGS_REG
+///
+typedef struct {
+ UINT16 CF : 1;
+ UINT16 Reserved1 : 1;
+ UINT16 PF : 1;
+ UINT16 Reserved2 : 1;
+ UINT16 AF : 1;
+ UINT16 Reserved3 : 1;
+ UINT16 ZF : 1;
+ UINT16 SF : 1;
+ UINT16 TF : 1;
+ UINT16 IF : 1;
+ UINT16 DF : 1;
+ UINT16 OF : 1;
+ UINT16 IOPL : 2;
+ UINT16 NT : 1;
+ UINT16 Reserved4 : 1;
+} EFI_FLAGS_REG;
+
+///
+/// EFI_WORD_REGS
+///
+typedef struct {
+ UINT16 AX;
+ UINT16 ReservedAX;
+ UINT16 BX;
+ UINT16 ReservedBX;
+ UINT16 CX;
+ UINT16 ReservedCX;
+ UINT16 DX;
+ UINT16 ReservedDX;
+ UINT16 SI;
+ UINT16 ReservedSI;
+ UINT16 DI;
+ UINT16 ReservedDI;
+ EFI_FLAGS_REG Flags;
+ UINT16 ReservedFlags;
+ UINT16 ES;
+ UINT16 CS;
+ UINT16 SS;
+ UINT16 DS;
+ UINT16 FS;
+ UINT16 GS;
+ UINT16 BP;
+ UINT16 ReservedBP;
+ UINT16 SP;
+ UINT16 ReservedSP;
+} EFI_WORD_REGS;
+
+///
+/// EFI_BYTE_REGS
+///
+typedef struct {
+ UINT8 AL, AH;
+ UINT16 ReservedAX;
+ UINT8 BL, BH;
+ UINT16 ReservedBX;
+ UINT8 CL, CH;
+ UINT16 ReservedCX;
+ UINT8 DL, DH;
+ UINT16 ReservedDX;
+} EFI_BYTE_REGS;
+
+///
+/// EFI_IA32_REGISTER_SET
+///
+typedef union {
+ EFI_DWORD_REGS E;
+ EFI_WORD_REGS X;
+ EFI_BYTE_REGS H;
+} EFI_IA32_REGISTER_SET;
+
+/**
+ Thunk to 16-bit real mode and execute a software interrupt with a vector
+ of BiosInt. Regs will contain the 16-bit register context on entry and
+ exit.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] BiosInt The processor interrupt vector to invoke.
+ @param[in,out] Reg Register contexted passed into (and returned) from thunk to
+ 16-bit mode.
+
+ @retval TRUE Thunk completed with no BIOS errors in the target code. See Regs for status.
+ @retval FALSE There was a BIOS error in the target code.
+**/
+typedef
+BOOLEAN
+(EFIAPI *EFI_LEGACY_BIOS_INT86)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UINT8 BiosInt,
+ IN OUT EFI_IA32_REGISTER_SET *Regs
+ );
+
+/**
+ Thunk to 16-bit real mode and call Segment:Offset. Regs will contain the
+ 16-bit register context on entry and exit. Arguments can be passed on
+ the Stack argument
+
+ @param[in] This The protocol instance pointer.
+ @param[in] Segment The segemnt of 16-bit mode call.
+ @param[in] Offset The offset of 16-bit mdoe call.
+ @param[in] Reg Register contexted passed into (and returned) from thunk to
+ 16-bit mode.
+ @param[in] Stack The caller allocated stack used to pass arguments.
+ @param[in] StackSize The size of Stack in bytes.
+
+ @retval FALSE Thunk completed with no BIOS errors in the target code. See Regs for status. @retval TRUE There was a BIOS error in the target code.
+**/
+typedef
+BOOLEAN
+(EFIAPI *EFI_LEGACY_BIOS_FARCALL86)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UINT16 Segment,
+ IN UINT16 Offset,
+ IN EFI_IA32_REGISTER_SET *Regs,
+ IN VOID *Stack,
+ IN UINTN StackSize
+ );
+
+/**
+ Test to see if a legacy PCI ROM exists for this device. Optionally return
+ the Legacy ROM instance for this PCI device.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] PciHandle The PCI PC-AT OPROM from this devices ROM BAR will be loaded
+ @param[out] RomImage Return the legacy PCI ROM for this device.
+ @param[out] RomSize The size of ROM Image.
+ @param[out] Flags Indicates if ROM found and if PC-AT. Multiple bits can be set as follows:
+ - 00 = No ROM.
+ - 01 = ROM Found.
+ - 02 = ROM is a valid legacy ROM.
+
+ @retval EFI_SUCCESS The Legacy Option ROM available for this device
+ @retval EFI_UNSUPPORTED The Legacy Option ROM is not supported.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_CHECK_ROM)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN EFI_HANDLE PciHandle,
+ OUT VOID **RomImage OPTIONAL,
+ OUT UINTN *RomSize OPTIONAL,
+ OUT UINTN *Flags
+ );
+
+/**
+ Load a legacy PC-AT OPROM on the PciHandle device. Return information
+ about how many disks were added by the OPROM and the shadow address and
+ size. DiskStart & DiskEnd are INT 13h drive letters. Thus 0x80 is C:
+
+ @param[in] This The protocol instance pointer.
+ @param[in] PciHandle The PCI PC-AT OPROM from this devices ROM BAR will be loaded.
+ This value is NULL if RomImage is non-NULL. This is the normal
+ case.
+ @param[in] RomImage A PCI PC-AT ROM image. This argument is non-NULL if there is
+ no hardware associated with the ROM and thus no PciHandle,
+ otherwise is must be NULL.
+ Example is PXE base code.
+ @param[out] Flags The type of ROM discovered. Multiple bits can be set, as follows:
+ - 00 = No ROM.
+ - 01 = ROM found.
+ - 02 = ROM is a valid legacy ROM.
+ @param[out] DiskStart The disk number of first device hooked by the ROM. If DiskStart
+ is the same as DiskEnd no disked were hooked.
+ @param[out] DiskEnd disk number of the last device hooked by the ROM.
+ @param[out] RomShadowAddress Shadow address of PC-AT ROM.
+ @param[out] RomShadowSize Size of RomShadowAddress in bytes.
+
+ @retval EFI_SUCCESS Thunk completed, see Regs for status.
+ @retval EFI_INVALID_PARAMETER PciHandle not found
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_INSTALL_ROM)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN EFI_HANDLE PciHandle,
+ IN VOID **RomImage,
+ OUT UINTN *Flags,
+ OUT UINT8 *DiskStart OPTIONAL,
+ OUT UINT8 *DiskEnd OPTIONAL,
+ OUT VOID **RomShadowAddress OPTIONAL,
+ OUT UINT32 *ShadowedRomSize OPTIONAL
+ );
+
+/**
+ This function attempts to traditionally boot the specified BootOption. If the EFI context has
+ been compromised, this function will not return. This procedure is not used for loading an EFI-aware
+ OS off a traditional device. The following actions occur:
+ - Get EFI SMBIOS data structures, convert them to a traditional format, and copy to
+ Compatibility16.
+ - Get a pointer to ACPI data structures and copy the Compatibility16 RSD PTR to F0000 block.
+ - Find the traditional SMI handler from a firmware volume and register the traditional SMI
+ handler with the EFI SMI handler.
+ - Build onboard IDE information and pass this information to the Compatibility16 code.
+ - Make sure all PCI Interrupt Line registers are programmed to match 8259.
+ - Reconfigure SIO devices from EFI mode (polled) into traditional mode (interrupt driven).
+ - Shadow all PCI ROMs.
+ - Set up BDA and EBDA standard areas before the legacy boot.
+ - Construct the Compatibility16 boot memory map and pass it to the Compatibility16 code.
+ - Invoke the Compatibility16 table function Compatibility16PrepareToBoot(). This
+ invocation causes a thunk into the Compatibility16 code, which sets all appropriate internal
+ data structures. The boot device list is a parameter.
+ - Invoke the Compatibility16 Table function Compatibility16Boot(). This invocation
+ causes a thunk into the Compatibility16 code, which does an INT19.
+ - If the Compatibility16Boot() function returns, then the boot failed in a graceful
+ manner--meaning that the EFI code is still valid. An ungraceful boot failure causes a reset because the state
+ of EFI code is unknown.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] BootOption The EFI Device Path from BootXXXX variable.
+ @param[in] LoadOptionSize The size of LoadOption in size.
+ @param[in] LoadOption LThe oadOption from BootXXXX variable.
+
+ @retval EFI_DEVICE_ERROR Failed to boot from any boot device and memory is uncorrupted. Note: This function normally does not returns. It will either boot the OS or reset the system if memory has been "corrupted" by loading a boot sector and passing control to it.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_BOOT)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN BBS_BBS_DEVICE_PATH *BootOption,
+ IN UINT32 LoadOptionsSize,
+ IN VOID *LoadOptions
+ );
+
+/**
+ This function takes the Leds input parameter and sets/resets the BDA accordingly.
+ Leds is also passed to Compatibility16 code, in case any special processing is required.
+ This function is normally called from EFI Setup drivers that handle user-selectable
+ keyboard options such as boot with NUM LOCK on/off. This function does not
+ touch the keyboard or keyboard LEDs but only the BDA.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] Leds The status of current Scroll, Num & Cap lock LEDS:
+ - Bit 0 is Scroll Lock 0 = Not locked.
+ - Bit 1 is Num Lock.
+ - Bit 2 is Caps Lock.
+
+ @retval EFI_SUCCESS The BDA was updated successfully.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_UPDATE_KEYBOARD_LED_STATUS)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UINT8 Leds
+ );
+
+/**
+ Retrieve legacy BBS info and assign boot priority.
+
+ @param[in] This The protocol instance pointer.
+ @param[out] HddCount The number of HDD_INFO structures.
+ @param[out] HddInfo Onboard IDE controller information.
+ @param[out] BbsCount The number of BBS_TABLE structures.
+ @param[in,out] BbsTable Points to List of BBS_TABLE.
+
+ @retval EFI_SUCCESS Tables were returned.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_GET_BBS_INFO)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ OUT UINT16 *HddCount,
+ OUT HDD_INFO **HddInfo,
+ OUT UINT16 *BbsCount,
+ IN OUT BBS_TABLE **BbsTable
+ );
+
+/**
+ Assign drive number to legacy HDD drives prior to booting an EFI
+ aware OS so the OS can access drives without an EFI driver.
+
+ @param[in] This The protocol instance pointer.
+ @param[out] BbsCount The number of BBS_TABLE structures
+ @param[out] BbsTable List of BBS entries
+
+ @retval EFI_SUCCESS Drive numbers assigned.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_PREPARE_TO_BOOT_EFI)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ OUT UINT16 *BbsCount,
+ OUT BBS_TABLE **BbsTable
+ );
+
+/**
+ To boot from an unconventional device like parties and/or execute
+ HDD diagnostics.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] Attributes How to interpret the other input parameters.
+ @param[in] BbsEntry The 0-based index into the BbsTable for the parent
+ device.
+ @param[in] BeerData A pointer to the 128 bytes of ram BEER data.
+ @param[in] ServiceAreaData A pointer to the 64 bytes of raw Service Area data. The
+ caller must provide a pointer to the specific Service
+ Area and not the start all Service Areas.
+
+ @retval EFI_INVALID_PARAMETER If error. Does NOT return if no error.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_BOOT_UNCONVENTIONAL_DEVICE)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UDC_ATTRIBUTES Attributes,
+ IN UINTN BbsEntry,
+ IN VOID *BeerData,
+ IN VOID *ServiceAreaData
+ );
+
+/**
+ Shadow all legacy16 OPROMs that haven't been shadowed.
+ Warning: Use this with caution. This routine disconnects all EFI
+ drivers. If used externally, then the caller must re-connect EFI
+ drivers.
+
+ @param[in] This The protocol instance pointer.
+
+ @retval EFI_SUCCESS OPROMs were shadowed.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_SHADOW_ALL_LEGACY_OPROMS)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This
+ );
+
+/**
+ Get a region from the LegacyBios for S3 usage.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] LegacyMemorySize The size of required region.
+ @param[in] Region The region to use.
+ 00 = Either 0xE0000 or 0xF0000 block.
+ - Bit0 = 1 0xF0000 block.
+ - Bit1 = 1 0xE0000 block.
+ @param[in] Alignment Address alignment. Bit mapped. The first non-zero
+ bit from right is alignment.
+ @param[out] LegacyMemoryAddress The Region Assigned
+
+ @retval EFI_SUCCESS The Region was assigned.
+ @retval EFI_ACCESS_DENIED The function was previously invoked.
+ @retval Other The Region was not assigned.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_GET_LEGACY_REGION)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UINTN LegacyMemorySize,
+ IN UINTN Region,
+ IN UINTN Alignment,
+ OUT VOID **LegacyMemoryAddress
+ );
+
+/**
+ Get a region from the LegacyBios for Tiano usage. Can only be invoked once.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] LegacyMemorySize The size of data to copy.
+ @param[in] LegacyMemoryAddress The Legacy Region destination address.
+ Note: must be in region assigned by
+ LegacyBiosGetLegacyRegion.
+ @param[in] LegacyMemorySourceAddress The source of the data to copy.
+
+ @retval EFI_SUCCESS The Region assigned.
+ @retval EFI_ACCESS_DENIED Destination was outside an assigned region.
+
+**/
+typedef
+EFI_STATUS
+(EFIAPI *EFI_LEGACY_BIOS_COPY_LEGACY_REGION)(
+ IN EFI_LEGACY_BIOS_PROTOCOL *This,
+ IN UINTN LegacyMemorySize,
+ IN VOID *LegacyMemoryAddress,
+ IN VOID *LegacyMemorySourceAddress
+ );
+
+///
+/// Abstracts the traditional BIOS from the rest of EFI. The LegacyBoot()
+/// member function allows the BDS to support booting a traditional OS.
+/// EFI thunks drivers that make EFI bindings for BIOS INT services use
+/// all the other member functions.
+///
+struct _EFI_LEGACY_BIOS_PROTOCOL {
+ ///
+ /// Performs traditional software INT. See the Int86() function description.
+ ///
+ EFI_LEGACY_BIOS_INT86 Int86;
+
+ ///
+ /// Performs a far call into Compatibility16 or traditional OpROM code.
+ ///
+ EFI_LEGACY_BIOS_FARCALL86 FarCall86;
+
+ ///
+ /// Checks if a traditional OpROM exists for this device.
+ ///
+ EFI_LEGACY_BIOS_CHECK_ROM CheckPciRom;
+
+ ///
+ /// Loads a traditional OpROM in traditional OpROM address space.
+ ///
+ EFI_LEGACY_BIOS_INSTALL_ROM InstallPciRom;
+
+ ///
+ /// Boots a traditional OS.
+ ///
+ EFI_LEGACY_BIOS_BOOT LegacyBoot;
+
+ ///
+ /// Updates BDA to reflect the current EFI keyboard LED status.
+ ///
+ EFI_LEGACY_BIOS_UPDATE_KEYBOARD_LED_STATUS UpdateKeyboardLedStatus;
+
+ ///
+ /// Allows an external agent, such as BIOS Setup, to get the BBS data.
+ ///
+ EFI_LEGACY_BIOS_GET_BBS_INFO GetBbsInfo;
+
+ ///
+ /// Causes all legacy OpROMs to be shadowed.
+ ///
+ EFI_LEGACY_BIOS_SHADOW_ALL_LEGACY_OPROMS ShadowAllLegacyOproms;
+
+ ///
+ /// Performs all actions prior to boot. Used when booting an EFI-aware OS
+ /// rather than a legacy OS.
+ ///
+ EFI_LEGACY_BIOS_PREPARE_TO_BOOT_EFI PrepareToBootEfi;
+
+ ///
+ /// Allows EFI to reserve an area in the 0xE0000 or 0xF0000 block.
+ ///
+ EFI_LEGACY_BIOS_GET_LEGACY_REGION GetLegacyRegion;
+
+ ///
+ /// Allows EFI to copy data to the area specified by GetLegacyRegion.
+ ///
+ EFI_LEGACY_BIOS_COPY_LEGACY_REGION CopyLegacyRegion;
+
+ ///
+ /// Allows the user to boot off an unconventional device such as a PARTIES partition.
+ ///
+ EFI_LEGACY_BIOS_BOOT_UNCONVENTIONAL_DEVICE BootUnconventionalDevice;
+};
+
+//
+// Legacy BIOS needs to access memory in page 0 (0-4095), which is disabled if
+// NULL pointer detection feature is enabled. Following macro can be used to
+// enable/disable page 0 before/after accessing it.
+//
+#define ACCESS_PAGE0_CODE(statements) \
+ do { \
+ EFI_STATUS Status_; \
+ EFI_GCD_MEMORY_SPACE_DESCRIPTOR Desc_; \
+ \
+ Desc_.Attributes = 0; \
+ Status_ = gDS->GetMemorySpaceDescriptor (0, &Desc_); \
+ ASSERT_EFI_ERROR (Status_); \
+ if ((Desc_.Attributes & EFI_MEMORY_RP) != 0) { \
+ Status_ = gDS->SetMemorySpaceAttributes ( \
+ 0, \
+ EFI_PAGES_TO_SIZE(1), \
+ Desc_.Attributes & ~(UINT64)EFI_MEMORY_RP \
+ ); \
+ ASSERT_EFI_ERROR (Status_); \
+ } \
+ \
+ { \
+ statements; \
+ } \
+ \
+ if ((Desc_.Attributes & EFI_MEMORY_RP) != 0) { \
+ Status_ = gDS->SetMemorySpaceAttributes ( \
+ 0, \
+ EFI_PAGES_TO_SIZE(1), \
+ Desc_.Attributes \
+ ); \
+ ASSERT_EFI_ERROR (Status_); \
+ } \
+ } while (FALSE)
+
+extern EFI_GUID gEfiLegacyBiosProtocolGuid;
+
+#endif
diff --git a/Misc/Win7SecureBoot.png b/Misc/Win7SecureBoot.png
deleted file mode 100644
index 9cd911b..0000000
--- a/Misc/Win7SecureBoot.png
+++ /dev/null
Binary files differ
diff --git a/README.md b/README.md
index 4727354..4b7fce3 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,8 @@
# Overview
EfiGuard is a portable x64 UEFI bootkit that patches the Windows boot manager, boot loader and kernel at boot time in order to disable PatchGuard and Driver Signature Enforcement (DSE).
+If you're just looking to try EfiGuard, skip to [Usage](#usage).
+
# Features
- Currently supports all EFI-compatible versions of Windows x64 ever released, from Vista SP1 to Windows 11.
- Easy to use: can be booted from a USB stick or the Windows EFI partition via a loader that automatically finds and boots Windows. The driver can also be loaded and configured manually using either the UEFI shell or the loader.
@@ -8,14 +10,14 @@ EfiGuard is a portable x64 UEFI bootkit that patches the Windows boot manager, b
- Works passively: the driver does not load or start the Windows boot manager. Instead it acts on a load of `bootmgfw.efi` by the firmware boot manager via the boot selection menu or an EFI application such as the loader. If a non-Windows OS is booted, the driver will automatically unload itself.
- Supports four-stage patching for when `bootmgfw.efi` starts `bootmgr.efi` rather than `winload.efi`. This is the case when a WIM file is loaded to boot WinPE, Windows Setup or Windows Recovery mode.
- Graceful recovery: in case of patch failure, the driver will display error information and prompt to continue booting or to reboot by pressing ESC. This is true even up to the final kernel patch stage, because the last patch stage happens before `ExitBootServices` is called. Many UEFI Windows bootkits hook `OslArchTransferToKernel` which, while easy to find by pattern matching, is a function that executes in protected mode after `ExitBootServices`. This means no boot services are available to tell the user that something went wrong.
- ![bsod](Misc/BSOD.png)
+ ![bsod](.github/img/BSOD.png)
Simulated patch failure with error information
- Debuggable: can output messages to a kernel debugger and to the screen (albeit buffered) during the kernel patching stage, and to a serial port or unbuffered to the screen during the boot manager and boot loader patching stages. If the driver is compiled with PDB debug information, it is possible to load the debug symbols at any point after HAL initialization by specifying the virtual DXE driver base and debugging it as you would a regular NT driver.
- DSE bypasses: available as either a straightforward [UPGDSED](https://github.com/hfiref0x/UPGDSED)-style DSE disable at boot time or as a hook on the `SetVariable()` EFI runtime service. The latter serves as an arbitrary kernel mode read/write backdoor that can be called from Windows using `NtSetSystemEnvironmentValueEx` and allows setting `g_CiEnabled`/`g_CiOptions` to the desired value. A small DSEFix-style application named `EfiDSEFix.exe` is provided that can be used to do this. It is also possible to leave DSE enabled and to disable only PatchGuard. The loader will use the `SetVariable` hook method by default, due to the fact that some anti-cheat and anti-virus programs do not understand the difference between cheats or malware and self-signed drivers in general and target the UPGDSED fix.
- Supports on-disk modified kernels and boot loaders by patching `ImgpValidateImageHash` at every stage as well as `ImgpFilterValidationFailure`, which may silently rat out some classes of violations to a TPM or the SI log file.
- Allows Secure Boot to work with Windows 7 (not a joke!). Windows 7 itself is oblivious to Secure Boot as it does not support it, or (<a href="https://msdn.microsoft.com/en-us/ie/dn938339(v=vs.60)">officially</a>) even booting without CSM. This is useful for people who want to use Windows 7 on a locked down device that requires WHQL Secure Boot. Wiki entry on how to get this to work [here](https://github.com/Mattiwatti/EfiGuard/wiki/Secure-boot-on-Windows-7).
- ![win7_secureboot](Misc/Win7SecureBoot.png)
+ ![win7_secureboot](.github/img/Win7SecureBoot.png)
[WinObjEx64](https://github.com/hfiref0x/WinObjEx64) on Windows 7 with Secure Boot enabled
@@ -23,21 +25,41 @@ EfiGuard is a portable x64 UEFI bootkit that patches the Windows boot manager, b
- EfiGuard can not disable Hypervisor-enforced Code Integrity (HVCI or HyperGuard) due to HVCI running at a greater privilege level. EfiGuard **can** coexist with HVCI and even successfully disables PatchGuard in the normal kernel, but this is not useful in practice because HVCI will catch what PatchGuard did previously. Both types of DSE bypass are rendered useless by HVCI: the boot time patch has no effect because the kernel defers to the secure kernel for integrity checks, and the `SetVariable` hook will cause a `SECURE_KERNEL_ERROR` bugcheck if it is used to write to `g_CiOptions`.
- Checked kernels are not supported due to the differences in PatchGuard and DSE initialization code caused by disabled optimizations and added asserts, as well as additional changes to PatchGuard in checked kernels. This should not be an issue as checked kernels are not generally useful without a kernel debugger attached, which disables PatchGuard.
-# How to use
-There are two ways to use EfiGuard: booting the loader (easiest), or using the UEFI shell to load the driver. In both cases it is possible to install EfiGuard on a secondary boot medium such as a USB stick or on the EFI system partition. Using the EFI partition has the advantage of not requiring a second boot disk, but this method is more complex to set up. It is advised to try one of the methods below first, and read the instructions in [issue #2](https://github.com/Mattiwatti/EfiGuard/issues/2#issuecomment-478998015) if you want to install EfiGuard on the EFI partition.
+# Usage
+There are two ways to use EfiGuard: booting the **loader application**, which will load the driver and start Windows for you, or installing the driver as a **UEFI driver entry** so it will be loaded automatically by the firmware.
+
+Installing the driver can be preferable in some advanced configurations such as when multi-booting, but the loader is easiest to use and should work well in all configurations. See the table below for the most important differences between the two methods. If unsure, choose the **loader application**.
+
+| | Location | Installation | Skippable? | Which OS is booted? |
+|-------------------|----------------|----------------|--------------------|---------------------|
+| UEFI Driver Entry | Must be on ESP | Via UEFI Shell | :x: | Same as before |
+| Loader | Anywhere | Not needed | :heavy_check_mark: | Windows |
+
+Loader vs UEFI driver entry comparison
+
## Booting the loader
-1. Download or compile EfiGuard, go to `EFI/Boot` and rename one of `Loader.efi` or `Loader.config.efi` to `bootx64.efi`. The two are identical, except `Loader.efi` boots without user interaction whereas `Loader.config.efi` will prompt you to configure the DSE patch method used by the driver (if you want to change this).
-2. Place the files on a boot drive such as a USB stick (for physical machines) or an ISO/virtual disk (for VMs). The paths should be `/EFI/Boot/{bootx64|EfiGuardDxe}.efi`. It is recommended to use FAT32 formatted USB sticks.
-3. Boot the machine from the new drive instead of booting Windows. Most firmwares provide a boot menu to do this (accessible via F10/F11/F12). If not, you will need to configure the BIOS to boot from the new drive.
-4. If you are using the default loader, Windows should now boot, and you should see EfiGuard messages during boot. If you are using the configurable loader, answer the configuration prompts and Windows will boot.
-5. If you booted with the `SetVariable` hook (the default), run `EfiDSEFix.exe -d` from a command prompt after boot to disable DSE. Run `EfiDSEFix.exe` to see the full list of options.
-
-## Using the UEFI shell to load the driver
-1. Follow the steps 1 and 2 as above, but do not rename the loader to `bootx64.efi`. Instead, either use the BIOS-provided shell (if you have one), or download the [EDK2 UEFI Shell](https://github.com/tianocore/edk2/blob/edk2-stable201903/ShellBinPkg/UefiShell/X64/Shell.efi?raw=true) and rename it to `bootx64.efi`.
-2. Boot the machine to the UEFI shell.
-3. `cd` to `/EFI/Boot` on the correct filesystem and run `load EfiGuardDxe.efi` to load the driver.
-4. (Optional) Run either `Loader.efi` or `Loader.config.efi` from the same directory to boot Windows. You can also continue working in the shell, or `exit` to go back to the BIOS/boot menu and boot from there.
-5. After boot, apply the DSE fix as above if applicable.
+1. Download EfiGuard and rename `EFI/Boot/Loader.efi` to `bootx64.efi`.
+2. Place the files on a boot drive such as a FAT32 formatted USB stick (for physical machines) or an ISO/virtual disk (for VMs).
+ Assuming drive `X:`, the paths for the two files should now be `X:/EFI/Boot/{bootx64|EfiGuardDxe}.efi`
+3. Boot the machine from the drive you used in step 2.
+ Most firmwares provide a boot menu to do this via F8/F10/F11/F12. If not, you will need to configure the BIOS to boot from the new drive.
+4. Windows should now boot, and you should see EfiGuard messages during boot.
+5. If you booted with the `SetVariable` hook (the default), run `EfiDSEFix.exe -d` from an Administrator command prompt after boot to disable DSE, or run `EfiDSEFix.exe` to see the full list of options.
+
+Note that you **don't need to use a separate drive** for the loader. If preferable, you can install EfiGuard on the ESP that Windows is already installed on. However, this is somewhat more complicated as you will need to add a UEFI boot entry for the loader.
+
+To do this, mount the ESP at `X:` using `mountvol X: /S` and follow the steps above, but do **not** rename the loader and simply copy both files to `X:/EFI/Boot`. After that, you will need to manually add a UEFI boot entry from the [UEFI Shell](https://github.com/tianocore/edk2/blob/edk2-stable201903/ShellBinPkg/UefiShell/X64/Shell.efi?raw=true) using `bcfg boot addp 0 Loader.efi "EfiGuard"`, or alternatively using `efibootmgr` (Linux), EasyUEFI (Windows), or similar.
+
+## Installing the driver
+1. Mount the ESP at `X:` using `mountvol X: /S`.
+2. Copy `EfiGuardDxe.efi` to `X:/EFI/Boot/EfiGuardDxe.efi`.
+3. Boot to the [UEFI Shell](https://github.com/tianocore/edk2/blob/edk2-stable201903/ShellBinPkg/UefiShell/X64/Shell.efi?raw=true) and add a UEFI driver entry: `bcfg driver add 0 EfiGuardDxe.efi "EfiGuardDxe"`.
+4. Windows should now boot, and you should see EfiGuard messages during boot.
+5. If you booted with the `SetVariable` hook (the default), run `EfiDSEFix.exe -d` from an Administrator command prompt after boot to disable DSE, or run `EfiDSEFix.exe` to see the full list of options.
+
+**Note**: depending on your firmware, you may need to use "add**p**" in step 3 instead of "add". VirtualBox is known to require this, and possibly some motherboard firmwares do too.
+
+**Note**: some very old or noncompliant firmwares may not support this method of installation at all. On these systems you will have no option but to use the loader instead.
# Compilation
## Compiling EfiGuardDxe and the loader
@@ -59,7 +81,6 @@ Add `-D DO_NOT_DISABLE_PATCHGUARD=1` if you want to leave PatchGuard intact (Exp
## Last but not Least
This will produce `EfiGuardDxe.efi` and `Loader.efi` in `workspace/Build/EfiGuard/RELEASE_VS2019/X64`.
-To build the interactively configurable loader, append `-D CONFIGURE_DRIVER=1` to the build command.
If you've set `EFIGUARD_DRIVER_FILENAME`, you'll need to rename `EfiGuardDxe.efi` to `EFIGUARD_DRIVER_FILENAME`.
TODO: Rename automatic.
@@ -70,7 +91,6 @@ Copy both `*.efi` files to your EFI boot partition at `/EFI/Boot/`.
EfiDSEFix requires Visual Studio to build.
1. Open `EfiGuard.sln` and build the solution.
-
The output binary `EfiDSEFix.exe` will be in `Application/EfiDSEFix/bin`.
The Visual Studio solution also includes projects for `EfiGuardDxe.efi` and `Loader.efi` which can be used with [VisualUefi](https://github.com/ionescu007/VisualUefi), but these projects are not built by default as they will not link without additional code, and the build output will be inferior (bigger) than what EDK2 produces. `Loader.efi` will not link at all due to VisualUefi missing UefiBootManagerLib. These project files are thus meant as a development aid only and the EFI files should still be compiled with EDK2. To set up VisualUefi for this purpose, clone the repository into `workspace/VisualUefi` and open `EfiGuard.sln`.
@@ -99,7 +119,7 @@ and change `XXXX-XXXX` to the UUID returned by: `sudo blkid /dev/disk` whereas d
You may rename `Loader.efi` to any file you want, but keep in mind that `EfiGuardDxe.efi` needs to be in the same folder as `Loader.efi` ANDneeds to be renamed to `EFIGUARD_DRIVER_FILENAME` (if set).
# Architecture
- ![architecture](Misc/EfiGuard.svg)
+ ![architecture](.github/img/EfiGuard.svg)
While EfiGuard is a UEFI bootkit, it did not start out as one. EfiGuard was originally an on-disk patcher running on NT (similar to [UPGDSED](https://github.com/hfiref0x/UPGDSED)), intended to test the viability of a disassembler-based aproach, as opposed to using PDB symbols and version-specific signatures. [PatchNtoskrnl.c](EfiGuardDxe/PatchNtoskrnl.c) still looks very much like this original design. Only after this approach proved successful, with no modifications to code needed in over a year of Windows updates, did UEFI come into the picture as a way to further improve capabilities and ease of use.
Some of the benefits provided by a bootkit approach include: