2023-06-28 21:16:12

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 00/17] Integrity Policy Enforcement LSM (IPE)

Overview:
---------

IPE is a Linux Security Module which takes a complimentary approach to
access control. Whereas existing mandatory access control mechanisms
base their decisions on labels and paths, IPE instead determines
whether or not an operation should be allowed based on immutable
security properties of the system component the operation is being
performed on.

IPE itself does not mandate how the security property should be
evaluated, but relies on an extensible set of external property providers
to evaluate the component. IPE makes its decision based on reference
values for the selected properties, specified in the IPE policy.

The reference values represent the value that the policy writer and the
local system administrator (based on the policy signature) trust for the
system to accomplish the desired tasks.

One such provider is for example dm-verity, which is able to represent
the integrity property of a partition (its immutable state) with a digest.

IPE is compiled under CONFIG_SECURITY_IPE.

Use Cases
---------

IPE works best in fixed-function devices: Devices in which their purpose
is clearly defined and not supposed to be changed (e.g. network firewall
device in a data center, an IoT device, etcetera), where all software and
configuration is built and provisioned by the system owner.

IPE is a long-way off for use in general-purpose computing: the Linux
community as a whole tends to follow a decentralized trust model,
known as the web of trust, which IPE has no support for as of yet.
There are exceptions, such as the case where a Linux distribution
vendor trusts only their own keys, where IPE can successfully be used
to enforce the trust requirement.

Additionally, while most packages are signed today, the files inside
the packages (for instance, the executables), tend to be unsigned. This
makes it difficult to utilize IPE in systems where a package manager is
expected to be functional, without major changes to the package manager
and ecosystem behind it.

DIGLIM[1] is a system that when combined with IPE, could be used to
enable general purpose computing scenarios.

Policy:
-------

IPE policy is a plain-text policy composed of multiple statements
over several lines. There is one required line, at the top of the
policy, indicating the policy name, and the policy version, for
instance:

policy_name=Ex_Policy policy_version=0.0.0

The policy version indicates the current version of the policy. This is
used to prevent roll-back of policy to potentially insecure previous
versions of the policy.

The next portion of IPE policy, are rules. Rules are formed by key=value
pairs, known as properties. IPE rules require two keys: "action", which
determines what IPE does when it encounters a match against the policy
and "op", which determines when that rule should be evaluated.

Thus, a minimal rule is:

op=EXECUTE action=ALLOW

This example rule will allow any execution. A rule is required to have the
"op" property as the first token of a rule, and the "action" as the last
token of the rule.

Additional properties are used to restrict attributes about the files being
evaluated. These properties are intended to be deterministic attributes
that are resident in the kernel.

For example:

op=EXECUTE dmverity_signature=FALSE action=DENY

This rule with property dmverity_signature will deny any file not from
a signed dmverity volume to be executed.

All available properties for IPE described in the documentation patch of
this series.

Rules are evaluated top-to-bottom. As a result, any revocation rules,
or denies should be placed early in the file to ensure that these rules
are evaluated before a rule with "action=ALLOW" is hit.

Any unknown syntax in IPE policy will result in a fatal error to parse
the policy.

Additionally, a DEFAULT operation must be set for all understood
operations within IPE. For policies to remain completely forwards
compatible, it is recommended that users add a "DEFAULT action=ALLOW"
and override the defaults on a per-operation basis.

For more information about the policy syntax, see the kernel
documentation page.

Early Usermode Protection:
--------------------------

IPE can be provided with a policy at startup to load and enforce.
This is intended to be a minimal policy to get the system to a state
where userspace is setup and ready to receive commands, at which
point a policy can be deployed via securityfs. This "boot policy" can be
specified via the config, SECURITY_IPE_BOOT_POLICY, which accepts a path
to a plain-text version of the IPE policy to apply. This policy will be
compiled into the kernel. If not specified, IPE will be disabled until a
policy is deployed and activated through the method above.

Policy Examples:
----------------

Allow all:

policy_name=Allow_All policy_version=0.0.0
DEFAULT action=ALLOW

Allow only initial superblock:

policy_name=Allow_All_Initial_SB policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE boot_verified=TRUE action=ALLOW

Allow any signed dm-verity volume and the initial superblock:

policy_name=AllowSignedAndInitial policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE boot_verified=TRUE action=ALLOW
op=EXECUTE dmverity_signature=TRUE action=ALLOW

Prohibit execution from a specific dm-verity volume, while allowing
all signed volumes and the initial superblock:

policy_name=ProhibitSingleVolume policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE dmverity_roothash=sha256:401fcec5944823ae12f62726e8184407a5fa9599783f030dec146938 action=DENY
op=EXECUTE boot_verified=TRUE action=ALLOW
op=EXECUTE dmverity_signature=TRUE action=ALLOW

Allow only a specific dm-verity volume:

policy_name=AllowSpecific policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE dmverity_roothash=sha256:401fcec5944823ae12f62726e8184407a5fa9599783f030dec146938 action=ALLOW

Allow any signed fs-verity file

policy_name=AllowSignedFSVerity policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE fsverity_signature=TRUE action=ALLOW

Deny a specific fs-verity file:

policy_name=ProhibitSpecificFSVF policy_version=0.0.0
DEFAULT action=DENY

op=EXECUTE fsverity_digest=sha256:fd88f2b8824e197f850bf4c5109bea5cf0ee38104f710843bb72da796ba5af9e action=DENY
op=EXECUTE boot_verified=TRUE action=ALLOW
op=EXECUTE dmverity_signature=TRUE action=ALLOW

Deploying Policies:
-------------------

First sign a plain text policy, with a certificate that is present in
the SYSTEM_TRUSTED_KEYRING of your test machine. Through openssl, the
signing can be done via:

openssl smime -sign -in "$MY_POLICY" -signer "$MY_CERTIFICATE" \
-inkey "$MY_PRIVATE_KEY" -outform der -noattr -nodetach \
-out "$MY_POLICY.p7s"

Then, simply cat the file into the IPE's "new_policy" securityfs node:

cat "$MY_POLICY.p7s" > /sys/kernel/security/ipe/new_policy

The policy should now be present under the policies/ subdirectory, under
its "policy_name" attribute.

The policy is now present in the kernel and can be marked as active,
via the securityfs node:

echo 1 > "/sys/kernel/security/ipe/$MY_POLICY_NAME/active"

This will now mark the policy as active and the system will be enforcing
$MY_POLICY_NAME.

There is one requirement when marking a policy as active, the policy_version
attribute must either increase, or remain the same as the currently running
policy.

Policies can be updated via:

cat "$MY_UPDATED_POLICY.p7s" > \
"/sys/kernel/security/ipe/policies/$MY_POLICY_NAME/update"

Additionally, policies can be deleted via the "delete" securityfs
node. Simply write "1" to the corresponding node in the policy folder:

echo 1 > "/sys/kernel/security/ipe/policies/$MY_POLICY_NAME/delete"

There is only one requirement to delete policies, the policy being
deleted must not be the active policy.

NOTE: Any securityfs write to IPE's nodes will require CAP_MAC_ADMIN.

Integrations:
-------------

This patch series adds support for fsverity via digest and signature
(fsverity_signature and fsverity_digest), dm-verity by digest and
signature (dmverity_signature and dmverity_roothash), and trust for
the initramfs (boot_verified).

Please see the documentation patch for more information about the
integrations available.

Testing:
--------

KUnit Tests are available. Recommended kunitconfig:

CONFIG_KUNIT=y
CONFIG_SECURITY=y
CONFIG_SECURITYFS=y
CONFIG_PKCS7_MESSAGE_PARSER=y
CONFIG_SYSTEM_DATA_VERIFICATION=y
CONFIG_FS_VERITY=y
CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y
CONFIG_BLOCK=y
CONFIG_MD=y
CONFIG_BLK_DEV_DM=y
CONFIG_DM_VERITY=y
CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y
CONFIG_NET=y
CONFIG_AUDIT=y
CONFIG_AUDITSYSCALL=y

CONFIG_SECURITY_IPE=y
CONFIG_IPE_PROP_DM_VERITY=y
CONFIG_IPE_PROP_FS_VERITY=y
CONFIG_SECURITY_IPE_KUNIT_TEST=y

Simply run:

make ARCH=um mrproper
./tools/testing/kunit/kunit.py run --kunitconfig <path/to/config>

And the tests will execute and report the result. For more indepth testing,
it will require you to create and mount a dm-verity volume or fs-verity
enabled file.

Documentation:
--------------

There is both documentation available on github at
https://microsoft.github.io/ipe, and Documentation in this patch series,
to be added in-tree.

Known Gaps:
-----------

IPE has two known gaps:

1. IPE cannot verify the integrity of anonymous executable memory, such as
the trampolines created by gcc closures and libffi (<3.4.2), or JIT'd code.
Unfortunately, as this is dynamically generated code, there is no way
for IPE to ensure the integrity of this code to form a trust basis. In all
cases, the return result for these operations will be whatever the admin
configures the DEFAULT action for "EXECUTE".

2. IPE cannot verify the integrity of interpreted languages' programs when
these scripts invoked via ``<interpreter> <file>``. This is because the
way interpreters execute these files, the scripts themselves are not
evaluated as executable code through one of IPE's hooks. Interpreters
can be enlightened to the usage of IPE by trying to mmap a file into
executable memory (+X), after opening the file and responding to the
error code appropriately. This also applies to included files, or high
value files, such as configuration files of critical system components.

Appendix:
---------

A. IPE Github Repository: https://github.com/microsoft/ipe
B. IPE Users' Guide: Documentation/admin-guide/LSM/ipe.rst

References:
-----------

1: https://lore.kernel.org/bpf/[email protected]/

FAQ:
----

Q: What is the difference between IMA and IPE?

A: See the documentation patch for more on this topic.

Previous Postings
-----------------

v1: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v5: https://lore.kernel.org/all/[email protected]/
v6: https://lore.kernel.org/all/[email protected]/
v7: https://lore.kernel.org/all/1634151995-16266-1-git-send-email-deven.desai@linux.microsoft.com/
v8: https://lore.kernel.org/all/1654714889-26728-1-git-send-email-deven.desai@linux.microsoft.com/
v9: https://lore.kernel.org/lkml/[email protected]/

Changelog:
----------

v2:
Split the second patch of the previous series into two.
Minor corrections in the cover-letter and documentation
comments regarding CAP_MAC_ADMIN checks in IPE.

v3:
Address various comments by Jann Horn. Highlights:
Switch various audit allocators to GFP_KERNEL.
Utilize rcu_access_pointer() in various locations.
Strip out the caching system for properties
Strip comments from headers
Move functions around in patches
Remove kernel command line parameters
Reconcile the race condition on the delete node for policy by
expanding the policy critical section.

Address a few comments by Jonathan Corbet around the documentation
pages for IPE.

Fix an issue with the initialization of IPE policy with a "-0"
version, caused by not initializing the hlist entries before
freeing.

v4:
Address a concern around IPE's behavior with unknown syntax.
Specifically, make any unknown syntax a fatal error instead of a
warning, as suggested by Mickaël Salaün.
Introduce a new securityfs node, $securityfs/ipe/property_config,
which provides a listing of what properties are enabled by the
kernel and their versions. This allows usermode to predict what
policies should be allowed.
Strip some comments from c files that I missed.
Clarify some documentation comments around 'boot_verified'.
While this currently does not functionally change the property
itself, the distinction is important when IPE can enforce verified
reads. Additionally, 'KERNEL_READ' was omitted from the documentation.
This has been corrected.
Change SecurityFS and SHA1 to a reverse dependency.
Update the cover-letter with the updated behavior of unknown syntax.
Remove all sysctls, making an equivalent function in securityfs.
Rework the active/delete mechanism to be a node under the policy in
$securityfs/ipe/policies.
The kernel command line parameters ipe.enforce and ipe.success_audit
have returned as this functionality is no longer exposed through
sysfs.

v5:
Correct some grammatical errors reported by Randy Dunlap.
Fix some warnings reported by kernel test bot.
Change convention around security_bdev_setsecurity. -ENOSYS
is now expected if an LSM does not implement a particular @name,
as suggested by Casey Schaufler.
Minor string corrections related to the move from sysfs to securityfs
Correct a spelling of an #ifdef for the permissive argument.
Add the kernel parameters re-added to the documentation.
Fix a minor bug where the mode being audited on permissive switch
was the original mode, not the mode being swapped to.
Cleanup doc comments, fix some whitespace alignment issues.

v6:
Change if statement condition in security_bdev_setsecurity to be
more concise, as suggested by Casey Schaufler and Al Viro
Drop the 6th patch in the series, "dm-verity move signature check..."
due to numerous issues, and it ultimately providing no real value.
Fix the patch tree - the previous iteration appears to have been in a
torn state (patches 8+9 were merged). This has since been corrected.

v7:
* Reword cover letter to more accurate convey IPE's purpose
and latest updates.
* Refactor series to:
1. Support a context structure, enabling:
1. Easier Testing via KUNIT
2. A better architecture for future designs
2. Make parser code cleaner
* Move patch 01/12 to [14/16] of the series
* Split up patch 02/12 into four parts:
1. context creation [01/16]
2. audit [07/16]
3. evaluation loop [03/16]
4. access control hooks [05/16]
5. permissive mode [08/16]
* Split up patch 03/12 into two parts:
1. parser [02/16]
2. userspace interface [04/16]
* Reword and refactor patch 04/12 to [09/16]
* Squash patch 05/12, 07/12, 09/12 to [10/16]
* Squash patch 08/12, 10/12 to [11/16]
* Change audit records to MAC region (14XX) from Integrity region (18XX)
* Add FSVerity Support
* Interface changes:
1. "raw" was renamed to "pkcs7" and made read only
2. "raw"'s write functionality (update a policy) moved to "update"
3. introduced "version", "policy_name" nodes.
4. "content" renamed to "policy"
5. The boot policy can now be updated like any other policy.
* Add additional developer-level documentation
* Update admin-guide docs to reflect changes.
* Kunit tests
* Dropped CONFIG_SECURITY_IPE_PERMISSIVE_SWITCH - functionality can
easily come later with a small patch.
* Use partition0 for block_device for dm-verity patch

v8:
* Add changelog information to individual commits
* A large number of changes to the audit patch.
* split fs/ & security/ changes to two separate patches.
* split block/, security/ & drivers/md/ changes to separate patches.
* Add some historical context to what lead to the creation of IPE
in the documentation patch.
* Cover-letter changes suggested by Roberto Sassu.

v9:
* Rewrite IPE parser to use kernel match_table parser.
* Adapt existing IPE properties to the new parser.
* Remove ipe_context, quote policy syntax, kernel_read for simplicity.
* Add new function in the security file system to delete IPE policy.
* Make IPE audit builtin and change several audit formats.
* Make boot_verified property builtin

v10:
* Address various code style/format issues
* Correct the rcu locking for active policy
* Fix memleak bugs in the parser, optimize the parser per upstream feedback
* Adding new audit events for IPE and update audit formats
* Make the dmverity property auto selected
* Adding more context in the commit messages

Deven Bowers (14):
security: add ipe lsm
ipe: add policy parser
ipe: add evaluation loop
ipe: add LSM hooks on execution and kernel read
ipe: introduce 'boot_verified' as a trust provider
ipe: add userspace interface
uapi|audit|ipe: add ipe auditing support
ipe: add permissive toggle
block|security: add LSM blob to block_device
dm-verity: consume root hash digest and signature data via LSM hook
ipe: add support for dm-verity as a trust provider
scripts: add boot policy generation program
ipe: kunit test for parser
documentation: add ipe documentation

Fan Wu (3):
security: add new securityfs delete function
fsverity: consume builtin signature via LSM hook
ipe: enable support for fs-verity as a trust provider

Documentation/admin-guide/LSM/index.rst | 1 +
Documentation/admin-guide/LSM/ipe.rst | 752 ++++++++++++++++++
.../admin-guide/kernel-parameters.txt | 12 +
Documentation/security/index.rst | 1 +
Documentation/security/ipe.rst | 420 ++++++++++
MAINTAINERS | 10 +
block/bdev.c | 7 +
drivers/md/dm-verity-target.c | 25 +-
drivers/md/dm-verity-verify-sig.c | 16 +-
drivers/md/dm-verity-verify-sig.h | 10 +-
fs/verity/fsverity_private.h | 2 +-
fs/verity/open.c | 26 +-
include/linux/blk_types.h | 3 +
include/linux/dm-verity.h | 19 +
include/linux/fsverity.h | 2 +
include/linux/lsm_hook_defs.h | 5 +
include/linux/lsm_hooks.h | 1 +
include/linux/security.h | 23 +
include/uapi/linux/audit.h | 3 +
scripts/Makefile | 1 +
scripts/ipe/Makefile | 2 +
scripts/ipe/polgen/.gitignore | 1 +
scripts/ipe/polgen/Makefile | 6 +
scripts/ipe/polgen/polgen.c | 145 ++++
security/Kconfig | 11 +-
security/Makefile | 1 +
security/inode.c | 25 +
security/ipe/.gitignore | 1 +
security/ipe/Kconfig | 75 ++
security/ipe/Makefile | 31 +
security/ipe/audit.c | 267 +++++++
security/ipe/audit.h | 19 +
security/ipe/digest.c | 142 ++++
security/ipe/digest.h | 26 +
security/ipe/eval.c | 416 ++++++++++
security/ipe/eval.h | 60 ++
security/ipe/fs.c | 249 ++++++
security/ipe/fs.h | 16 +
security/ipe/hooks.c | 275 +++++++
security/ipe/hooks.h | 42 +
security/ipe/ipe.c | 92 +++
security/ipe/ipe.h | 25 +
security/ipe/policy.c | 213 +++++
security/ipe/policy.h | 100 +++
security/ipe/policy_fs.c | 481 +++++++++++
security/ipe/policy_parser.c | 552 +++++++++++++
security/ipe/policy_parser.h | 11 +
security/ipe/policy_tests.c | 294 +++++++
security/security.c | 99 +++
49 files changed, 5000 insertions(+), 16 deletions(-)
create mode 100644 Documentation/admin-guide/LSM/ipe.rst
create mode 100644 Documentation/security/ipe.rst
create mode 100644 include/linux/dm-verity.h
create mode 100644 scripts/ipe/Makefile
create mode 100644 scripts/ipe/polgen/.gitignore
create mode 100644 scripts/ipe/polgen/Makefile
create mode 100644 scripts/ipe/polgen/polgen.c
create mode 100644 security/ipe/.gitignore
create mode 100644 security/ipe/Kconfig
create mode 100644 security/ipe/Makefile
create mode 100644 security/ipe/audit.c
create mode 100644 security/ipe/audit.h
create mode 100644 security/ipe/digest.c
create mode 100644 security/ipe/digest.h
create mode 100644 security/ipe/eval.c
create mode 100644 security/ipe/eval.h
create mode 100644 security/ipe/fs.c
create mode 100644 security/ipe/fs.h
create mode 100644 security/ipe/hooks.c
create mode 100644 security/ipe/hooks.h
create mode 100644 security/ipe/ipe.c
create mode 100644 security/ipe/ipe.h
create mode 100644 security/ipe/policy.c
create mode 100644 security/ipe/policy.h
create mode 100644 security/ipe/policy_fs.c
create mode 100644 security/ipe/policy_parser.c
create mode 100644 security/ipe/policy_parser.h
create mode 100644 security/ipe/policy_tests.c

--
2.25.1



2023-06-28 21:16:21

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

From: Deven Bowers <[email protected]>

dm-verity provides a strong guarantee of a block device's integrity. As
a generic way to check the integrity of a block device, it provides
those integrity guarantees to its higher layers, including the filesystem
level.

An LSM that control access to a resource on the system based on the
available integrity claims can use this transitive property of
dm-verity, by querying the underlying block_device of a particular
file.

The digest and signature information need to be stored in the block
device to fulfill the next requirement of authorization via LSM policy.
This will enable the LSM to perform revocation of devices that are still
mounted, prohibiting execution of files that are no longer authorized
by the LSM in question.

This patch added two security hook calls in dm-verity to save the
dm-verity roothash and the roothash signature to LSM blobs.

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>
---
v2:
+ No Changes

v3:
+ No changes

v4:
+ No changes

v5:
+ No changes

v6:
+ Fix an improper cleanup that can result in
a leak

v7:
+ Squash patch 08/12, 10/12 to [11/16]
+ Use part0 for block_device, to retrieve the block_device, when
calling security_bdev_setsecurity

v8:
+ Undo squash of 08/12, 10/12 - separating drivers/md/ from
security/ & block/
+ Use common-audit function for dmverity_signature.
+ Change implementation for storing the dm-verity digest to use the
newly introduced dm_verity_digest structure introduced in patch
14/20.
+ Create new structure, dm_verity_digest, containing digest algorithm,
size, and digest itself to pass to the LSM layer. V7 was missing the
algorithm.
+ Create an associated public header containing this new structure and
the key values for the LSM hook, specific to dm-verity.
+ Additional information added to commit, discussing the layering of
the changes and how the information passed will be used.

v9:
+ No changes

v10:
+ No changes
---
drivers/md/dm-verity-target.c | 25 +++++++++++++++++++++++--
drivers/md/dm-verity-verify-sig.c | 16 +++++++++++++---
drivers/md/dm-verity-verify-sig.h | 10 ++++++----
include/linux/dm-verity.h | 19 +++++++++++++++++++
4 files changed, 61 insertions(+), 9 deletions(-)
create mode 100644 include/linux/dm-verity.h

diff --git a/drivers/md/dm-verity-target.c b/drivers/md/dm-verity-target.c
index 26adcfea0302..54d46b2f2723 100644
--- a/drivers/md/dm-verity-target.c
+++ b/drivers/md/dm-verity-target.c
@@ -13,6 +13,7 @@
* access behavior.
*/

+#include "dm-core.h"
#include "dm-verity.h"
#include "dm-verity-fec.h"
#include "dm-verity-verify-sig.h"
@@ -22,6 +23,9 @@
#include <linux/scatterlist.h>
#include <linux/string.h>
#include <linux/jump_label.h>
+#include <linux/security.h>
+#include <linux/dm-verity.h>
+#include <crypto/hash_info.h>

#define DM_MSG_PREFIX "verity"

@@ -1183,6 +1187,8 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
sector_t hash_position;
char dummy;
char *root_hash_digest_to_validate;
+ struct block_device *bdev;
+ struct dm_verity_digest root_digest;

v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
if (!v) {
@@ -1225,6 +1231,13 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
}
v->version = num;

+ bdev = dm_table_get_md(ti->table)->disk->part0;
+ if (!bdev) {
+ ti->error = "Mapped device lookup failed";
+ r = -ENOMEM;
+ goto bad;
+ }
+
r = dm_get_device(ti, argv[1], BLK_OPEN_READ, &v->data_dev);
if (r) {
ti->error = "Data device lookup failed";
@@ -1357,7 +1370,7 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
}

/* Root hash signature is a optional parameter*/
- r = verity_verify_root_hash(root_hash_digest_to_validate,
+ r = verity_verify_root_hash(bdev, root_hash_digest_to_validate,
strlen(root_hash_digest_to_validate),
verify_args.sig,
verify_args.sig_size);
@@ -1440,6 +1453,15 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
ti->per_io_data_size = roundup(ti->per_io_data_size,
__alignof__(struct dm_verity_io));

+ root_digest.digest = v->root_digest;
+ root_digest.digest_len = v->digest_size;
+ root_digest.algo = v->alg_name;
+
+ r = security_bdev_setsecurity(bdev, DM_VERITY_ROOTHASH_SEC_NAME, &root_digest,
+ sizeof(root_digest));
+ if (r)
+ goto bad;
+
verity_verify_sig_opts_cleanup(&verify_args);

dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
@@ -1447,7 +1469,6 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
return 0;

bad:
-
verity_verify_sig_opts_cleanup(&verify_args);
dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
verity_dtr(ti);
diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
index 4836508ea50c..33165dd7470f 100644
--- a/drivers/md/dm-verity-verify-sig.c
+++ b/drivers/md/dm-verity-verify-sig.c
@@ -9,6 +9,9 @@
#include <linux/verification.h>
#include <keys/user-type.h>
#include <linux/module.h>
+#include <linux/security.h>
+#include <linux/dm-verity.h>
+#include "dm-core.h"
#include "dm-verity.h"
#include "dm-verity-verify-sig.h"

@@ -97,14 +100,17 @@ int verity_verify_sig_parse_opt_args(struct dm_arg_set *as,
* verify_verify_roothash - Verify the root hash of the verity hash device
* using builtin trusted keys.
*
+ * @bdev: block_device representing the device-mapper created block device.
+ * Used by the security hook, to set information about the block_device.
* @root_hash: For verity, the roothash/data to be verified.
* @root_hash_len: Size of the roothash/data to be verified.
* @sig_data: The trusted signature that verifies the roothash/data.
* @sig_len: Size of the signature.
*
*/
-int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
- const void *sig_data, size_t sig_len)
+int verity_verify_root_hash(struct block_device *bdev, const void *root_hash,
+ size_t root_hash_len, const void *sig_data,
+ size_t sig_len)
{
int ret;

@@ -126,8 +132,12 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
NULL,
#endif
VERIFYING_UNSPECIFIED_SIGNATURE, NULL, NULL);
+ if (ret)
+ return ret;

- return ret;
+ return security_bdev_setsecurity(bdev,
+ DM_VERITY_SIGNATURE_SEC_NAME,
+ sig_data, sig_len);
}

void verity_verify_sig_opts_cleanup(struct dm_verity_sig_opts *sig_opts)
diff --git a/drivers/md/dm-verity-verify-sig.h b/drivers/md/dm-verity-verify-sig.h
index f36ea92127bf..5c6023fac97b 100644
--- a/drivers/md/dm-verity-verify-sig.h
+++ b/drivers/md/dm-verity-verify-sig.h
@@ -20,8 +20,9 @@ struct dm_verity_sig_opts {

#define DM_VERITY_ROOT_HASH_VERIFICATION_OPTS 2

-int verity_verify_root_hash(const void *data, size_t data_len,
- const void *sig_data, size_t sig_len);
+int verity_verify_root_hash(struct block_device *bdev, const void *data,
+ size_t data_len, const void *sig_data,
+ size_t sig_len);
bool verity_verify_is_sig_opt_arg(const char *arg_name);

int verity_verify_sig_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v,
@@ -34,8 +35,9 @@ void verity_verify_sig_opts_cleanup(struct dm_verity_sig_opts *sig_opts);

#define DM_VERITY_ROOT_HASH_VERIFICATION_OPTS 0

-static inline int verity_verify_root_hash(const void *data, size_t data_len,
- const void *sig_data, size_t sig_len)
+int verity_verify_root_hash(struct block_device *bdev, const void *data,
+ size_t data_len, const void *sig_data,
+ size_t sig_len)
{
return 0;
}
diff --git a/include/linux/dm-verity.h b/include/linux/dm-verity.h
new file mode 100644
index 000000000000..bb0413d55d72
--- /dev/null
+++ b/include/linux/dm-verity.h
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef _LINUX_DM_VERITY_H
+#define _LINUX_DM_VERITY_H
+
+#include <linux/types.h>
+#include <crypto/hash_info.h>
+#include <linux/device-mapper.h>
+
+struct dm_verity_digest {
+ const char *algo;
+ const u8 *digest;
+ size_t digest_len;
+};
+
+#define DM_VERITY_SIGNATURE_SEC_NAME DM_NAME ".verity-signature"
+#define DM_VERITY_ROOTHASH_SEC_NAME DM_NAME ".verity-roothash"
+
+#endif /* _LINUX_DM_VERITY_H */
--
2.25.1


2023-06-28 21:16:26

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 02/17] ipe: add policy parser

From: Deven Bowers <[email protected]>

IPE's interpretation of the what the user trusts is accomplished through
its policy. IPE's design is to not provide support for a single trust
provider, but to support multiple providers to enable the end-user to
choose the best one to seek their needs.

This requires the policy to be rather flexible and modular so that
integrity providers, like fs-verity, dm-verity, dm-integrity, or
some other system, can plug into the policy with minimal code changes.

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>

---
v2:
+ Split evaluation loop, access control hooks,
and evaluation loop from policy parser and userspace
interface to pass mailing list character limit

v3:
+ Move policy load and activation audit event to 03/12
+ Fix a potential panic when a policy failed to load.
+ use pr_warn for a failure to parse instead of an
audit record
+ Remove comments from headers
+ Add lockdep assertions to ipe_update_active_policy and
ipe_activate_policy
+ Fix up warnings with checkpatch --strict
+ Use file_ns_capable for CAP_MAC_ADMIN for securityfs
nodes.
+ Use memdup_user instead of kzalloc+simple_write_to_buffer.
+ Remove strict_parse command line parameter, as it is added
by the sysctl command line.
+ Prefix extern variables with ipe_

v4:
+ Remove securityfs to reverse-dependency
+ Add SHA1 reverse dependency.
+ Add versioning scheme for IPE properties, and associated
interface to query the versioning scheme.
+ Cause a parser to always return an error on unknown syntax.
+ Remove strict_parse option
+ Change active_policy interface from sysctl, to securityfs,
and change scheme.

v5:
+ Cause an error if a default action is not defined for each
operation.
+ Minor function renames

v6:
+ No changes

v7:
+ Further split parser and userspace interface into two
separate commits, for easier review.
+ Refactor policy parser to make code cleaner via introducing a
more modular design, for easier extension of policy, and
easier review.

v8:
+ remove unnecessary pr_info emission on parser loading
+ add explicit newline to the pr_err emitted when a parser
fails to load.

v9:
+ switch to match table to parse policy
+ remove quote syntax and KERNEL_READ operation

v10:
+ Fix memory leaks in parser
+ Fix typos and change code styles
---
security/ipe/Makefile | 2 +
security/ipe/policy.c | 97 +++++++
security/ipe/policy.h | 83 ++++++
security/ipe/policy_parser.c | 488 +++++++++++++++++++++++++++++++++++
security/ipe/policy_parser.h | 11 +
5 files changed, 681 insertions(+)
create mode 100644 security/ipe/policy.c
create mode 100644 security/ipe/policy.h
create mode 100644 security/ipe/policy_parser.c
create mode 100644 security/ipe/policy_parser.h

diff --git a/security/ipe/Makefile b/security/ipe/Makefile
index 571648579991..16bbe80991f1 100644
--- a/security/ipe/Makefile
+++ b/security/ipe/Makefile
@@ -8,3 +8,5 @@
obj-$(CONFIG_SECURITY_IPE) += \
hooks.o \
ipe.o \
+ policy.o \
+ policy_parser.o \
diff --git a/security/ipe/policy.c b/security/ipe/policy.c
new file mode 100644
index 000000000000..4069ff075093
--- /dev/null
+++ b/security/ipe/policy.c
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include <linux/errno.h>
+#include <linux/verification.h>
+
+#include "ipe.h"
+#include "policy.h"
+#include "policy_parser.h"
+
+/**
+ * ipe_free_policy - Deallocate a given IPE policy.
+ * @p: Supplies the policy to free.
+ *
+ * Safe to call on IS_ERR/NULL.
+ */
+void ipe_free_policy(struct ipe_policy *p)
+{
+ if (IS_ERR_OR_NULL(p))
+ return;
+
+ free_parsed_policy(p->parsed);
+ if (!p->pkcs7)
+ kfree(p->text);
+ kfree(p->pkcs7);
+ kfree(p);
+}
+
+static int set_pkcs7_data(void *ctx, const void *data, size_t len,
+ size_t asn1hdrlen)
+{
+ struct ipe_policy *p = ctx;
+
+ p->text = (const char *)data;
+ p->textlen = len;
+
+ return 0;
+}
+
+/**
+ * ipe_new_policy - Allocate and parse an ipe_policy structure.
+ *
+ * @text: Supplies a pointer to the plain-text policy to parse.
+ * @textlen: Supplies the length of @text.
+ * @pkcs7: Supplies a pointer to a pkcs7-signed IPE policy.
+ * @pkcs7len: Supplies the length of @pkcs7.
+ *
+ * @text/@textlen Should be NULL/0 if @pkcs7/@pkcs7len is set.
+ *
+ * Return:
+ * * !IS_ERR - Success
+ * * -EBADMSG - Policy is invalid
+ * * -ENOMEM - Out of memory
+ */
+struct ipe_policy *ipe_new_policy(const char *text, size_t textlen,
+ const char *pkcs7, size_t pkcs7len)
+{
+ int rc = 0;
+ struct ipe_policy *new = NULL;
+
+ new = kzalloc(sizeof(*new), GFP_KERNEL);
+ if (!new)
+ return ERR_PTR(-ENOMEM);
+
+ if (!text) {
+ new->pkcs7len = pkcs7len;
+ new->pkcs7 = kmemdup(pkcs7, pkcs7len, GFP_KERNEL);
+ if (!new->pkcs7) {
+ rc = -ENOMEM;
+ goto err;
+ }
+
+ rc = verify_pkcs7_signature(NULL, 0, new->pkcs7, pkcs7len, NULL,
+ VERIFYING_UNSPECIFIED_SIGNATURE,
+ set_pkcs7_data, new);
+ if (rc)
+ goto err;
+ } else {
+ new->textlen = textlen;
+ new->text = kstrdup(text, GFP_KERNEL);
+ if (!new->text) {
+ rc = -ENOMEM;
+ goto err;
+ }
+ }
+
+ rc = parse_policy(new);
+ if (rc)
+ goto err;
+
+ return new;
+err:
+ ipe_free_policy(new);
+ return ERR_PTR(rc);
+}
diff --git a/security/ipe/policy.h b/security/ipe/policy.h
new file mode 100644
index 000000000000..113a037f0d71
--- /dev/null
+++ b/security/ipe/policy.h
@@ -0,0 +1,83 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+#ifndef _IPE_POLICY_H
+#define _IPE_POLICY_H
+
+#include <linux/list.h>
+#include <linux/types.h>
+
+enum ipe_op_type {
+ __IPE_OP_EXEC = 0,
+ __IPE_OP_FIRMWARE,
+ __IPE_OP_KERNEL_MODULE,
+ __IPE_OP_KEXEC_IMAGE,
+ __IPE_OP_KEXEC_INITRAMFS,
+ __IPE_OP_IMA_POLICY,
+ __IPE_OP_IMA_X509,
+ __IPE_OP_MAX
+};
+
+#define __IPE_OP_INVALID __IPE_OP_MAX
+
+enum ipe_action_type {
+ __IPE_ACTION_ALLOW = 0,
+ __IPE_ACTION_DENY,
+ __IPE_ACTION_MAX
+};
+
+#define __IPE_ACTION_INVALID __IPE_ACTION_MAX
+
+enum ipe_prop_type {
+ __IPE_PROP_MAX
+};
+
+#define __IPE_PROP_INVALID __IPE_PROP_MAX
+
+struct ipe_prop {
+ struct list_head next;
+ enum ipe_prop_type type;
+ void *value;
+};
+
+struct ipe_rule {
+ enum ipe_op_type op;
+ enum ipe_action_type action;
+ struct list_head props;
+ struct list_head next;
+};
+
+struct ipe_op_table {
+ struct list_head rules;
+ enum ipe_action_type default_action;
+};
+
+struct ipe_parsed_policy {
+ const char *name;
+ struct {
+ u16 major;
+ u16 minor;
+ u16 rev;
+ } version;
+
+ enum ipe_action_type global_default_action;
+
+ struct ipe_op_table rules[__IPE_OP_MAX];
+};
+
+struct ipe_policy {
+ const char *pkcs7;
+ size_t pkcs7len;
+
+ const char *text;
+ size_t textlen;
+
+ struct ipe_parsed_policy *parsed;
+};
+
+struct ipe_policy *ipe_new_policy(const char *text, size_t textlen,
+ const char *pkcs7, size_t pkcs7len);
+void ipe_free_policy(struct ipe_policy *pol);
+
+#endif /* _IPE_POLICY_H */
diff --git a/security/ipe/policy_parser.c b/security/ipe/policy_parser.c
new file mode 100644
index 000000000000..27e5767480b0
--- /dev/null
+++ b/security/ipe/policy_parser.c
@@ -0,0 +1,488 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include <linux/types.h>
+#include <linux/parser.h>
+
+#include "policy.h"
+#include "policy_parser.h"
+
+#define START_COMMENT '#'
+
+/**
+ * new_parsed_policy - Allocate and initialize a parsed policy.
+ *
+ * Return:
+ * * !IS_ERR - OK
+ * * -ENOMEM - Out of memory
+ */
+static struct ipe_parsed_policy *new_parsed_policy(void)
+{
+ size_t i = 0;
+ struct ipe_parsed_policy *p = NULL;
+ struct ipe_op_table *t = NULL;
+
+ p = kzalloc(sizeof(*p), GFP_KERNEL);
+ if (!p)
+ return ERR_PTR(-ENOMEM);
+
+ p->global_default_action = __IPE_ACTION_INVALID;
+
+ for (i = 0; i < ARRAY_SIZE(p->rules); ++i) {
+ t = &p->rules[i];
+
+ t->default_action = __IPE_ACTION_INVALID;
+ INIT_LIST_HEAD(&t->rules);
+ }
+
+ return p;
+}
+
+/**
+ * remove_comment - Truncate all chars following START_COMMENT in a string.
+ *
+ * @line: Supplies a poilcy line string for preprocessing.
+ */
+static void remove_comment(char *line)
+{
+ line = strchr(line, START_COMMENT);
+
+ if (line)
+ *line = '\0';
+}
+
+/**
+ * remove_trailing_spaces - Truncate all trailing spaces in a string.
+ *
+ * @line: Supplies a poilcy line string for preprocessing.
+ *
+ * Return: The length of truncated string.
+ */
+static size_t remove_trailing_spaces(char *line)
+{
+ size_t i = 0;
+
+ for (i = strlen(line); i > 0 && (line[i - 1] == ' ' || line[i - 1] == '\t'); --i)
+ ;
+
+ line[i] = '\0';
+
+ return i;
+}
+
+/**
+ * parse_version - Parse policy version.
+ * @ver: Supplies a version string to be parsed.
+ * @p: Supplies the partial parsed policy.
+ *
+ * Return:
+ * * 0 - OK
+ * * !0 - Standard errno
+ */
+static int parse_version(char *ver, struct ipe_parsed_policy *p)
+{
+ int rc = 0;
+ size_t sep_count = 0;
+ char *token;
+ u16 *const cv[] = { &p->version.major, &p->version.minor, &p->version.rev };
+
+ while ((token = strsep(&ver, ".")) != NULL) {
+ /* prevent overflow */
+ if (sep_count >= ARRAY_SIZE(cv))
+ return -EBADMSG;
+
+ rc = kstrtou16(token, 10, cv[sep_count]);
+ if (rc)
+ return rc;
+
+ ++sep_count;
+ }
+
+ /* prevent underflow */
+ if (sep_count != ARRAY_SIZE(cv))
+ rc = -EBADMSG;
+
+ return rc;
+}
+
+enum header_opt {
+ __IPE_HEADER_POLICY_NAME = 0,
+ __IPE_HEADER_POLICY_VERSION,
+ __IPE_HEADER_MAX
+};
+
+static const match_table_t header_tokens = {
+ {__IPE_HEADER_POLICY_NAME, "policy_name=%s"},
+ {__IPE_HEADER_POLICY_VERSION, "policy_version=%s"},
+ {__IPE_HEADER_MAX, NULL}
+};
+
+/**
+ * parse_header - Parse policy header information.
+ * @line: Supplies header line to be parsed.
+ * @p: Supplies the partial parsed policy.
+ *
+ * Return:
+ * * 0 - OK
+ * * !0 - Standard errno
+ */
+static int parse_header(char *line, struct ipe_parsed_policy *p)
+{
+ int rc = 0;
+ char *t, *ver = NULL;
+ substring_t args[MAX_OPT_ARGS];
+ size_t idx = 0;
+
+ while ((t = strsep(&line, " \t")) != NULL) {
+ int token;
+
+ if (*t == '\0')
+ continue;
+ if (idx >= __IPE_HEADER_MAX) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+ token = match_token(t, header_tokens, args);
+ if (token != idx) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+ switch (token) {
+ case __IPE_HEADER_POLICY_NAME:
+ p->name = match_strdup(&args[0]);
+ if (!p->name)
+ rc = -ENOMEM;
+ break;
+ case __IPE_HEADER_POLICY_VERSION:
+ ver = match_strdup(&args[0]);
+ if (!ver) {
+ rc = -ENOMEM;
+ break;
+ }
+ rc = parse_version(ver, p);
+ break;
+ default:
+ rc = -EBADMSG;
+ }
+ if (rc)
+ goto err;
+ ++idx;
+ }
+
+ if (idx != __IPE_HEADER_MAX) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+out:
+ kfree(ver);
+ return rc;
+err:
+ kfree(p->name);
+ p->name = NULL;
+ goto out;
+}
+
+/**
+ * token_default - Determine if the given token is "DEFAULT".
+ * @token: Supplies the token string to be compared.
+ *
+ * Return:
+ * * 0 - The token is not "DEFAULT"
+ * * !0 - The token is "DEFAULT"
+ */
+static bool token_default(char *token)
+{
+ return !strcmp(token, "DEFAULT");
+}
+
+/**
+ * free_rule - Free the supplied ipe_rule struct.
+ * @r: Supplies the ipe_rule struct to be freed.
+ *
+ * Free a ipe_rule struct @r. Note @r must be removed from any lists before
+ * calling this function.
+ */
+static void free_rule(struct ipe_rule *r)
+{
+ struct ipe_prop *p, *t;
+
+ if (IS_ERR_OR_NULL(r))
+ return;
+
+ list_for_each_entry_safe(p, t, &r->props, next) {
+ list_del(&p->next);
+ kfree(p);
+ }
+
+ kfree(r);
+}
+
+static const match_table_t operation_tokens = {
+ {__IPE_OP_EXEC, "op=EXECUTE"},
+ {__IPE_OP_FIRMWARE, "op=FIRMWARE"},
+ {__IPE_OP_KERNEL_MODULE, "op=KMODULE"},
+ {__IPE_OP_KEXEC_IMAGE, "op=KEXEC_IMAGE"},
+ {__IPE_OP_KEXEC_INITRAMFS, "op=KEXEC_INITRAMFS"},
+ {__IPE_OP_IMA_POLICY, "op=IMA_POLICY"},
+ {__IPE_OP_IMA_X509, "op=IMA_X509_CERT"},
+ {__IPE_OP_INVALID, NULL}
+};
+
+/**
+ * parse_operation - Parse the operation type given a token string.
+ * @t: Supplies the token string to be parsed.
+ *
+ * Return: The parsed operation type.
+ */
+static enum ipe_op_type parse_operation(char *t)
+{
+ substring_t args[MAX_OPT_ARGS];
+
+ return match_token(t, operation_tokens, args);
+}
+
+static const match_table_t action_tokens = {
+ {__IPE_ACTION_ALLOW, "action=ALLOW"},
+ {__IPE_ACTION_DENY, "action=DENY"},
+ {__IPE_ACTION_INVALID, NULL}
+};
+
+/**
+ * parse_action - Parse the action type given a token string.
+ * @t: Supplies the token string to be parsed.
+ *
+ * Return: The parsed action type.
+ */
+static enum ipe_action_type parse_action(char *t)
+{
+ substring_t args[MAX_OPT_ARGS];
+
+ return match_token(t, action_tokens, args);
+}
+
+/**
+ * parse_property - Parse the property type given a token string.
+ * @t: Supplies the token string to be parsed.
+ * @r: Supplies the ipe_rule the parsed property will be associated with.
+ *
+ * Return:
+ * * !IS_ERR - OK
+ * * -ENOMEM - Out of memory
+ * * -EBADMSG - The supplied token cannot be parsed
+ */
+static int parse_property(char *t, struct ipe_rule *r)
+{
+ return -EBADMSG;
+}
+
+/**
+ * parse_rule - parse a policy rule line.
+ * @line: Supplies rule line to be parsed.
+ * @p: Supplies the partial parsed policy.
+ *
+ * Return:
+ * * !IS_ERR - OK
+ * * -ENOMEM - Out of memory
+ * * -EBADMSG - Policy syntax error
+ */
+static int parse_rule(char *line, struct ipe_parsed_policy *p)
+{
+ int rc = 0;
+ bool first_token = true, is_default_rule = false;
+ bool op_parsed = false;
+ enum ipe_op_type op = __IPE_OP_INVALID;
+ enum ipe_action_type action = __IPE_ACTION_INVALID;
+ struct ipe_rule *r = NULL;
+ char *t;
+
+ r = kzalloc(sizeof(*r), GFP_KERNEL);
+ if (!r)
+ return -ENOMEM;
+
+ INIT_LIST_HEAD(&r->next);
+ INIT_LIST_HEAD(&r->props);
+
+ while (t = strsep(&line, " \t"), line) {
+ if (*t == '\0')
+ continue;
+ if (first_token && token_default(t)) {
+ is_default_rule = true;
+ } else {
+ if (!op_parsed) {
+ op = parse_operation(t);
+ if (op == __IPE_OP_INVALID)
+ rc = -EBADMSG;
+ else
+ op_parsed = true;
+ } else {
+ rc = parse_property(t, r);
+ }
+ }
+
+ if (rc)
+ goto err;
+ first_token = false;
+ }
+
+ action = parse_action(t);
+ if (action == __IPE_ACTION_INVALID) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+ if (is_default_rule) {
+ if (!list_empty(&r->props)) {
+ rc = -EBADMSG;
+ } else if (op == __IPE_OP_INVALID) {
+ if (p->global_default_action != __IPE_ACTION_INVALID)
+ rc = -EBADMSG;
+ else
+ p->global_default_action = action;
+ } else {
+ if (p->rules[op].default_action != __IPE_ACTION_INVALID)
+ rc = -EBADMSG;
+ else
+ p->rules[op].default_action = action;
+ }
+ } else if (op != __IPE_OP_INVALID && action != __IPE_ACTION_INVALID) {
+ r->op = op;
+ r->action = action;
+ } else {
+ rc = -EBADMSG;
+ }
+
+ if (rc)
+ goto err;
+ if (!is_default_rule)
+ list_add_tail(&r->next, &p->rules[op].rules);
+ else
+ free_rule(r);
+
+out:
+ return rc;
+err:
+ free_rule(r);
+ goto out;
+}
+
+/**
+ * free_parsed_policy - free a parsed policy structure.
+ * @p: Supplies the parsed policy.
+ */
+void free_parsed_policy(struct ipe_parsed_policy *p)
+{
+ size_t i = 0;
+ struct ipe_rule *pp, *t;
+
+ if (IS_ERR_OR_NULL(p))
+ return;
+
+ for (i = 0; i < ARRAY_SIZE(p->rules); ++i)
+ list_for_each_entry_safe(pp, t, &p->rules[i].rules, next) {
+ list_del(&pp->next);
+ free_rule(pp);
+ }
+
+ kfree(p->name);
+ kfree(p);
+}
+
+/**
+ * validate_policy - validate a parsed policy.
+ * @p: Supplies the fully parsed policy.
+ *
+ * Given a policy structure that was just parsed, validate that all
+ * necessary fields are present, initialized correctly.
+ *
+ * A parsed policy can be in an invalid state for use (a default was
+ * undefined) by just parsing the policy.
+ *
+ * Return:
+ * * 0 - OK
+ * * -EBADMSG - Policy is invalid
+ */
+static int validate_policy(const struct ipe_parsed_policy *p)
+{
+ int i = 0;
+
+ if (p->global_default_action != __IPE_ACTION_INVALID)
+ return 0;
+
+ for (i = 0; i < ARRAY_SIZE(p->rules); ++i) {
+ if (p->rules[i].default_action == __IPE_ACTION_INVALID)
+ return -EBADMSG;
+ }
+
+ return 0;
+}
+
+/**
+ * parse_policy - Given a string, parse the string into an IPE policy.
+ * @p: partially filled ipe_policy structure to populate with the result.
+ * it must have text and textlen set.
+ *
+ * Return:
+ * * 0 - OK
+ * * -EBADMSG - Policy is invalid
+ * * -ENOMEM - Out of Memory
+ */
+int parse_policy(struct ipe_policy *p)
+{
+ int rc = 0;
+ size_t len;
+ char *policy = NULL, *dup = NULL;
+ char *line = NULL;
+ bool header_parsed = false;
+ struct ipe_parsed_policy *pp = NULL;
+
+ if (!p->textlen)
+ return -EBADMSG;
+
+ policy = kmemdup_nul(p->text, p->textlen, GFP_KERNEL);
+ if (!policy)
+ return -ENOMEM;
+ dup = policy;
+
+ pp = new_parsed_policy();
+ if (IS_ERR(pp)) {
+ rc = PTR_ERR(pp);
+ goto out;
+ }
+
+ while ((line = strsep(&policy, "\n\r")) != NULL) {
+ remove_comment(line);
+ len = remove_trailing_spaces(line);
+ if (!len)
+ continue;
+
+ if (!header_parsed) {
+ rc = parse_header(line, pp);
+ if (rc)
+ goto err;
+ header_parsed = true;
+ } else {
+ rc = parse_rule(line, pp);
+ if (rc)
+ goto err;
+ }
+ }
+
+ if (!header_parsed || validate_policy(pp)) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+ p->parsed = pp;
+
+out:
+ kfree(dup);
+ return rc;
+err:
+ free_parsed_policy(pp);
+ goto out;
+}
diff --git a/security/ipe/policy_parser.h b/security/ipe/policy_parser.h
new file mode 100644
index 000000000000..2b744103d06a
--- /dev/null
+++ b/security/ipe/policy_parser.h
@@ -0,0 +1,11 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+#ifndef _IPE_POLICY_PARSER_H
+#define _IPE_POLICY_PARSER_H
+
+int parse_policy(struct ipe_policy *p);
+void free_parsed_policy(struct ipe_parsed_policy *p);
+
+#endif /* _IPE_POLICY_PARSER_H */
--
2.25.1


2023-06-28 21:16:27

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 15/17] scripts: add boot policy generation program

From: Deven Bowers <[email protected]>

Enables an IPE policy to be enforced from kernel start, enabling access
control based on trust from kernel startup. This is accomplished by
transforming an IPE policy indicated by CONFIG_IPE_BOOT_POLICY into a
c-string literal that is parsed at kernel startup as an unsigned policy.

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>
---
v2:
+ No Changes

v3:
+ No Changes

v4:
+ No Changes

v5:
+ No Changes

v6:
+ No Changes

v7:
+ Move from 01/11 to 14/16
+ Don't return errno directly.
+ Make output of script more user-friendly
+ Add escaping for tab and '?'
+ Mark argv pointer const
+ Invert return code check in the boot policy parsing code path.

v8:
+ No significant changes.

v9:
+ no changes

v10:
+ Update the init part code for rcu changes in the eval loop patch
---
MAINTAINERS | 1 +
scripts/Makefile | 1 +
scripts/ipe/Makefile | 2 +
scripts/ipe/polgen/.gitignore | 1 +
scripts/ipe/polgen/Makefile | 6 ++
scripts/ipe/polgen/polgen.c | 145 ++++++++++++++++++++++++++++++++++
security/ipe/.gitignore | 1 +
security/ipe/Kconfig | 10 +++
security/ipe/Makefile | 11 +++
security/ipe/fs.c | 8 ++
security/ipe/ipe.c | 17 ++++
11 files changed, 203 insertions(+)
create mode 100644 scripts/ipe/Makefile
create mode 100644 scripts/ipe/polgen/.gitignore
create mode 100644 scripts/ipe/polgen/Makefile
create mode 100644 scripts/ipe/polgen/polgen.c
create mode 100644 security/ipe/.gitignore

diff --git a/MAINTAINERS b/MAINTAINERS
index ad00887d38ea..fb8d6a16f2a6 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -10283,6 +10283,7 @@ M: Fan Wu <[email protected]>
L: [email protected]
S: Supported
T: git git://github.com/microsoft/ipe.git
+F: scripts/ipe/
F: security/ipe/

INTEL 810/815 FRAMEBUFFER DRIVER
diff --git a/scripts/Makefile b/scripts/Makefile
index 32b6ba722728..18baecdada01 100644
--- a/scripts/Makefile
+++ b/scripts/Makefile
@@ -46,6 +46,7 @@ targets += module.lds
subdir-$(CONFIG_GCC_PLUGINS) += gcc-plugins
subdir-$(CONFIG_MODVERSIONS) += genksyms
subdir-$(CONFIG_SECURITY_SELINUX) += selinux
+subdir-$(CONFIG_SECURITY_IPE) += ipe

# Let clean descend into subdirs
subdir- += basic dtc gdb kconfig mod
diff --git a/scripts/ipe/Makefile b/scripts/ipe/Makefile
new file mode 100644
index 000000000000..e87553fbb8d6
--- /dev/null
+++ b/scripts/ipe/Makefile
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+subdir-y := polgen
diff --git a/scripts/ipe/polgen/.gitignore b/scripts/ipe/polgen/.gitignore
new file mode 100644
index 000000000000..80f32f25d200
--- /dev/null
+++ b/scripts/ipe/polgen/.gitignore
@@ -0,0 +1 @@
+polgen
diff --git a/scripts/ipe/polgen/Makefile b/scripts/ipe/polgen/Makefile
new file mode 100644
index 000000000000..066060c22b4a
--- /dev/null
+++ b/scripts/ipe/polgen/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+hostprogs-always-y := polgen
+HOST_EXTRACFLAGS += \
+ -I$(srctree)/include \
+ -I$(srctree)/include/uapi \
+
diff --git a/scripts/ipe/polgen/polgen.c b/scripts/ipe/polgen/polgen.c
new file mode 100644
index 000000000000..40b6fe07f47b
--- /dev/null
+++ b/scripts/ipe/polgen/polgen.c
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <errno.h>
+
+static void usage(const char *const name)
+{
+ printf("Usage: %s OutputFile (PolicyFile)\n", name);
+ exit(EINVAL);
+}
+
+static int policy_to_buffer(const char *pathname, char **buffer, size_t *size)
+{
+ int rc = 0;
+ FILE *fd;
+ char *lbuf;
+ size_t fsize;
+ size_t read;
+
+ fd = fopen(pathname, "r");
+ if (!fd) {
+ rc = errno;
+ goto out;
+ }
+
+ fseek(fd, 0, SEEK_END);
+ fsize = ftell(fd);
+ rewind(fd);
+
+ lbuf = malloc(fsize);
+ if (!lbuf) {
+ rc = ENOMEM;
+ goto out_close;
+ }
+
+ read = fread((void *)lbuf, sizeof(*lbuf), fsize, fd);
+ if (read != fsize) {
+ rc = -1;
+ goto out_free;
+ }
+
+ *buffer = lbuf;
+ *size = fsize;
+ fclose(fd);
+
+ return rc;
+
+out_free:
+ free(lbuf);
+out_close:
+ fclose(fd);
+out:
+ return rc;
+}
+
+static int write_boot_policy(const char *pathname, const char *buf, size_t size)
+{
+ int rc = 0;
+ FILE *fd;
+ size_t i;
+
+ fd = fopen(pathname, "w");
+ if (!fd) {
+ rc = errno;
+ goto err;
+ }
+
+ fprintf(fd, "/* This file is automatically generated.");
+ fprintf(fd, " Do not edit. */\n");
+ fprintf(fd, "#include <linux/stddef.h>\n");
+ fprintf(fd, "\nextern const char *const ipe_boot_policy;\n\n");
+ fprintf(fd, "const char *const ipe_boot_policy =\n");
+
+ if (!buf || size == 0) {
+ fprintf(fd, "\tNULL;\n");
+ fclose(fd);
+ return 0;
+ }
+
+ fprintf(fd, "\t\"");
+
+ for (i = 0; i < size; ++i) {
+ switch (buf[i]) {
+ case '"':
+ fprintf(fd, "\\\"");
+ break;
+ case '\'':
+ fprintf(fd, "'");
+ break;
+ case '\n':
+ fprintf(fd, "\\n\"\n\t\"");
+ break;
+ case '\\':
+ fprintf(fd, "\\\\");
+ break;
+ case '\t':
+ fprintf(fd, "\\t");
+ break;
+ case '\?':
+ fprintf(fd, "\\?");
+ break;
+ default:
+ fprintf(fd, "%c", buf[i]);
+ }
+ }
+ fprintf(fd, "\";\n");
+ fclose(fd);
+
+ return 0;
+
+err:
+ if (fd)
+ fclose(fd);
+ return rc;
+}
+
+int main(int argc, const char *const argv[])
+{
+ int rc = 0;
+ size_t len = 0;
+ char *policy = NULL;
+
+ if (argc < 2)
+ usage(argv[0]);
+
+ if (argc > 2) {
+ rc = policy_to_buffer(argv[2], &policy, &len);
+ if (rc != 0)
+ goto cleanup;
+ }
+
+ rc = write_boot_policy(argv[1], policy, len);
+cleanup:
+ if (policy)
+ free(policy);
+ if (rc != 0)
+ perror("An error occurred during policy conversion: ");
+ return rc;
+}
diff --git a/security/ipe/.gitignore b/security/ipe/.gitignore
new file mode 100644
index 000000000000..eca22ad5ed22
--- /dev/null
+++ b/security/ipe/.gitignore
@@ -0,0 +1 @@
+boot-policy.c
\ No newline at end of file
diff --git a/security/ipe/Kconfig b/security/ipe/Kconfig
index 9dd5c4769d79..a6c5d48dd0a3 100644
--- a/security/ipe/Kconfig
+++ b/security/ipe/Kconfig
@@ -18,6 +18,16 @@ menuconfig SECURITY_IPE
If unsure, answer N.

if SECURITY_IPE
+config IPE_BOOT_POLICY
+ string "Integrity policy to apply on system startup"
+ help
+ This option specifies a filepath to a IPE policy that is compiled
+ into the kernel. This policy will be enforced until a policy update
+ is deployed via the $securityfs/ipe/policies/$policy_name/active
+ interface.
+
+ If unsure, leave blank.
+
menu "IPE Trust Providers"

config IPE_PROP_DM_VERITY
diff --git a/security/ipe/Makefile b/security/ipe/Makefile
index ec7f69c34735..b7f0118215da 100644
--- a/security/ipe/Makefile
+++ b/security/ipe/Makefile
@@ -5,7 +5,16 @@
# Makefile for building the IPE module as part of the kernel tree.
#

+quiet_cmd_polgen = IPE_POL $(2)
+ cmd_polgen = scripts/ipe/polgen/polgen security/ipe/boot-policy.c $(2)
+
+targets += boot-policy.c
+
+$(obj)/boot-policy.c: scripts/ipe/polgen/polgen $(CONFIG_IPE_BOOT_POLICY) FORCE
+ $(call if_changed,polgen,$(CONFIG_IPE_BOOT_POLICY))
+
obj-$(CONFIG_SECURITY_IPE) += \
+ boot-policy.o \
digest.o \
eval.o \
fs.o \
@@ -15,3 +24,5 @@ obj-$(CONFIG_SECURITY_IPE) += \
policy_fs.o \
policy_parser.o \
audit.o \
+
+clean-files := boot-policy.c \
diff --git a/security/ipe/fs.c b/security/ipe/fs.c
index 1761d39e4d04..31d30a58a662 100644
--- a/security/ipe/fs.c
+++ b/security/ipe/fs.c
@@ -192,6 +192,7 @@ static const struct file_operations enforce_fops = {
static int __init ipe_init_securityfs(void)
{
int rc = 0;
+ struct ipe_policy *ap;

if (!ipe_enabled)
return -EOPNOTSUPP;
@@ -222,6 +223,13 @@ static int __init ipe_init_securityfs(void)
goto err;
}

+ ap = rcu_access_pointer(ipe_active_policy);
+ if (ap) {
+ rc = ipe_new_policyfs_node(ap);
+ if (rc)
+ goto err;
+ }
+
np = securityfs_create_file("new_policy", 0200, root, NULL, &np_fops);
if (IS_ERR(np)) {
rc = PTR_ERR(np);
diff --git a/security/ipe/ipe.c b/security/ipe/ipe.c
index 1d3d66e1623b..8110fa5ff203 100644
--- a/security/ipe/ipe.c
+++ b/security/ipe/ipe.c
@@ -7,6 +7,7 @@
#include "hooks.h"
#include "eval.h"

+extern const char *const ipe_boot_policy;
bool ipe_enabled;

static struct lsm_blob_sizes ipe_blobs __ro_after_init = {
@@ -61,11 +62,27 @@ static struct security_hook_list ipe_hooks[] __ro_after_init = {
static int __init ipe_init(void)
{
int rc = 0;
+ struct ipe_policy *p = NULL;

security_add_hooks(ipe_hooks, ARRAY_SIZE(ipe_hooks), "ipe");
ipe_enabled = true;

+ if (ipe_boot_policy) {
+ p = ipe_new_policy(ipe_boot_policy, strlen(ipe_boot_policy),
+ NULL, 0);
+ if (IS_ERR(p)) {
+ rc = PTR_ERR(p);
+ goto err;
+ }
+
+ rcu_assign_pointer(ipe_active_policy, p);
+ }
+
+out:
return rc;
+err:
+ ipe_free_policy(p);
+ goto out;
}

DEFINE_LSM(ipe) = {
--
2.25.1


2023-06-28 21:16:36

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 16/17] ipe: kunit test for parser

From: Deven Bowers <[email protected]>

Add various happy/unhappy unit tests for both IPE's parser.

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>

---
v1-v6:
+ Not present

v7:
Introduced

v8:
+ Remove the kunit tests with respect to the fsverity digest, as these
require significant changes to work with the new method of acquiring
the digest at runtime.

v9:
+ Remove the kunit tests related to ipe_context

v10:
+ No changes
---
security/ipe/Kconfig | 17 +++
security/ipe/Makefile | 3 +
security/ipe/policy_tests.c | 294 ++++++++++++++++++++++++++++++++++++
3 files changed, 314 insertions(+)
create mode 100644 security/ipe/policy_tests.c

diff --git a/security/ipe/Kconfig b/security/ipe/Kconfig
index a6c5d48dd0a3..ac04a9974297 100644
--- a/security/ipe/Kconfig
+++ b/security/ipe/Kconfig
@@ -55,4 +55,21 @@ config IPE_PROP_FS_VERITY

endmenu

+config SECURITY_IPE_KUNIT_TEST
+ bool "Build KUnit tests for IPE" if !KUNIT_ALL_TESTS
+ depends on KUNIT=y
+ default KUNIT_ALL_TESTS
+ help
+ This builds the IPE KUnit tests.
+
+ KUnit tests run during boot and output the results to the debug log
+ in TAP format (https://testanything.org/). Only useful for kernel devs
+ running KUnit test harness and are not for inclusion into a
+ production build.
+
+ For more information on KUnit and unit tests in general please refer
+ to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+ If unsure, say N.
+
endif
diff --git a/security/ipe/Makefile b/security/ipe/Makefile
index b7f0118215da..f3845a6a6ece 100644
--- a/security/ipe/Makefile
+++ b/security/ipe/Makefile
@@ -26,3 +26,6 @@ obj-$(CONFIG_SECURITY_IPE) += \
audit.o \

clean-files := boot-policy.c \
+
+obj-$(CONFIG_SECURITY_IPE_KUNIT_TEST) += \
+ policy_tests.o \
diff --git a/security/ipe/policy_tests.c b/security/ipe/policy_tests.c
new file mode 100644
index 000000000000..f076460ee7fc
--- /dev/null
+++ b/security/ipe/policy_tests.c
@@ -0,0 +1,294 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include <linux/slab.h>
+#include <linux/types.h>
+#include <linux/list.h>
+#include <kunit/test.h>
+#include "policy.h"
+struct policy_case {
+ const char *const policy;
+ int errno;
+ const char *const desc;
+};
+
+static const struct policy_case policy_cases[] = {
+ {
+ "policy_name=allowall policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW",
+ 0,
+ "basic",
+ },
+ {
+ "policy_name=trailing_comment policy_version=152.0.0 #This is comment\n"
+ "DEFAULT action=ALLOW",
+ 0,
+ "trailing comment",
+ },
+ {
+ "policy_name=allowallnewline policy_version=0.2.0\n"
+ "DEFAULT action=ALLOW\n"
+ "\n",
+ 0,
+ "trailing newline",
+ },
+ {
+ "policy_name=carriagereturnlinefeed policy_version=0.0.1\n"
+ "DEFAULT action=ALLOW\n"
+ "\r\n",
+ 0,
+ "clrf newline",
+ },
+ {
+ "policy_name=whitespace policy_version=0.0.0\n"
+ "DEFAULT\taction=ALLOW\n"
+ " \t DEFAULT \t op=EXECUTE action=DENY\n"
+ "op=EXECUTE boot_verified=TRUE action=ALLOW\n"
+ "# this is a\tcomment\t\t\t\t\n"
+ "DEFAULT \t op=KMODULE\t\t\t action=DENY\r\n"
+ "op=KMODULE boot_verified=TRUE action=ALLOW\n",
+ 0,
+ "various whitespaces and nested default",
+ },
+ {
+ "policy_name=boot_verified policy_version=-1236.0.0\n"
+ "DEFAULT\taction=ALLOW\n",
+ -EINVAL,
+ "negative version",
+ },
+ {
+ "policy_name=$@!*&^%%\\:;{}() policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW",
+ 0,
+ "special characters",
+ },
+ {
+ "policy_name=test policy_version=999999.0.0\n"
+ "DEFAULT action=ALLOW",
+ -ERANGE,
+ "overflow version",
+ },
+ {
+ "policy_name=test policy_version=255.0\n"
+ "DEFAULT action=ALLOW",
+ -EBADMSG,
+ "incomplete version",
+ },
+ {
+ "policy_name=test policy_version=111.0.0.0\n"
+ "DEFAULT action=ALLOW",
+ -EBADMSG,
+ "extra version",
+ },
+ {
+ "",
+ -EBADMSG,
+ "0-length policy",
+ },
+ {
+ "policy_name=test\0policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW",
+ -EBADMSG,
+ "random null in header",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "\0DEFAULT action=ALLOW",
+ -EBADMSG,
+ "incomplete policy from NULL",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=DENY\n\0"
+ "op=EXECUTE dmverity_signature=TRUE action=ALLOW\n",
+ 0,
+ "NULL truncates policy",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE dmverity_signature=abc action=ALLOW",
+ -EBADMSG,
+ "invalid property type",
+ },
+ {
+ "DEFAULT action=ALLOW",
+ -EBADMSG,
+ "missing policy header",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n",
+ -EBADMSG,
+ "missing default definition",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "dmverity_signature=TRUE op=EXECUTE action=ALLOW",
+ -EBADMSG,
+ "invalid rule ordering"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "action=ALLOW op=EXECUTE dmverity_signature=TRUE",
+ -EBADMSG,
+ "invalid rule ordering (2)",
+ },
+ {
+ "policy_name=test policy_version=0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE dmverity_signature=TRUE action=ALLOW",
+ -EBADMSG,
+ "invalid version",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=UNKNOWN dmverity_signature=TRUE action=ALLOW",
+ -EBADMSG,
+ "unknown operation",
+ },
+ {
+ "policy_name=asdvpolicy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n",
+ -EBADMSG,
+ "missing space after policy name",
+ },
+ {
+ "policy_name=test\xFF\xEF policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE dmverity_signature=TRUE action=ALLOW",
+ 0,
+ "expanded ascii",
+ },
+ {
+ "policy_name=test\xFF\xEF policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE dmverity_roothash=GOOD_DOG action=ALLOW",
+ -EBADMSG,
+ "invalid property value (2)",
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "policy_name=test policy_version=0.1.0\n"
+ "DEFAULT action=ALLOW",
+ -EBADMSG,
+ "double header"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "DEFAULT action=ALLOW\n",
+ -EBADMSG,
+ "double default"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "DEFAULT op=EXECUTE action=DENY\n"
+ "DEFAULT op=EXECUTE action=ALLOW\n",
+ -EBADMSG,
+ "double operation default"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "DEFAULT op=EXECUTE action=DEN\n",
+ -EBADMSG,
+ "invalid action value"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "DEFAULT op=EXECUTE action\n",
+ -EBADMSG,
+ "invalid action value (2)"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "UNKNOWN value=true\n",
+ -EBADMSG,
+ "unrecognized statement"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE dmverity_roothash=1c0d7ee1f8343b7fbe418378e8eb22c061d7dec7 action=DENY\n",
+ -EBADMSG,
+ "old-style digest"
+ },
+ {
+ "policy_name=test policy_version=0.0.0\n"
+ "DEFAULT action=ALLOW\n"
+ "op=EXECUTE fsverity_digest=1c0d7ee1f8343b7fbe418378e8eb22c061d7dec7 action=DENY\n",
+ -EBADMSG,
+ "old-style digest"
+ }
+};
+
+static void pol_to_desc(const struct policy_case *c, char *desc)
+{
+ strncpy(desc, c->desc, KUNIT_PARAM_DESC_SIZE);
+}
+
+KUNIT_ARRAY_PARAM(ipe_policies, policy_cases, pol_to_desc);
+
+/**
+ * ipe_parser_unsigned_test - Test the parser by passing unsigned policies.
+ * @test: Supplies a pointer to a kunit structure.
+ *
+ * This is called by the kunit harness. This test does not check the correctness
+ * of the policy, but ensures that errors are handled correctly.
+ */
+static void ipe_parser_unsigned_test(struct kunit *test)
+{
+ const struct policy_case *p = test->param_value;
+ struct ipe_policy *pol = ipe_new_policy(p->policy, strlen(p->policy), NULL, 0);
+
+ if (p->errno) {
+ KUNIT_EXPECT_EQ(test, PTR_ERR(pol), p->errno);
+ return;
+ }
+
+ KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pol);
+ KUNIT_EXPECT_NOT_ERR_OR_NULL(test, pol->parsed);
+ KUNIT_EXPECT_STREQ(test, pol->text, p->policy);
+ KUNIT_EXPECT_PTR_EQ(test, NULL, pol->pkcs7);
+ KUNIT_EXPECT_EQ(test, 0, pol->pkcs7len);
+
+ ipe_free_policy(pol);
+}
+
+/**
+ * ipe_parser_widestring_test - Ensure parser fail on a wide string policy.
+ * @test: Supplies a pointer to a kunit structure.
+ *
+ * This is called by the kunit harness.
+ */
+static void ipe_parser_widestring_test(struct kunit *test)
+{
+ struct ipe_policy *pol = NULL;
+ const unsigned short policy[] = L"policy_name=Test policy_version=0.0.0\n"
+ L"DEFAULT action=ALLOW";
+
+ pol = ipe_new_policy((const char *)policy, (ARRAY_SIZE(policy) - 1) * 2, NULL, 0);
+ KUNIT_EXPECT_TRUE(test, IS_ERR_OR_NULL(pol));
+
+ ipe_free_policy(pol);
+}
+
+static struct kunit_case ipe_parser_test_cases[] = {
+ KUNIT_CASE_PARAM(ipe_parser_unsigned_test, ipe_policies_gen_params),
+ KUNIT_CASE(ipe_parser_widestring_test),
+};
+
+static struct kunit_suite ipe_parser_test_suite = {
+ .name = "ipe-parser",
+ .test_cases = ipe_parser_test_cases,
+};
+
+kunit_test_suite(ipe_parser_test_suite);
--
2.25.1


2023-06-28 21:17:17

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 07/17] ipe: add userspace interface

From: Deven Bowers <[email protected]>

As is typical with LSMs, IPE uses securityfs as its interface with
userspace. for a complete list of the interfaces and the respective
inputs/outputs, please see the documentation under
admin-guide/LSM/ipe.rst

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>

---
v2:
+ Split evaluation loop, access control hooks,
and evaluation loop from policy parser and userspace
interface to pass mailing list character limit

v3:
+ Move policy load and activation audit event to 03/12
+ Fix a potential panic when a policy failed to load.
+ use pr_warn for a failure to parse instead of an
audit record
+ Remove comments from headers
+ Add lockdep assertions to ipe_update_active_policy and
ipe_activate_policy
+ Fix up warnings with checkpatch --strict
+ Use file_ns_capable for CAP_MAC_ADMIN for securityfs
nodes.
+ Use memdup_user instead of kzalloc+simple_write_to_buffer.
+ Remove strict_parse command line parameter, as it is added
by the sysctl command line.
+ Prefix extern variables with ipe_

v4:
+ Remove securityfs to reverse-dependency
+ Add SHA1 reverse dependency.
+ Add versioning scheme for IPE properties, and associated
interface to query the versioning scheme.
+ Cause a parser to always return an error on unknown syntax.
+ Remove strict_parse option
+ Change active_policy interface from sysctl, to securityfs,
and change scheme.

v5:
+ Cause an error if a default action is not defined for each
operation.
+ Minor function renames

v6:
+ No changes

v7:
+ Propagating changes to support the new ipe_context structure in the
evaluation loop.

+ Further split the parser and userspace interface changes into
separate commits.

+ "raw" was renamed to "pkcs7" and made read only
+ "raw"'s write functionality (update a policy) moved to "update"
+ introduced "version", "policy_name" nodes.
+ "content" renamed to "policy"
+ changes to allow the compiled-in policy to be treated
identical to deployed-after-the-fact policies.

v8:
+ Prevent securityfs initialization if the LSM is disabled

v9:
+ Switch to securityfs_recursive_remove for policy folder deletion

v10:
+ Simplify and correct concurrency
+ Fix typos
---
security/ipe/Makefile | 2 +
security/ipe/fs.c | 101 ++++++++
security/ipe/fs.h | 16 ++
security/ipe/ipe.c | 3 +
security/ipe/ipe.h | 2 +
security/ipe/policy.c | 111 +++++++++
security/ipe/policy.h | 9 +
security/ipe/policy_fs.c | 481 +++++++++++++++++++++++++++++++++++++++
8 files changed, 725 insertions(+)
create mode 100644 security/ipe/fs.c
create mode 100644 security/ipe/fs.h
create mode 100644 security/ipe/policy_fs.c

diff --git a/security/ipe/Makefile b/security/ipe/Makefile
index d7f2870d7c09..8602d71250b4 100644
--- a/security/ipe/Makefile
+++ b/security/ipe/Makefile
@@ -7,7 +7,9 @@

obj-$(CONFIG_SECURITY_IPE) += \
eval.o \
+ fs.o \
hooks.o \
ipe.o \
policy.o \
+ policy_fs.o \
policy_parser.o \
diff --git a/security/ipe/fs.c b/security/ipe/fs.c
new file mode 100644
index 000000000000..522162af741a
--- /dev/null
+++ b/security/ipe/fs.c
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include <linux/dcache.h>
+#include <linux/security.h>
+
+#include "ipe.h"
+#include "fs.h"
+#include "policy.h"
+
+static struct dentry *np __ro_after_init;
+static struct dentry *root __ro_after_init;
+struct dentry *policy_root __ro_after_init;
+
+/**
+ * new_policy - Write handler for the securityfs node, "ipe/new_policy".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t new_policy(struct file *f, const char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ char *copy = NULL;
+ struct ipe_policy *p = NULL;
+
+ if (!file_ns_capable(f, &init_user_ns, CAP_MAC_ADMIN))
+ return -EPERM;
+
+ copy = memdup_user_nul(data, len);
+ if (IS_ERR(copy))
+ return PTR_ERR(copy);
+
+ p = ipe_new_policy(NULL, 0, copy, len);
+ if (IS_ERR(p)) {
+ rc = PTR_ERR(p);
+ goto out;
+ }
+
+ rc = ipe_new_policyfs_node(p);
+
+out:
+ if (rc < 0 && !IS_ERR(p))
+ ipe_free_policy(p);
+ kfree(copy);
+ return (rc < 0) ? rc : len;
+}
+
+static const struct file_operations np_fops = {
+ .write = new_policy,
+};
+
+/**
+ * ipe_init_securityfs - Initialize IPE's securityfs tree at fsinit.
+ *
+ * Return:
+ * * !0 - Error
+ * * 0 - OK
+ */
+static int __init ipe_init_securityfs(void)
+{
+ int rc = 0;
+
+ if (!ipe_enabled)
+ return -EOPNOTSUPP;
+
+ root = securityfs_create_dir("ipe", NULL);
+ if (IS_ERR(root)) {
+ rc = PTR_ERR(root);
+ goto err;
+ }
+
+ policy_root = securityfs_create_dir("policies", root);
+ if (IS_ERR(policy_root)) {
+ rc = PTR_ERR(policy_root);
+ goto err;
+ }
+
+ np = securityfs_create_file("new_policy", 0200, root, NULL, &np_fops);
+ if (IS_ERR(np)) {
+ rc = PTR_ERR(np);
+ goto err;
+ }
+
+ return 0;
+err:
+ securityfs_remove(np);
+ securityfs_remove(policy_root);
+ securityfs_remove(root);
+ return rc;
+}
+
+fs_initcall(ipe_init_securityfs);
diff --git a/security/ipe/fs.h b/security/ipe/fs.h
new file mode 100644
index 000000000000..c1fc0ca4ae93
--- /dev/null
+++ b/security/ipe/fs.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#ifndef _IPE_FS_H
+#define _IPE_FS_H
+
+#include "policy.h"
+
+extern struct dentry *policy_root __ro_after_init;
+
+int ipe_new_policyfs_node(struct ipe_policy *p);
+void ipe_del_policyfs_node(struct ipe_policy *p);
+
+#endif /* _IPE_FS_H */
diff --git a/security/ipe/ipe.c b/security/ipe/ipe.c
index 8f98ee7b8025..6f063d51b2af 100644
--- a/security/ipe/ipe.c
+++ b/security/ipe/ipe.c
@@ -6,6 +6,8 @@
#include "ipe.h"
#include "hooks.h"

+bool ipe_enabled;
+
static struct lsm_blob_sizes ipe_blobs __ro_after_init = {
};

@@ -33,6 +35,7 @@ static int __init ipe_init(void)
int rc = 0;

security_add_hooks(ipe_hooks, ARRAY_SIZE(ipe_hooks), "ipe");
+ ipe_enabled = true;

return rc;
}
diff --git a/security/ipe/ipe.h b/security/ipe/ipe.h
index a1c68d0fc2e0..6dec06403eee 100644
--- a/security/ipe/ipe.h
+++ b/security/ipe/ipe.h
@@ -13,4 +13,6 @@

#include <linux/lsm_hooks.h>

+extern bool ipe_enabled;
+
#endif /* _IPE_H */
diff --git a/security/ipe/policy.c b/security/ipe/policy.c
index 4069ff075093..3e8e4a06a044 100644
--- a/security/ipe/policy.c
+++ b/security/ipe/policy.c
@@ -7,9 +7,36 @@
#include <linux/verification.h>

#include "ipe.h"
+#include "eval.h"
+#include "fs.h"
#include "policy.h"
#include "policy_parser.h"

+/* lock for synchronizing writers across ipe policy */
+DEFINE_MUTEX(ipe_policy_lock);
+
+/**
+ * ver_to_u64 - Convert an internal ipe_policy_version to a u64.
+ * @p: Policy to extract the version from.
+ *
+ * Bits (LSB is index 0):
+ * [48,32] -> Major
+ * [32,16] -> Minor
+ * [16, 0] -> Revision
+ *
+ * Return: u64 version of the embedded version structure.
+ */
+static inline u64 ver_to_u64(const struct ipe_policy *const p)
+{
+ u64 r;
+
+ r = (((u64)p->parsed->version.major) << 32)
+ | (((u64)p->parsed->version.minor) << 16)
+ | ((u64)(p->parsed->version.rev));
+
+ return r;
+}
+
/**
* ipe_free_policy - Deallocate a given IPE policy.
* @p: Supplies the policy to free.
@@ -21,6 +48,7 @@ void ipe_free_policy(struct ipe_policy *p)
if (IS_ERR_OR_NULL(p))
return;

+ ipe_del_policyfs_node(p);
free_parsed_policy(p->parsed);
if (!p->pkcs7)
kfree(p->text);
@@ -39,6 +67,65 @@ static int set_pkcs7_data(void *ctx, const void *data, size_t len,
return 0;
}

+/**
+ * ipe_update_policy - parse a new policy and replace @old with it.
+ * @root: Supplies a pointer to the securityfs inode saved the policy.
+ * @text: Supplies a pointer to the plain text policy.
+ * @textlen: Supplies the length of @text.
+ * @pkcs7: Supplies a pointer to a buffer containing a pkcs7 message.
+ * @pkcs7len: Supplies the length of @pkcs7len.
+ *
+ * @text/@textlen is mutually exclusive with @pkcs7/@pkcs7len - see
+ * ipe_new_policy.
+ *
+ * Return:
+ * * !IS_ERR - The old policy
+ * * -ENOENT - Policy doesn't exist
+ * * -EINVAL - New policy is invalid
+ */
+struct ipe_policy *ipe_update_policy(struct inode *root,
+ const char *text, size_t textlen,
+ const char *pkcs7, size_t pkcs7len)
+{
+ int rc = 0;
+ struct ipe_policy *old, *ap, *new = NULL;
+
+ lockdep_assert_held(&ipe_policy_lock);
+
+ old = (struct ipe_policy *)root->i_private;
+ if (!old)
+ return ERR_PTR(-ENOENT);
+
+ new = ipe_new_policy(text, textlen, pkcs7, pkcs7len);
+ if (IS_ERR(new))
+ return new;
+
+ if (strcmp(new->parsed->name, old->parsed->name)) {
+ rc = -EINVAL;
+ goto err;
+ }
+
+ if (ver_to_u64(old) > ver_to_u64(new)) {
+ rc = -EINVAL;
+ goto err;
+ }
+
+ root->i_private = new;
+
+ ap = rcu_dereference_protected(ipe_active_policy,
+ lockdep_is_held(&ipe_policy_lock));
+ if (old == ap)
+ rcu_assign_pointer(ipe_active_policy, new);
+
+ swap(new->policyfs, old->policyfs);
+
+out:
+ return (rc < 0) ? ERR_PTR(rc) : old;
+err:
+ ipe_free_policy(new);
+ goto out;
+}
+
/**
* ipe_new_policy - Allocate and parse an ipe_policy structure.
*
@@ -95,3 +182,27 @@ struct ipe_policy *ipe_new_policy(const char *text, size_t textlen,
ipe_free_policy(new);
return ERR_PTR(rc);
}
+
+/**
+ * ipe_set_active_pol - Make @p the active policy.
+ * @p: Supplies a pointer to the policy to make active.
+ *
+ * Return:
+ * * !IS_ERR - Success
+ * * -EINVAL - New active policy version is invalid
+ */
+int ipe_set_active_pol(const struct ipe_policy *p)
+{
+ struct ipe_policy *ap = NULL;
+
+ lockdep_assert_held(&ipe_policy_lock);
+
+ ap = rcu_dereference_protected(ipe_active_policy,
+ lockdep_is_held(&ipe_policy_lock));
+ if (ap && ver_to_u64(ap) > ver_to_u64(p))
+ return -EINVAL;
+
+ rcu_assign_pointer(ipe_active_policy, p);
+
+ return 0;
+}
diff --git a/security/ipe/policy.h b/security/ipe/policy.h
index a74856b9966c..94bcbbf79b05 100644
--- a/security/ipe/policy.h
+++ b/security/ipe/policy.h
@@ -7,6 +7,7 @@

#include <linux/list.h>
#include <linux/types.h>
+#include <linux/fs.h>

enum ipe_op_type {
__IPE_OP_EXEC = 0,
@@ -76,10 +77,18 @@ struct ipe_policy {
size_t textlen;

struct ipe_parsed_policy *parsed;
+
+ struct dentry *policyfs;
};

struct ipe_policy *ipe_new_policy(const char *text, size_t textlen,
const char *pkcs7, size_t pkcs7len);
void ipe_free_policy(struct ipe_policy *pol);
+struct ipe_policy *ipe_update_policy(struct inode *root,
+ const char *text,
+ size_t textlen, const char *pkcs7,
+ size_t pkcs7len);
+int ipe_set_active_pol(const struct ipe_policy *p);
+extern struct mutex ipe_policy_lock;

#endif /* _IPE_POLICY_H */
diff --git a/security/ipe/policy_fs.c b/security/ipe/policy_fs.c
new file mode 100644
index 000000000000..52a120118cda
--- /dev/null
+++ b/security/ipe/policy_fs.c
@@ -0,0 +1,481 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+#include <linux/fs.h>
+#include <linux/namei.h>
+#include <linux/types.h>
+#include <linux/dcache.h>
+#include <linux/security.h>
+
+#include "ipe.h"
+#include "policy.h"
+#include "eval.h"
+#include "fs.h"
+
+#define MAX_VERSION_SIZE ARRAY_SIZE("65535.65535.65535")
+
+/**
+ * ipefs_file - defines a file in securityfs.
+ */
+struct ipefs_file {
+ const char *name;
+ umode_t access;
+ const struct file_operations *fops;
+};
+
+/**
+ * read_pkcs7 - Read handler for "ipe/policies/$name/pkcs7".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * @data will be populated with the pkcs7 blob representing the policy
+ * on success. If the policy is unsigned (like the boot policy), this
+ * will return -ENOENT.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t read_pkcs7(struct file *f, char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+
+ inode_lock_shared(root);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ if (!p->pkcs7) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ rc = simple_read_from_buffer(data, len, offset, p->pkcs7, p->pkcs7len);
+
+out:
+ inode_unlock_shared(root);
+
+ return rc;
+}
+
+/**
+ * read_policy - Read handler for "ipe/policies/$name/policy".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * @data will be populated with the plain-text version of the policy
+ * on success.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t read_policy(struct file *f, char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+
+ inode_lock_shared(root);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ rc = simple_read_from_buffer(data, len, offset, p->text, p->textlen);
+
+out:
+ inode_unlock_shared(root);
+
+ return rc;
+}
+
+/**
+ * read_name: Read handler for "ipe/policies/$name/name".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * @data will be populated with the policy_name attribute on success.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t read_name(struct file *f, char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+
+ inode_lock_shared(root);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ rc = simple_read_from_buffer(data, len, offset, p->parsed->name,
+ strlen(p->parsed->name));
+
+out:
+ inode_unlock_shared(root);
+
+ return rc;
+}
+
+/**
+ * read_version - Read handler for "ipe/policies/$name/version".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * @data will be populated with the version string on success.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t read_version(struct file *f, char __user *data,
+ size_t len, loff_t *offset)
+{
+ ssize_t rc = 0;
+ size_t bufsize = 0;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+ char buffer[MAX_VERSION_SIZE] = { 0 };
+
+ root = d_inode(f->f_path.dentry->d_parent);
+
+ inode_lock_shared(root);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ bufsize = scnprintf(buffer, ARRAY_SIZE(buffer), "%hu.%hu.%hu",
+ p->parsed->version.major, p->parsed->version.minor,
+ p->parsed->version.rev);
+
+ rc = simple_read_from_buffer(data, len, offset, buffer, bufsize);
+
+out:
+ inode_unlock_shared(root);
+
+ return rc;
+}
+
+/**
+ * setactive - Write handler for "ipe/policies/$name/active".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Supplies a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t setactive(struct file *f, const char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ bool value = false;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+
+ if (!file_ns_capable(f, &init_user_ns, CAP_MAC_ADMIN))
+ return -EPERM;
+
+ rc = kstrtobool_from_user(data, len, &value);
+ if (rc)
+ return rc;
+
+ if (!value)
+ return -EINVAL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+ inode_lock(root);
+ mutex_lock(&ipe_policy_lock);
+
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ rc = -ENOENT;
+ goto out;
+ }
+
+ rc = ipe_set_active_pol(p);
+
+out:
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+ synchronize_rcu();
+ return (rc < 0) ? rc : len;
+}
+
+/**
+ * getactive - Read handler for "ipe/policies/$name/active".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Suppleis a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * @data will be populated with the 1 or 0 depending on if the
+ * corresponding policy is active.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t getactive(struct file *f, char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ const char *str;
+ struct inode *root = NULL;
+ const struct ipe_policy *p = NULL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+
+ inode_lock_shared(root);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ inode_unlock_shared(root);
+ return -ENOENT;
+ }
+ inode_unlock_shared(root);
+
+ str = (p == rcu_access_pointer(ipe_active_policy)) ? "1" : "0";
+ rc = simple_read_from_buffer(data, len, offset, str, 1);
+
+ return rc;
+}
+
+/**
+ * update_policy - Write handler for "ipe/policies/$name/update".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Supplies a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * On success this updates the policy represented by $name,
+ * in-place.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t update_policy(struct file *f, const char __user *data,
+ size_t len, loff_t *offset)
+{
+ char *copy = NULL;
+ struct inode *root = NULL;
+ struct ipe_policy *old = NULL;
+
+ if (!file_ns_capable(f, &init_user_ns, CAP_MAC_ADMIN))
+ return -EPERM;
+
+ copy = memdup_user(data, len);
+ if (IS_ERR(copy))
+ return PTR_ERR(copy);
+
+ root = d_inode(f->f_path.dentry->d_parent);
+ inode_lock(root);
+ mutex_lock(&ipe_policy_lock);
+ old = ipe_update_policy(root, NULL, 0, copy, len);
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+ synchronize_rcu();
+
+ kfree(copy);
+ if (IS_ERR(old))
+ return PTR_ERR(old);
+ ipe_free_policy(old);
+
+ return len;
+}
+
+/**
+ * delete_policy - write handler for "ipe/policies/$name/delete".
+ * @f: Supplies a file structure representing the securityfs node.
+ * @data: Supplies a buffer passed to the write syscall.
+ * @len: Supplies the length of @data.
+ * @offset: unused.
+ *
+ * On success this deletes the policy represented by $name.
+ *
+ * Return:
+ * * >0 - Success, Length of buffer written
+ * * <0 - Error
+ */
+static ssize_t delete_policy(struct file *f, const char __user *data,
+ size_t len, loff_t *offset)
+{
+ int rc = 0;
+ bool value = false;
+ struct inode *root = NULL;
+ struct ipe_policy *p = NULL;
+ struct ipe_policy *ap = NULL;
+
+ if (!file_ns_capable(f, &init_user_ns, CAP_MAC_ADMIN))
+ return -EPERM;
+
+ rc = kstrtobool_from_user(data, len, &value);
+ if (rc)
+ return rc;
+
+ if (!value)
+ return -EINVAL;
+
+ root = d_inode(f->f_path.dentry->d_parent);
+ inode_lock(root);
+ mutex_lock(&ipe_policy_lock);
+ p = (struct ipe_policy *)root->i_private;
+ if (!p) {
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+ return -ENOENT;
+ }
+
+ ap = rcu_dereference_protected(ipe_active_policy,
+ lockdep_is_held(&ipe_policy_lock));
+ if (p == ap) {
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+ return -EPERM;
+ }
+ root->i_private = NULL;
+
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+ synchronize_rcu();
+
+ ipe_free_policy(p);
+ return len;
+}
+
+static const struct file_operations content_fops = {
+ .read = read_policy,
+};
+
+static const struct file_operations pkcs7_fops = {
+ .read = read_pkcs7,
+};
+
+static const struct file_operations name_fops = {
+ .read = read_name,
+};
+
+static const struct file_operations ver_fops = {
+ .read = read_version,
+};
+
+static const struct file_operations active_fops = {
+ .write = setactive,
+ .read = getactive,
+};
+
+static const struct file_operations update_fops = {
+ .write = update_policy,
+};
+
+static const struct file_operations delete_fops = {
+ .write = delete_policy,
+};
+
+/**
+ * policy_subdir - files under a policy subdirectory
+ */
+static const struct ipefs_file policy_subdir[] = {
+ { "pkcs7", 0444, &pkcs7_fops },
+ { "policy", 0444, &content_fops },
+ { "name", 0444, &name_fops },
+ { "version", 0444, &ver_fops },
+ { "active", 0600, &active_fops },
+ { "update", 0200, &update_fops },
+ { "delete", 0200, &delete_fops },
+};
+
+/**
+ * ipe_del_policyfs_node - Delete a securityfs entry for @p.
+ * @p: Supplies a pointer to the policy to delete a securityfs entry for.
+ */
+void ipe_del_policyfs_node(struct ipe_policy *p)
+{
+ securityfs_recursive_remove(p->policyfs);
+ p->policyfs = NULL;
+}
+
+/**
+ * ipe_new_policyfs_node - Create a securityfs entry for @p.
+ * @p: Supplies a pointer to the policy to create a securityfs entry for.
+ *
+ * Return:
+ * * 0 - OK
+ * * !0 - Error
+ */
+int ipe_new_policyfs_node(struct ipe_policy *p)
+{
+ int rc = 0;
+ size_t i = 0;
+ struct dentry *d = NULL;
+ struct dentry *policyfs = NULL;
+ struct inode *root = NULL;
+ const struct ipefs_file *f = NULL;
+
+ if (p->policyfs)
+ return 0;
+
+ policyfs = securityfs_create_dir(p->parsed->name, policy_root);
+ if (IS_ERR(policyfs)) {
+ rc = PTR_ERR(policyfs);
+ goto err;
+ }
+
+ root = d_inode(policyfs);
+
+ for (i = 0; i < ARRAY_SIZE(policy_subdir); ++i) {
+ f = &policy_subdir[i];
+
+ d = securityfs_create_file(f->name, f->access, policyfs,
+ NULL, f->fops);
+ if (IS_ERR(d)) {
+ rc = PTR_ERR(d);
+ goto err;
+ }
+ }
+
+ inode_lock(root);
+ mutex_lock(&ipe_policy_lock);
+ p->policyfs = policyfs;
+ root->i_private = p;
+ mutex_unlock(&ipe_policy_lock);
+ inode_unlock(root);
+
+ return 0;
+err:
+ securityfs_recursive_remove(policyfs);
+ return rc;
+}
--
2.25.1


2023-06-28 21:17:53

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 01/17] security: add ipe lsm

From: Deven Bowers <[email protected]>

Integrity Policy Enforcement (IPE) is an LSM that provides an
complimentary approach to Mandatory Access Control than existing LSMs
today.

Existing LSMs have centered around the concept of access to a resource
should be controlled by the current user's credentials. IPE's approach,
is that access to a resource should be controlled by the system's trust
of a current resource.

The basis of this approach is defining a global policy to specify which
resource can be trusted.

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>
---
v2:
+ Split evaluation loop, access control hooks,
and evaluation loop from policy parser and userspace
interface to pass mailing list character limit

v3:
+ Move ipe_load_properties to patch 04.
+ Remove useless 0-initializations
+ Prefix extern variables with ipe_
+ Remove kernel module parameters, as these are
exposed through sysctls.
+ Add more prose to the IPE base config option
help text.
+ Use GFP_KERNEL for audit_log_start.
+ Remove unnecessary caching system.
+ Remove comments from headers
+ Use rcu_access_pointer for rcu-pointer null check
+ Remove usage of reqprot; use prot only.
+ Move policy load and activation audit event to 03/12

v4:
+ Remove sysctls in favor of securityfs nodes
+ Re-add kernel module parameters, as these are now
exposed through securityfs.
+ Refactor property audit loop to a separate function.

v5:
+ fix minor grammatical errors
+ do not group rule by curly-brace in audit record,
reconstruct the exact rule.

v6:
+ No changes

v7:
+ Further split lsm creation into a separate commit from the
evaluation loop and audit system, for easier review.

+ Introduce the concept of an ipe_context, a scoped way to
introduce execution policies, used initially for allowing for
kunit tests in isolation.

v8:
+ Follow lsmname_hook_name convention for lsm hooks.
+ Move LSM blob accessors to ipe.c and mark LSM blobs as static.

v9:
+ Remove ipe_context for simplification

v10:
+ Add github url
---
MAINTAINERS | 7 +++++++
security/Kconfig | 11 ++++++-----
security/Makefile | 1 +
security/ipe/Kconfig | 17 +++++++++++++++++
security/ipe/Makefile | 10 ++++++++++
security/ipe/ipe.c | 37 +++++++++++++++++++++++++++++++++++++
security/ipe/ipe.h | 16 ++++++++++++++++
7 files changed, 94 insertions(+), 5 deletions(-)
create mode 100644 security/ipe/Kconfig
create mode 100644 security/ipe/Makefile
create mode 100644 security/ipe/ipe.c
create mode 100644 security/ipe/ipe.h

diff --git a/MAINTAINERS b/MAINTAINERS
index a82795114ad4..ad00887d38ea 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -10278,6 +10278,13 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity.git
F: security/integrity/
F: security/integrity/ima/

+INTEGRITY POLICY ENFORCEMENT (IPE)
+M: Fan Wu <[email protected]>
+L: [email protected]
+S: Supported
+T: git git://github.com/microsoft/ipe.git
+F: security/ipe/
+
INTEL 810/815 FRAMEBUFFER DRIVER
M: Antonino Daplas <[email protected]>
L: [email protected]
diff --git a/security/Kconfig b/security/Kconfig
index 97abeb9b9a19..daa4626ea99c 100644
--- a/security/Kconfig
+++ b/security/Kconfig
@@ -202,6 +202,7 @@ source "security/yama/Kconfig"
source "security/safesetid/Kconfig"
source "security/lockdown/Kconfig"
source "security/landlock/Kconfig"
+source "security/ipe/Kconfig"

source "security/integrity/Kconfig"

@@ -241,11 +242,11 @@ endchoice

config LSM
string "Ordered list of enabled LSMs"
- default "landlock,lockdown,yama,loadpin,safesetid,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
- default "landlock,lockdown,yama,loadpin,safesetid,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
- default "landlock,lockdown,yama,loadpin,safesetid,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
- default "landlock,lockdown,yama,loadpin,safesetid,bpf" if DEFAULT_SECURITY_DAC
- default "landlock,lockdown,yama,loadpin,safesetid,selinux,smack,tomoyo,apparmor,bpf"
+ default "landlock,lockdown,yama,loadpin,safesetid,smack,selinux,tomoyo,apparmor,bpf,ipe" if DEFAULT_SECURITY_SMACK
+ default "landlock,lockdown,yama,loadpin,safesetid,apparmor,selinux,smack,tomoyo,bpf,ipe" if DEFAULT_SECURITY_APPARMOR
+ default "landlock,lockdown,yama,loadpin,safesetid,tomoyo,bpf,ipe" if DEFAULT_SECURITY_TOMOYO
+ default "landlock,lockdown,yama,loadpin,safesetid,bpf,ipe" if DEFAULT_SECURITY_DAC
+ default "landlock,lockdown,yama,loadpin,safesetid,selinux,smack,tomoyo,apparmor,bpf,ipe"
help
A comma-separated list of LSMs, in initialization order.
Any LSMs left off this list, except for those with order
diff --git a/security/Makefile b/security/Makefile
index 18121f8f85cd..527b1864d96c 100644
--- a/security/Makefile
+++ b/security/Makefile
@@ -24,6 +24,7 @@ obj-$(CONFIG_SECURITY_LOCKDOWN_LSM) += lockdown/
obj-$(CONFIG_CGROUPS) += device_cgroup.o
obj-$(CONFIG_BPF_LSM) += bpf/
obj-$(CONFIG_SECURITY_LANDLOCK) += landlock/
+obj-$(CONFIG_SECURITY_IPE) += ipe/

# Object integrity file lists
obj-$(CONFIG_INTEGRITY) += integrity/
diff --git a/security/ipe/Kconfig b/security/ipe/Kconfig
new file mode 100644
index 000000000000..e4875fb04883
--- /dev/null
+++ b/security/ipe/Kconfig
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Integrity Policy Enforcement (IPE) configuration
+#
+
+menuconfig SECURITY_IPE
+ bool "Integrity Policy Enforcement (IPE)"
+ depends on SECURITY && SECURITYFS
+ select PKCS7_MESSAGE_PARSER
+ select SYSTEM_DATA_VERIFICATION
+ help
+ This option enables the Integrity Policy Enforcement LSM
+ allowing users to define a policy to enforce a trust-based access
+ control. A key feature of IPE is a customizable policy to allow
+ admins to reconfigure trust requirements on the fly.
+
+ If unsure, answer N.
diff --git a/security/ipe/Makefile b/security/ipe/Makefile
new file mode 100644
index 000000000000..571648579991
--- /dev/null
+++ b/security/ipe/Makefile
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) Microsoft Corporation. All rights reserved.
+#
+# Makefile for building the IPE module as part of the kernel tree.
+#
+
+obj-$(CONFIG_SECURITY_IPE) += \
+ hooks.o \
+ ipe.o \
diff --git a/security/ipe/ipe.c b/security/ipe/ipe.c
new file mode 100644
index 000000000000..2ee0f5de29d7
--- /dev/null
+++ b/security/ipe/ipe.c
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include "ipe.h"
+
+static struct lsm_blob_sizes ipe_blobs __ro_after_init = {
+};
+
+static struct security_hook_list ipe_hooks[] __ro_after_init = {
+};
+
+/**
+ * ipe_init - Entry point of IPE.
+ *
+ * This is called at LSM init, which happens occurs early during kernel
+ * start up. During this phase, IPE registers its hooks and loads the
+ * builtin boot policy.
+ * Return:
+ * * 0 - OK
+ * * -ENOMEM - Out of memory
+ */
+static int __init ipe_init(void)
+{
+ int rc = 0;
+
+ security_add_hooks(ipe_hooks, ARRAY_SIZE(ipe_hooks), "ipe");
+
+ return rc;
+}
+
+DEFINE_LSM(ipe) = {
+ .name = "ipe",
+ .init = ipe_init,
+ .blobs = &ipe_blobs,
+};
diff --git a/security/ipe/ipe.h b/security/ipe/ipe.h
new file mode 100644
index 000000000000..a1c68d0fc2e0
--- /dev/null
+++ b/security/ipe/ipe.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#ifndef _IPE_H
+#define _IPE_H
+
+#ifdef pr_fmt
+#undef pr_fmt
+#endif
+#define pr_fmt(fmt) "IPE: " fmt
+
+#include <linux/lsm_hooks.h>
+
+#endif /* _IPE_H */
--
2.25.1


2023-06-28 21:21:57

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 12/17] ipe: add support for dm-verity as a trust provider

From: Deven Bowers <[email protected]>

Allows author of IPE policy to indicate trust for a singular dm-verity
volume, identified by roothash, through "dmverity_roothash" and all
signed dm-verity volumes, through "dmverity_signature".

Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>
---
v2:
+ No Changes

v3:
+ No changes

v4:
+ No changes

v5:
+ No changes

v6:
+ Fix an improper cleanup that can result in
a leak

v7:
+ Squash patch 08/12, 10/12 to [11/16]

v8:
+ Undo squash of 08/12, 10/12 - separating drivers/md/ from security/
& block/
+ Use common-audit function for dmverity_signature.
+ Change implementation for storing the dm-verity digest to use the
newly introduced dm_verity_digest structure introduced in patch
14/20.

v9:
+ Adapt to the new parser

v10:
+ Select the Kconfig when all dependencies are enabled
---
security/ipe/Kconfig | 18 +++++
security/ipe/Makefile | 1 +
security/ipe/audit.c | 25 ++++++
security/ipe/digest.c | 142 +++++++++++++++++++++++++++++++++++
security/ipe/digest.h | 26 +++++++
security/ipe/eval.c | 101 ++++++++++++++++++++++++-
security/ipe/eval.h | 13 ++++
security/ipe/hooks.c | 51 +++++++++++++
security/ipe/hooks.h | 8 ++
security/ipe/ipe.c | 15 ++++
security/ipe/ipe.h | 4 +
security/ipe/policy.h | 3 +
security/ipe/policy_parser.c | 21 ++++++
13 files changed, 427 insertions(+), 1 deletion(-)
create mode 100644 security/ipe/digest.c
create mode 100644 security/ipe/digest.h

diff --git a/security/ipe/Kconfig b/security/ipe/Kconfig
index ac4d558e69d5..7afb1ce0cb99 100644
--- a/security/ipe/Kconfig
+++ b/security/ipe/Kconfig
@@ -8,6 +8,7 @@ menuconfig SECURITY_IPE
depends on SECURITY && SECURITYFS && AUDIT && AUDITSYSCALL
select PKCS7_MESSAGE_PARSER
select SYSTEM_DATA_VERIFICATION
+ select IPE_PROP_DM_VERITY if DM_VERITY && DM_VERITY_VERIFY_ROOTHASH_SIG
help
This option enables the Integrity Policy Enforcement LSM
allowing users to define a policy to enforce a trust-based access
@@ -15,3 +16,20 @@ menuconfig SECURITY_IPE
admins to reconfigure trust requirements on the fly.

If unsure, answer N.
+
+if SECURITY_IPE
+menu "IPE Trust Providers"
+
+config IPE_PROP_DM_VERITY
+ bool "Enable support for dm-verity volumes"
+ depends on DM_VERITY && DM_VERITY_VERIFY_ROOTHASH_SIG
+ help
+ This option enables the properties 'dmverity_signature' and
+ 'dmverity_roothash' in IPE policy. These properties evaluates
+ to TRUE when a file is evaluated against a dm-verity volume
+ that was mounted with a signed root-hash or the volume's
+ root hash matches the supplied value in the policy.
+
+endmenu
+
+endif
diff --git a/security/ipe/Makefile b/security/ipe/Makefile
index 89a76ad72301..ec7f69c34735 100644
--- a/security/ipe/Makefile
+++ b/security/ipe/Makefile
@@ -6,6 +6,7 @@
#

obj-$(CONFIG_SECURITY_IPE) += \
+ digest.o \
eval.o \
fs.o \
hooks.o \
diff --git a/security/ipe/audit.c b/security/ipe/audit.c
index 08f855f70f76..781f98536b35 100644
--- a/security/ipe/audit.c
+++ b/security/ipe/audit.c
@@ -13,6 +13,7 @@
#include "hooks.h"
#include "policy.h"
#include "audit.h"
+#include "digest.h"

#define ACTSTR(x) ((x) == __IPE_ACTION_ALLOW ? "ALLOW" : "DENY")

@@ -40,8 +41,29 @@ static const char *const audit_op_names[__IPE_OP_MAX] = {
static const char *const audit_prop_names[__IPE_PROP_MAX] = {
"boot_verified=FALSE",
"boot_verified=TRUE",
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+ "dmverity_roothash=",
+ "dmverity_signature=FALSE",
+ "dmverity_signature=TRUE",
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
};

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+/**
+ * audit_dmv_roothash - audit a roothash of a dmverity volume.
+ * @ab: Supplies a pointer to the audit_buffer to append to.
+ * @r: Supplies a pointer to the digest structure.
+ */
+static void audit_dmv_roothash(struct audit_buffer *ab, const void *rh)
+{
+ ipe_digest_audit(ab, rh);
+}
+#else
+static void audit_dmv_roothash(struct audit_buffer *ab, const void *rh)
+{
+}
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
/**
* audit_rule - audit an IPE policy rule approximation.
* @ab: Supplies a pointer to the audit_buffer to append to.
@@ -55,6 +77,9 @@ static void audit_rule(struct audit_buffer *ab, const struct ipe_rule *r)

list_for_each_entry(ptr, &r->props, next) {
audit_log_format(ab, "%s", audit_prop_names[ptr->type]);
+ if (ptr->type == __IPE_PROP_DMV_ROOTHASH)
+ audit_dmv_roothash(ab, ptr->value);
+
audit_log_format(ab, " ");
}

diff --git a/security/ipe/digest.c b/security/ipe/digest.c
new file mode 100644
index 000000000000..7a42ca71880c
--- /dev/null
+++ b/security/ipe/digest.c
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#include "digest.h"
+
+/**
+ * ipe_digest_parse - parse a digest in IPE's policy.
+ * @valstr: Supplies the string parsed from the policy.
+ * @value: Supplies a pointer to be populated with the result.
+ *
+ * Digests in IPE are defined in a standard way:
+ * <alg_name>:<hex>
+ *
+ * Use this function to create a property to parse the digest
+ * consistently. The parsed digest will be saved in @value in IPE's
+ * policy.
+ *
+ * Return:
+ * * 0 - OK
+ * * !0 - Error
+ */
+int ipe_digest_parse(const char *valstr, void **value)
+{
+ char *sep, *raw_digest;
+ size_t raw_digest_len;
+ int rc = 0;
+ u8 *digest = NULL;
+ struct digest_info *info = NULL;
+
+ info = kzalloc(sizeof(*info), GFP_KERNEL);
+ if (!info)
+ return -ENOMEM;
+
+ sep = strchr(valstr, ':');
+ if (!sep) {
+ rc = -EBADMSG;
+ goto err;
+ }
+
+ info->alg = kstrndup(valstr, sep - valstr, GFP_KERNEL);
+ if (!info->alg) {
+ rc = -ENOMEM;
+ goto err;
+ }
+
+ raw_digest = sep + 1;
+ raw_digest_len = strlen(raw_digest);
+ info->raw_digest = kstrndup(raw_digest, raw_digest_len, GFP_KERNEL);
+ if (!info->raw_digest) {
+ rc = -ENOMEM;
+ goto err_free_alg;
+ }
+
+ info->digest_len = (raw_digest_len + 1) / 2;
+ digest = kzalloc(info->digest_len, GFP_KERNEL);
+ if (!digest) {
+ rc = -ENOMEM;
+ goto err_free_raw;
+ }
+
+ rc = hex2bin(digest, raw_digest, info->digest_len);
+ if (rc < 0) {
+ rc = -EINVAL;
+ goto err_free_raw;
+ }
+
+ info->digest = digest;
+ *value = info;
+ return 0;
+
+err_free_raw:
+ kfree(info->raw_digest);
+err_free_alg:
+ kfree(info->alg);
+err:
+ kfree(digest);
+ kfree(info);
+ return rc;
+}
+
+/**
+ * ipe_digest_eval - evaluate an IPE digest against another digest.
+ * @expect: Supplies the policy-provided digest value.
+ * @digest: Supplies the digest to compare against the policy digest value.
+ * @digest_len: The length of @digest.
+ * @alg: Supplies the name of the algorithm used to calculated @digest.
+ *
+ * Return:
+ * * true - digests match
+ * * false - digests do not match
+ */
+bool ipe_digest_eval(const void *expect, const u8 *digest, size_t digest_len,
+ const char *alg)
+{
+ const struct digest_info *info = (struct digest_info *)expect;
+
+ return (digest_len == info->digest_len) && !strcmp(alg, info->alg) &&
+ (!memcmp(info->digest, digest, info->digest_len));
+}
+
+/**
+ * ipe_digest_free - free an IPE digest.
+ * @value: Supplies a pointer the policy-provided digest value to free.
+ */
+void ipe_digest_free(void **value)
+{
+ struct digest_info *info = (struct digest_info *)(*value);
+
+ if (IS_ERR_OR_NULL(info))
+ return;
+
+ kfree(info->alg);
+ kfree(info->raw_digest);
+ kfree(info->digest);
+ kfree(info);
+}
+
+/**
+ * ipe_digest_audit - audit a digest that was sourced from IPE's policy.
+ * @ab: Supplies the audit_buffer to append the formatted result.
+ * @val: Supplies a pointer to source the audit record from.
+ *
+ * Digests in IPE are defined in a standard way:
+ * <alg_name>:<hex>
+ *
+ * Use this function to create a property to audit the digest
+ * consistently.
+ *
+ * Return:
+ * 0 - OK
+ * !0 - Error
+ */
+void ipe_digest_audit(struct audit_buffer *ab, const void *val)
+{
+ const struct digest_info *info = (struct digest_info *)val;
+
+ audit_log_untrustedstring(ab, info->alg);
+ audit_log_format(ab, ":");
+ audit_log_untrustedstring(ab, info->raw_digest);
+}
diff --git a/security/ipe/digest.h b/security/ipe/digest.h
new file mode 100644
index 000000000000..e40ba4b2799e
--- /dev/null
+++ b/security/ipe/digest.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) Microsoft Corporation. All rights reserved.
+ */
+
+#ifndef _IPE_DIGEST_H
+#define _IPE_DIGEST_H
+
+#include "policy.h"
+#include <linux/types.h>
+#include <linux/audit.h>
+
+struct digest_info {
+ const char *alg;
+ const char *raw_digest;
+ const u8 *digest;
+ size_t digest_len;
+};
+
+int ipe_digest_parse(const char *valstr, void **value);
+void ipe_digest_free(void **value);
+void ipe_digest_audit(struct audit_buffer *ab, const void *val);
+bool ipe_digest_eval(const void *expect, const u8 *digest, size_t digest_len,
+ const char *alg);
+
+#endif /* _IPE_DIGEST_H */
diff --git a/security/ipe/eval.c b/security/ipe/eval.c
index 2d4b3a6d7b7a..8ba7d6bd2950 100644
--- a/security/ipe/eval.c
+++ b/security/ipe/eval.c
@@ -17,10 +17,12 @@
#include "hooks.h"
#include "policy.h"
#include "audit.h"
+#include "digest.h"

struct ipe_policy __rcu *ipe_active_policy;
bool success_audit;
bool enforce = true;
+#define INO_BLOCK_DEV(ino) ((ino)->i_sb->s_bdev)

static const struct super_block *pinned_sb;
static DEFINE_SPINLOCK(pin_lock);
@@ -60,6 +62,23 @@ static bool from_pinned(const struct super_block *sb)
return rv;
}

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+/**
+ * build_ipe_bdev_ctx - Build ipe_bdev field of an evaluation context.
+ * @ctx: Supplies a pointer to the context to be populdated.
+ * @ino: Supplies the inode struct of the file triggered IPE event.
+ */
+static void build_ipe_bdev_ctx(struct ipe_eval_ctx *ctx, const struct inode *const ino)
+{
+ if (INO_BLOCK_DEV(ino))
+ ctx->ipe_bdev = ipe_bdev(INO_BLOCK_DEV(ino));
+}
+#else
+static void build_ipe_bdev_ctx(struct ipe_eval_ctx *ctx, const struct inode *const ino)
+{
+}
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
/**
* build_eval_ctx - Build an evaluation context.
* @ctx: Supplies a pointer to the context to be populdated.
@@ -70,15 +89,89 @@ void build_eval_ctx(struct ipe_eval_ctx *ctx,
const struct file *file,
enum ipe_op_type op)
{
+ struct inode *ino = NULL;
+
if (op == __IPE_OP_EXEC && file)
pin_sb(FILE_SUPERBLOCK(file));

ctx->file = file;
ctx->op = op;

- if (file)
+ if (file) {
ctx->from_init_sb = from_pinned(FILE_SUPERBLOCK(file));
+ ino = d_real_inode(file->f_path.dentry);
+ build_ipe_bdev_ctx(ctx, ino);
+ }
+}
+
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+/**
+ * evaluate_dmv_roothash - Evaluate @ctx against a dmv roothash property.
+ * @ctx: Supplies a pointer to the context being evaluated.
+ * @p: Supplies a pointer to the property being evaluated.
+ *
+ * Return:
+ * * true - The current @ctx match the @p
+ * * false - The current @ctx doesn't match the @p
+ */
+static bool evaluate_dmv_roothash(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return !!ctx->ipe_bdev &&
+ ipe_digest_eval(p->value,
+ ctx->ipe_bdev->digest,
+ ctx->ipe_bdev->digest_len,
+ ctx->ipe_bdev->digest_algo);
+}
+
+/**
+ * evaluate_dmv_sig_false: Analyze @ctx against a dmv sig false property.
+ * @ctx: Supplies a pointer to the context being evaluated.
+ * @p: Supplies a pointer to the property being evaluated.
+ *
+ * Return:
+ * * true - The current @ctx match the @p
+ * * false - The current @ctx doesn't match the @p
+ */
+static bool evaluate_dmv_sig_false(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return !ctx->ipe_bdev || (!ctx->ipe_bdev->dm_verity_signed);
+}
+
+/**
+ * evaluate_dmv_sig_true: Analyze @ctx against a dmv sig true property.
+ * @ctx: Supplies a pointer to the context being evaluated.
+ * @p: Supplies a pointer to the property being evaluated.
+ *
+ * Return:
+ * * true - The current @ctx match the @p
+ * * false - The current @ctx doesn't match the @p
+ */
+static bool evaluate_dmv_sig_true(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return ctx->ipe_bdev && (!!ctx->ipe_bdev->dm_verity_signed);
+}
+#else
+static bool evaluate_dmv_roothash(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return false;
+}
+
+static bool evaluate_dmv_sig_false(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return false;
+}
+
+static bool evaluate_dmv_sig_true(const struct ipe_eval_ctx *const ctx,
+ struct ipe_prop *p)
+{
+ return false;
}
+#endif /* CONFIG_IPE_PROP_DM_VERITY */

/**
* evaluate_property - Analyze @ctx against a property.
@@ -97,6 +190,12 @@ static bool evaluate_property(const struct ipe_eval_ctx *const ctx,
return !ctx->from_init_sb;
case __IPE_PROP_BOOT_VERIFIED_TRUE:
return ctx->from_init_sb;
+ case __IPE_PROP_DMV_ROOTHASH:
+ return evaluate_dmv_roothash(ctx, p);
+ case __IPE_PROP_DMV_SIG_FALSE:
+ return evaluate_dmv_sig_false(ctx, p);
+ case __IPE_PROP_DMV_SIG_TRUE:
+ return evaluate_dmv_sig_true(ctx, p);
default:
return false;
}
diff --git a/security/ipe/eval.h b/security/ipe/eval.h
index 15c35921fd4d..746e58b79f2a 100644
--- a/security/ipe/eval.h
+++ b/security/ipe/eval.h
@@ -16,11 +16,24 @@ extern struct ipe_policy __rcu *ipe_active_policy;
extern bool success_audit;
extern bool enforce;

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+struct ipe_bdev {
+ bool dm_verity_signed;
+
+ const u8 *digest;
+ size_t digest_len;
+ const char *digest_algo;
+};
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
struct ipe_eval_ctx {
enum ipe_op_type op;

const struct file *file;
bool from_init_sb;
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+ const struct ipe_bdev *ipe_bdev;
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
};

enum ipe_match {
diff --git a/security/ipe/hooks.c b/security/ipe/hooks.c
index 6f94f5c8a0c3..9651e582791e 100644
--- a/security/ipe/hooks.c
+++ b/security/ipe/hooks.c
@@ -7,6 +7,9 @@
#include <linux/types.h>
#include <linux/binfmts.h>
#include <linux/mman.h>
+#include <linux/blk_types.h>
+#include <linux/dm-verity.h>
+#include <crypto/hash_info.h>

#include "ipe.h"
#include "hooks.h"
@@ -192,3 +195,51 @@ void ipe_sb_free_security(struct super_block *mnt_sb)
{
ipe_invalidate_pinned_sb(mnt_sb);
}
+
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+/**
+ * ipe_bdev_free_security - free IPE's LSM blob of block_devices.
+ * @bdev: Supplies a pointer to a block_device that contains the structure
+ * to free.
+ */
+void ipe_bdev_free_security(struct block_device *bdev)
+{
+ struct ipe_bdev *blob = ipe_bdev(bdev);
+
+ kfree(blob->digest);
+ kfree(blob->digest_algo);
+}
+
+/**
+ * ipe_bdev_setsecurity - save data from a bdev to IPE's LSM blob.
+ * @bdev: Supplies a pointer to a block_device that contains the LSM blob.
+ * @key: Supplies the string key that uniquely identifies the value.
+ * @value: Supplies the value to store.
+ * @len: The length of @value.
+ */
+int ipe_bdev_setsecurity(struct block_device *bdev, const char *key,
+ const void *value, size_t len)
+{
+ struct ipe_bdev *blob = ipe_bdev(bdev);
+
+ if (!strcmp(key, DM_VERITY_ROOTHASH_SEC_NAME)) {
+ const struct dm_verity_digest *digest = value;
+
+ blob->digest = kmemdup(digest->digest, digest->digest_len, GFP_KERNEL);
+ if (!blob->digest)
+ return -ENOMEM;
+
+ blob->digest_algo = kstrdup_const(digest->algo, GFP_KERNEL);
+ if (!blob->digest_algo)
+ return -ENOMEM;
+
+ blob->digest_len = digest->digest_len;
+ return 0;
+ } else if (!strcmp(key, DM_VERITY_SIGNATURE_SEC_NAME)) {
+ blob->dm_verity_signed = true;
+ return 0;
+ }
+
+ return -EOPNOTSUPP;
+}
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
diff --git a/security/ipe/hooks.h b/security/ipe/hooks.h
index ac0cdfd9877f..1d1d30b61f3e 100644
--- a/security/ipe/hooks.h
+++ b/security/ipe/hooks.h
@@ -8,6 +8,7 @@
#include <linux/fs.h>
#include <linux/binfmts.h>
#include <linux/security.h>
+#include <linux/device-mapper.h>

int ipe_bprm_check_security(struct linux_binprm *bprm);

@@ -24,4 +25,11 @@ int ipe_kernel_load_data(enum kernel_load_data_id id, bool contents);

void ipe_sb_free_security(struct super_block *mnt_sb);

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+void ipe_bdev_free_security(struct block_device *bdev);
+
+int ipe_bdev_setsecurity(struct block_device *bdev, const char *key,
+ const void *value, size_t len);
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
#endif /* _IPE_HOOKS_H */
diff --git a/security/ipe/ipe.c b/security/ipe/ipe.c
index 6f063d51b2af..fa2dcb9fde62 100644
--- a/security/ipe/ipe.c
+++ b/security/ipe/ipe.c
@@ -5,12 +5,23 @@

#include "ipe.h"
#include "hooks.h"
+#include "eval.h"

bool ipe_enabled;

static struct lsm_blob_sizes ipe_blobs __ro_after_init = {
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+ .lbs_bdev = sizeof(struct ipe_bdev),
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
};

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+struct ipe_bdev *ipe_bdev(struct block_device *b)
+{
+ return b->security + ipe_blobs.lbs_bdev;
+}
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
static struct security_hook_list ipe_hooks[] __ro_after_init = {
LSM_HOOK_INIT(bprm_check_security, ipe_bprm_check_security),
LSM_HOOK_INIT(mmap_file, ipe_mmap_file),
@@ -18,6 +29,10 @@ static struct security_hook_list ipe_hooks[] __ro_after_init = {
LSM_HOOK_INIT(kernel_read_file, ipe_kernel_read_file),
LSM_HOOK_INIT(kernel_load_data, ipe_kernel_load_data),
LSM_HOOK_INIT(sb_free_security, ipe_sb_free_security),
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+ LSM_HOOK_INIT(bdev_free_security, ipe_bdev_free_security),
+ LSM_HOOK_INIT(bdev_setsecurity, ipe_bdev_setsecurity),
+#endif
};

/**
diff --git a/security/ipe/ipe.h b/security/ipe/ipe.h
index 6dec06403eee..4e8d1a440c4b 100644
--- a/security/ipe/ipe.h
+++ b/security/ipe/ipe.h
@@ -15,4 +15,8 @@

extern bool ipe_enabled;

+#ifdef CONFIG_IPE_PROP_DM_VERITY
+struct ipe_bdev *ipe_bdev(struct block_device *b);
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
+
#endif /* _IPE_H */
diff --git a/security/ipe/policy.h b/security/ipe/policy.h
index 94bcbbf79b05..42059039bb3d 100644
--- a/security/ipe/policy.h
+++ b/security/ipe/policy.h
@@ -33,6 +33,9 @@ enum ipe_action_type {
enum ipe_prop_type {
__IPE_PROP_BOOT_VERIFIED_FALSE,
__IPE_PROP_BOOT_VERIFIED_TRUE,
+ __IPE_PROP_DMV_ROOTHASH,
+ __IPE_PROP_DMV_SIG_FALSE,
+ __IPE_PROP_DMV_SIG_TRUE,
__IPE_PROP_MAX
};

diff --git a/security/ipe/policy_parser.c b/security/ipe/policy_parser.c
index 28c14adfe6d2..cb87bc3d67fc 100644
--- a/security/ipe/policy_parser.c
+++ b/security/ipe/policy_parser.c
@@ -8,6 +8,7 @@

#include "policy.h"
#include "policy_parser.h"
+#include "digest.h"

#define START_COMMENT '#'

@@ -216,6 +217,7 @@ static void free_rule(struct ipe_rule *r)

list_for_each_entry_safe(p, t, &r->props, next) {
list_del(&p->next);
+ ipe_digest_free(&p->value);
kfree(p);
}

@@ -268,6 +270,11 @@ static enum ipe_action_type parse_action(char *t)
static const match_table_t property_tokens = {
{__IPE_PROP_BOOT_VERIFIED_FALSE, "boot_verified=FALSE"},
{__IPE_PROP_BOOT_VERIFIED_TRUE, "boot_verified=TRUE"},
+#ifdef CONFIG_IPE_PROP_DM_VERITY
+ {__IPE_PROP_DMV_ROOTHASH, "dmverity_roothash=%s"},
+ {__IPE_PROP_DMV_SIG_FALSE, "dmverity_signature=FALSE"},
+ {__IPE_PROP_DMV_SIG_TRUE, "dmverity_signature=TRUE"},
+#endif /* CONFIG_IPE_PROP_DM_VERITY */
{__IPE_PROP_INVALID, NULL}
};

@@ -287,6 +294,7 @@ static int parse_property(char *t, struct ipe_rule *r)
struct ipe_prop *p = NULL;
int rc = 0;
int token;
+ char *dup = NULL;

p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p)
@@ -295,8 +303,20 @@ static int parse_property(char *t, struct ipe_rule *r)
token = match_token(t, property_tokens, args);

switch (token) {
+ case __IPE_PROP_DMV_ROOTHASH:
+ dup = match_strdup(&args[0]);
+ if (!dup) {
+ rc = -ENOMEM;
+ goto err;
+ }
+ rc = ipe_digest_parse(dup, &p->value);
+ if (rc)
+ goto err;
+ fallthrough;
case __IPE_PROP_BOOT_VERIFIED_FALSE:
case __IPE_PROP_BOOT_VERIFIED_TRUE:
+ case __IPE_PROP_DMV_SIG_FALSE:
+ case __IPE_PROP_DMV_SIG_TRUE:
p->type = token;
break;
case __IPE_PROP_INVALID:
@@ -309,6 +329,7 @@ static int parse_property(char *t, struct ipe_rule *r)
list_add_tail(&p->next, &r->props);

out:
+ kfree(dup);
return rc;
err:
kfree(p);
--
2.25.1


2023-06-28 21:21:57

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 17/17] documentation: add ipe documentation

From: Deven Bowers <[email protected]>

Add IPE's admin and developer documentation to the kernel tree.

Co-developed-by: Fan Wu <[email protected]>
Signed-off-by: Deven Bowers <[email protected]>
Signed-off-by: Fan Wu <[email protected]>
---
v2:
+ No Changes

v3:
+ Add Acked-by
+ Fixup code block syntax
+ Fix a minor grammatical issue.

v4:
+ Update documentation with the results of other
code changes.

v5:
+ No changes

v6:
+ No changes

v7:
+ Add additional developer-level documentation
+ Update admin-guide docs to reflect changes.
+ Drop Acked-by due to significant changes
+ Added section about audit events in admin-guide

v8:
+ Correct terminology from "audit event" to "audit record"
+ Add associated documentation with the correct "audit event"
terminology.
+ Add some context to the historical motivation for IPE and design
philosophy.
+ Add some content about the securityfs layout in the policies
directory.
+ Various spelling and grammatical corrections.

v9:
+ Correct spelling of "pitfalls"
+ Update the docs w.r.t the new parser and new audit formats

v10:
+ Refine user docs per upstream suggetions
+ Update audit events part
---
Documentation/admin-guide/LSM/index.rst | 1 +
Documentation/admin-guide/LSM/ipe.rst | 752 ++++++++++++++++++
.../admin-guide/kernel-parameters.txt | 12 +
Documentation/security/index.rst | 1 +
Documentation/security/ipe.rst | 420 ++++++++++
MAINTAINERS | 2 +
6 files changed, 1188 insertions(+)
create mode 100644 Documentation/admin-guide/LSM/ipe.rst
create mode 100644 Documentation/security/ipe.rst

diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst
index a6ba95fbaa9f..ce63be6d64ad 100644
--- a/Documentation/admin-guide/LSM/index.rst
+++ b/Documentation/admin-guide/LSM/index.rst
@@ -47,3 +47,4 @@ subdirectories.
tomoyo
Yama
SafeSetID
+ ipe
diff --git a/Documentation/admin-guide/LSM/ipe.rst b/Documentation/admin-guide/LSM/ipe.rst
new file mode 100644
index 000000000000..da59f78427fa
--- /dev/null
+++ b/Documentation/admin-guide/LSM/ipe.rst
@@ -0,0 +1,752 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Integrity Policy Enforcement (IPE)
+==================================
+
+.. NOTE::
+
+ This is the documentation for admins, system builders, or individuals
+ attempting to use IPE. If you're looking for more developer-focused
+ documentation about IPE please see `Documentation/security/ipe.rst`
+
+Overview
+--------
+
+IPE is a Linux Security Module which takes a complimentary approach to
+access control. Whereas existing mandatory access control mechanisms
+base their decisions on labels and paths, IPE instead determines
+whether or not an operation should be allowed based on immutable
+security properties of the system component the operation is being
+performed on.
+
+IPE itself does not mandate how the security property should be
+evaluated, but relies on an extensible set of external property providers
+to evaluate the component. IPE makes its decision based on reference
+values for the selected properties, specified in the IPE policy.
+
+The reference values represent the value that the policy writer and the
+local system administrator (based on the policy signature) trust for the
+system to accomplish the desired tasks.
+
+One such provider is for example dm-verity, which is able to represent
+the integrity property of a partition (its immutable state) with a digest.
+
+To enable IPE, ensure that ``CONFIG_SECURITY_IPE`` (under
+:menuselection:`Security -> Integrity Policy Enforcement (IPE)`) config
+option is enabled.
+
+Use Cases
+---------
+
+IPE works best in fixed-function devices: devices in which their purpose
+is clearly defined and not supposed to be changed (e.g. network firewall
+device in a data center, an IoT device, etcetera), where all software and
+configuration is built and provisioned by the system owner.
+
+IPE is a long-way off for use in general-purpose computing: the Linux
+community as a whole tends to follow a decentralized trust model (known as
+the web of trust), which IPE has no support for it yet. Instead, IPE
+supports PKI (public key infrastructure), which generally designates a
+set of trusted entities that provide a measure of absolute trust.
+
+Additionally, while most packages are signed today, the files inside
+the packages (for instance, the executables), tend to be unsigned. This
+makes it difficult to utilize IPE in systems where a package manager is
+expected to be functional, without major changes to the package manager
+and ecosystem behind it.
+
+DIGLIM [#diglim]_ is a system that when combined with IPE, could be used to
+enable and support general-purpose computing use cases.
+
+Known Limitations
+-----------------
+
+IPE cannot verify the integrity of anonymous executable memory, such as
+the trampolines created by gcc closures and libffi (<3.4.2), or JIT'd code.
+Unfortunately, as this is dynamically generated code, there is no way
+for IPE to ensure the integrity of this code to form a trust basis. In all
+cases, the return result for these operations will be whatever the admin
+configures as the ``DEFAULT`` action for ``EXECUTE``.
+
+IPE cannot verify the integrity of programs written in interpreted
+languages when these scripts are invoked by passing these program files
+to the interpreter. This is because the way interpreters execute these
+files; the scripts themselves are not evaluated as executable code
+through one of IPE's hooks, but they are merely text files that are read
+(as opposed to compiled executables) [#interpreters]_.
+
+Threat Model
+------------
+
+The threat type addressed by IPE is tampering of executable userspace
+code beyond the initially booted kernel, and the initial verification of
+kernel modules that are loaded in userspace through ``modprobe`` or
+``insmod``.
+
+A bare-minimum example of a threat that should be mitigated by IPE, is
+an untrusted (potentially malicious) binary that is downloaded and
+bundled with all required dependencies (including a loader, libc, etc).
+With IPE, this binary should not be allowed to be executed, not even any
+of its dependencies.
+
+Tampering violates integrity, yet lack of trust is caused by being
+unable to detect tampering (and by extent verifying the integrity).
+IPE's role in mitigating this threat is to verify the integrity (and
+authenticity) of all executable code and to deny their use if they
+cannot be trusted (as integrity verification fails, or the authorization
+check fails against the reference value in the policy). IPE generates
+audit logs which may be utilized to detect and analyze failures
+resulting from policy violation.
+
+Tampering threat scenarios include modification or replacement of
+executable code by a range of actors including:
+
+- Actors with physical access to the hardware
+- Actors with local network access to the system
+- Actors with access to the deployment system
+- Compromised internal systems under external control
+- Malicious end users of the system
+- Compromised end users of the system
+- Remote (external) compromise of the system
+
+IPE does not mitigate threats arising from malicious but authorized
+developers (with access to a signing certificate), or compromised
+developer tools used by them (i.e. return-oriented programming attacks).
+Additionally, IPE draws hard security boundary between userspace and
+kernelspace. As a result, IPE does not provide any protections against a
+kernel level exploit, and a kernel-level exploit can disable or tamper
+with IPE's protections.
+
+Policy
+------
+
+IPE policy is a plain-text [#devdoc]_ policy composed of multiple statements
+over several lines. There is one required line, at the top of the
+policy, indicating the policy name, and the policy version, for
+instance::
+
+ policy_name=Ex_Policy policy_version=0.0.0
+
+The policy name is a unique key identifying this policy in a human
+readable name. This is used to create nodes under securityfs as well as
+uniquely identify policies to deploy new policies vs update existing
+policies.
+
+The policy version indicates the current version of the policy (NOT the
+policy syntax version). This is used to prevent rollback of policy to
+potentially insecure previous versions of the policy.
+
+The next portion of IPE policy are rules. Rules are formed by key=value
+pairs, known as properties. IPE rules require two properties: ``action``,
+which determines what IPE does when it encounters a match against the
+rule, and ``op``, which determines when the rule should be evaluated.
+The ordering is significant, a rule must start with ``op``, and end with
+``action``. Thus, a minimal rule is::
+
+ op=EXECUTE action=ALLOW
+
+This example will allow any execution. Additional properties are used to
+restrict attributes about the files being evaluated. These properties
+are intended to be descriptions of systems within the kernel that can
+provide a measure of integrity verification, such that IPE can determine
+the trust of the resource based on the value of the property.
+
+Rules are evaluated top-to-bottom. As a result, any revocation rules,
+or denies should be placed early in the file to ensure that these rules
+are evaluated before a rule with ``action=ALLOW``.
+
+IPE policy supports comments. The character '#' will function as a
+comment, ignoring all characters to the right of '#' until the newline.
+
+The default behavior of IPE evaluations can also be expressed in policy,
+through the ``DEFAULT`` statement. This can be done at a global level,
+or a per-operation level::
+
+ # Global
+ DEFAULT action=ALLOW
+
+ # Operation Specific
+ DEFAULT op=EXECUTE action=ALLOW
+
+A default must be set for all known operations in IPE. If you want to
+preserve older policies being compatible with newer kernels that can introduce
+new operations, set a global default of ``ALLOW``, then override the
+defaults on a per-operation basis (as above).
+
+With configurable policy-based LSMs, there's several issues with
+enforcing the configurable policies at startup, around reading and
+parsing the policy:
+
+1. The kernel *should* not read files from userspace, so directly reading
+ the policy file is prohibited.
+2. The kernel command line has a character limit, and one kernel module
+ should not reserve the entire character limit for its own
+ configuration.
+3. There are various boot loaders in the kernel ecosystem, so handing
+ off a memory block would be costly to maintain.
+
+As a result, IPE has addressed this problem through a concept of a "boot
+policy". A boot policy is a minimal policy which is compiled into the
+kernel. This policy is intended to get the system to a state where
+userspace is set up and ready to receive commands, at which point a more
+complex policy can be deployed via securityfs. The boot policy can be
+specified via ``SECURITY_IPE_BOOT_POLICY`` config option, which accepts
+a path to a plain-text version of the IPE policy to apply. This policy
+will be compiled into the kernel. If not specified, IPE will be disabled
+until a policy is deployed and activated through securityfs.
+
+Deploying Policies
+~~~~~~~~~~~~~~~~~~
+
+Policies can be deployed from userspace through securityfs. These policies
+are signed through the PKCS#7 message format to enforce some level of
+authorization of the policies (prohibiting an attacker from gaining
+unconstrained root, and deploying an "allow all" policy). These
+policies must be signed by a certificate that chains to the
+``SYSTEM_TRUSTED_KEYRING``. With openssl, the policy can be signed by::
+
+ openssl smime -sign \
+ -in "$MY_POLICY" \
+ -signer "$MY_CERTIFICATE" \
+ -inkey "$MY_PRIVATE_KEY" \
+ -noattr \
+ -nodetach \
+ -nosmimecap \
+ -outform der \
+ -out "$MY_POLICY.p7b"
+
+Deploying the policies is done through securityfs, through the
+``new_policy`` node. To deploy a policy, simply cat the file into the
+securityfs node::
+
+ cat "$MY_POLICY.p7b" > /sys/kernel/security/ipe/new_policy
+
+Upon success, this will create one subdirectory under
+``/sys/kernel/security/ipe/policies/``. The subdirectory will be the
+``policy_name`` field of the policy deployed, so for the example above,
+the directory will be ``/sys/kernel/security/ipe/policies/Ex_Policy``.
+Within this directory, there will be five files: ``pkcs7``, ``policy``,
+``active``, ``update``, and ``delete``.
+
+The ``pkcs7`` file is read-only. Reading it returns the raw PKCS#7 data
+that was provided to the kernel, representing the policy. If the policy being
+read is the boot policy, this will return ``ENOENT``, as it is not signed.
+
+The ``policy`` file is read only. Reading it returns the PKCS#7 inner
+content of the policy, which will be the plain text policy.
+
+The ``active`` file is used to set a policy as the currently active policy.
+This file is rw, and accepts a value of ``"1"`` to set the policy as active.
+Since only a single policy can be active at one time, all other policies
+will be marked inactive. The policy being marked active must have a policy
+version greater or equal to the currently-running version.
+
+The ``update`` file is used to update a policy that is already present
+in the kernel. This file is write-only and accepts a PKCS#7 signed
+policy. Two checks will always be performed on this policy: First, the
+``policy_names`` must match with the updated version and the existing
+version. Second the updated policy must have a policy version greater than
+or equal to the currently-running version. This is to prevent rollback attacks.
+
+The ``delete`` file is used to remove a policy that is no longer needed.
+This file is write-only and accepts a value of ``1`` to delete the policy.
+On deletion, the securityfs node representing the policy will be removed.
+However, delete the current active policy is not allowed and will return
+an operation not permitted error.
+
+Similarly, writing to both ``update`` and ``new_policy`` could result in
+bad message(policy syntax error) or file exists error. The latter error happens
+when trying to deploy a policy with a ``policy_name`` while the kernel already
+has a deployed policy with the same ``policy_name``.
+
+Deploying a policy will *not* cause IPE to start enforcing the policy. IPE will
+only enforce the policy marked active. Note that only one policy can be active
+at a time.
+
+Once deployment is successful, the policy can be activated, by writing file
+``/sys/kernel/security/ipe/$policy_name/active``.
+For example, the ``Ex_Policy`` can be activated by::
+
+ echo 1 > "/sys/kernel/security/ipe/Ex_Policy/active"
+
+From above point on, ``Ex_Policy`` is now the enforced policy on the
+system.
+
+IPE also provides a way to delete policies. This can be done via the
+``delete`` securityfs node, ``/sys/kernel/security/ipe/$policy_name/delete``.
+Writing ``1`` to that file deletes the policy::
+
+ echo 1 > "/sys/kernel/security/ipe/$policy_name/delete"
+
+There is only one requirement to delete a policy: the policy being deleted
+must be inactive.
+
+.. NOTE::
+
+ If a traditional MAC system is enabled (SELinux, apparmor, smack), all
+ writes to ipe's securityfs nodes require ``CAP_MAC_ADMIN``.
+
+Modes
+~~~~~
+
+IPE supports two modes of operation: permissive (similar to SELinux's
+permissive mode) and enforced. In permissive mode, all events are
+checked and policy violations are logged, but the policy is not really
+enforced. This allows users to test policies before enforcing them.
+
+The default mode is enforce, and can be changed via the kernel command
+line parameter ``ipe.enforce=(0|1)``, or the securityfs node
+``/sys/kernel/security/ipe/enforce``.
+
+.. NOTE::
+
+ If a traditional MAC system is enabled (SELinux, apparmor, smack, etcetera),
+ all writes to ipe's securityfs nodes require ``CAP_MAC_ADMIN``.
+
+Audit Events
+~~~~~~~~~~~~
+
+1420 AUDIT_IPE_ACCESS
+^^^^^^^^^^^^^^^^^^^^^
+Event Examples::
+
+ type=1420 audit(1653364370.067:61): path="/root/fs/rw/plain/execve" dev="vdc1" ino=16 rule="DEFAULT op=EXECUTE action=DENY"
+ type=1300 audit(1653364370.067:61): arch=c000003e syscall=10 success=no exit=-13 a0=7f0bf0644000 a1=4f80 a2=5 a3=7f0bf043d300 items=0 ppid=455 pid=737 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=ttyS0 ses=3 comm="mprotect" exe="/root/host/mprotect" subj=kernel key=(null)
+ type=1327 audit(1653364370.067:61): proctitle=686F73742F6D70726F7465637400534800527C5700527C5800706C61696E2F657865637665
+
+ type=1420 audit(1653364735.161:64): rule="DEFAULT op=EXECUTE action=DENY"
+ type=1300 audit(1653364735.161:64): arch=c000003e syscall=9 success=no exit=-13 a0=0 a1=1000 a2=4 a3=20 items=0 ppid=455 pid=774 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=ttyS0 ses=3 comm="mmap" exe="/root/host/mmap" subj=kernel key=(null)
+ type=1327 audit(1653364735.161:64): proctitle=686F73742F6D6D617000410058⏎
+
+This event indicates that IPE made an access control decision; the IPE
+specific record (1420) is always emitted in conjunction with a
+``AUDITSYSCALL`` record.
+
+Determining whether IPE is in permissive or enforced mode can be derived
+from ``success`` property and exit code of the ``AUDITSYSCALL`` record.
+
+
+Field descriptions:
+
++-------+------------+-----------+-------------------------------------------------+
+| Field | Value Type | Optional? | Description of Value |
++=======+============+===========+=================================================+
+| path | string | Yes | The absolute path to the evaluated file |
++-------+------------+-----------+-------------------------------------------------+
+| ino | integer | Yes | The inode number of the evaluated file |
++-------+------------+-----------+-------------------------------------------------+
+| dev | string | Yes | The device name of the evaluated file, e.g. vda |
++-------+------------+-----------+-------------------------------------------------+
+| rule | string | No | The matched policy rule |
++-------+------------+-----------+-------------------------------------------------+
+
+1421 AUDIT_IPE_CONFIG_CHANGE
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Event Example::
+
+ type=1421 audit(1653425583.136:54): old_active_pol_name="Allow_All" old_active_pol_version=0.0.0 old_policy_digest=sha256:E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 new_active_pol_name="boot_verified" new_active_pol_version=0.0.0 new_policy_digest=sha256:820EEA5B40CA42B51F68962354BA083122A20BB846F26765076DD8EED7B8F4DB auid=4294967295 ses=4294967295 lsm=ipe res=1
+ type=1300 audit(1653425583.136:54): SYSCALL arch=c000003e syscall=1 success=yes exit=2 a0=3 a1=5596fcae1fb0 a2=2 a3=2 items=0 ppid=184 pid=229 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=4294967295 comm="python3" exe="/usr/bin/python3.10" key=(null)
+ type=1327 audit(1653425583.136:54): PROCTITLE proctitle=707974686F6E3300746573742F6D61696E2E7079002D66002E2
+
+This event indicates that IPE switched the active poliy from one to another
+along with the version and the hash digest of the two policies.
+Note IPE can only have one policy active at a time, all access decision
+evaluation is based on the current active policy.
+The normal procedure to deploy a new policy is loading the policy to deploy
+into the kernel first, then switch the active policy to it.
+
+This record will always be emitted in conjunction with a ``AUDITSYSCALL`` record for the ``write`` syscall.
+
++------------------------+------------+-----------+---------------------------------------------------+
+| Field | Value Type | Optional? | Description of Value |
++========================+============+===========+===================================================+
+| old_active_pol_name | string | No | The name of previous active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| old_active_pol_version | string | No | The version of previous active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| old_policy_digest | string | No | The hash of previous active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| new_active_pol_name | string | No | The name of current active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| new_active_pol_version | string | No | The version of current active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| new_policy_digest | string | No | The hash of current active policy |
++------------------------+------------+-----------+---------------------------------------------------+
+| auid | integer | No | The login user ID |
++------------------------+------------+-----------+---------------------------------------------------+
+| ses | integer | No | The login session ID |
++------------------------+------------+-----------+---------------------------------------------------+
+| lsm | string | No | The lsm name associated with the event |
++------------------------+------------+-----------+---------------------------------------------------+
+| res | integer | No | The result of the audited operation(success/fail) |
++------------------------+------------+-----------+---------------------------------------------------+
+
+1422 AUDIT_IPE_POLICY_LOAD
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Event Example::
+
+ type=1422 audit(1653425529.927:53): policy_name="boot_verified" policy_version=0.0.0 policy_digest=sha256:820EEA5B40CA42B51F68962354BA083122A20BB846F26765076DD8EED7B8F4DB auid=4294967295 ses=4294967295 lsm=ipe res=1
+ type=1300 audit(1653425529.927:53): arch=c000003e syscall=1 success=yes exit=2567 a0=3 a1=5596fcae1fb0 a2=a07 a3=2 items=0 ppid=184 pid=229 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=4294967295 comm="python3" exe="/usr/bin/python3.10" key=(null)
+ type=1327 audit(1653425529.927:53): PROCTITLE proctitle=707974686F6E3300746573742F6D61696E2E7079002D66002E2E
+
+This record indicates a new policy has been loaded into the kernel with the policy name, policy version and policy hash.
+
+This record will always be emitted in conjunction with a ``AUDITSYSCALL`` record for the ``write`` syscall.
+
++----------------+------------+-----------+---------------------------------------------------+
+| Field | Value Type | Optional? | Description of Value |
++================+============+===========+===================================================+
+| policy_name | string | No | The policy_name |
++----------------+------------+-----------+---------------------------------------------------+
+| policy_version | string | No | The policy_version |
++----------------+------------+-----------+---------------------------------------------------+
+| policy_digest | string | No | The policy hash |
++----------------+------------+-----------+---------------------------------------------------+
+| auid | integer | No | The login user ID |
++----------------+------------+-----------+---------------------------------------------------+
+| ses | integer | No | The login session ID |
++----------------+------------+-----------+---------------------------------------------------+
+| lsm | string | No | The lsm name associated with the event |
++----------------+------------+-----------+---------------------------------------------------+
+| res | integer | No | The result of the audited operation(success/fail) |
++----------------+------------+-----------+---------------------------------------------------+
+
+
+1404 AUDIT_MAC_STATUS
+^^^^^^^^^^^^^^^^^^^^^
+
+Event Examples::
+
+ type=1404 audit(1653425689.008:55): enforcing=0 old_enforcing=1 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1
+ type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=)
+ type=1327 audit(1653425689.008:55): proctitle="-bash"
+
+ type=1404 audit(1653425689.008:55): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1
+ type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=)
+ type=1327 audit(1653425689.008:55): proctitle="-bash"
+
+This record will always be emitted in conjunction with a ``AUDITSYSCALL`` record for the ``write`` syscall.
+
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| Field | Value Type | Optional? | Description of Value | |
++===============+============+===========+=================================================================================================+=====+
+| enforcing | integer | No | The enforcing state IPE is being switched to, 1 is in enforcing mode, 0 is in permissive mode | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| old_enforcing | integer | No | The enforcing state IPE is being switched from, 1 is in enforcing mode, 0 is in permissive mode | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| auid | integer | No | The login user ID | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| ses | integer | No | The login session ID | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| enabled | integer | No | The new TTY audit enabled setting | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| old-enabled | integer | No | The old TTY audit enabled setting | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| lsm | string | No | The lsm name associated with the event | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+| res | integer | No | The result of the audited operation(success/fail) | |
++---------------+------------+-----------+-------------------------------------------------------------------------------------------------+-----+
+
+Success Auditing
+^^^^^^^^^^^^^^^^
+
+IPE supports success auditing. When enabled, all events that pass IPE
+policy and are not blocked will emit an audit event. This is disabled by
+default, and can be enabled via the kernel command line
+``ipe.success_audit=(0|1)`` or
+``/sys/kernel/security/ipe/success_audit`` securityfs file.
+
+This is *very* noisy, as IPE will check every userspace binary on the
+system, but is useful for debugging policies.
+
+.. NOTE::
+
+ If a traditional MAC system is enabled (SELinux, apparmor, smack, etcetera),
+ all writes to ipe's securityfs nodes require ``CAP_MAC_ADMIN``.
+
+Properties
+----------
+
+As explained above, IPE properties are ``key=value`` pairs expressed in
+IPE policy. Two properties are built-into the policy parser: 'op' and
+'action'. The other properties are deterministic attributes to express
+across files. Currently those properties are: '``boot_verified``',
+'``dmverity_signature``', '``dmverity_roothash``', '``fsverity_signature``',
+'``fsverity_digest``'. A description of all properties supported by IPE
+are listed below:
+
+op
+~~
+
+Indicates the operation for a rule to apply to. Must be in every rule,
+as the first token. IPE supports the following operations:
+
+ ``EXECUTE``
+
+ Pertains to any file attempting to be executed, or loaded as an
+ executable.
+
+ ``FIRMWARE``:
+
+ Pertains to firmware being loaded via the firmware_class interface.
+ This covers both the preallocated buffer and the firmware file
+ itself.
+
+ ``KMODULE``:
+
+ Pertains to loading kernel modules via ``modprobe`` or ``insmod``.
+
+ ``KEXEC_IMAGE``:
+
+ Pertains to kernel images loading via ``kexec``.
+
+ ``KEXEC_INITRAMFS``
+
+ Pertains to initrd images loading via ``kexec --initrd``.
+
+ ``POLICY``:
+
+ Controls loading policies via reading a kernel-space initiated read.
+
+ An example of such is loading IMA policies by writing the path
+ to the policy file to ``$securityfs/ima/policy``
+
+ ``X509_CERT``:
+
+ Controls loading IMA certificates through the Kconfigs,
+ ``CONFIG_IMA_X509_PATH`` and ``CONFIG_EVM_X509_PATH``.
+
+action
+~~~~~~
+
+ Determines what IPE should do when a rule matches. Must be in every
+ rule, as the final clause. Can be one of:
+
+ ``ALLOW``:
+
+ If the rule matches, explicitly allow access to the resource to proceed
+ without executing any more rules.
+
+ ``DENY``:
+
+ If the rule matches, explicitly prohibit access to the resource to
+ proceed without executing any more rules.
+
+boot_verified
+~~~~~~~~~~~~~
+
+ This property can be utilized for authorization of the first super-block
+ that executes a file. This is almost always init. Typically this is used
+ for systems with an initramfs or other initial disk, where this is unmounted
+ before the system becomes available, and is not covered by any other property.
+ The format of this property is::
+
+ boot_verified=(TRUE|FALSE)
+
+
+ .. WARNING::
+
+ This property will trust any disk where the first execution evaluation
+ occurs. If you do *NOT* have a startup disk that is unpacked and unmounted
+ (like initramfs), then it will automatically trust the root filesystem and
+ potentially overauthorize the entire disk.
+
+dmverity_roothash
+~~~~~~~~~~~~~~~~~
+
+ This property can be utilized for authorization or revocation of
+ specific dm-verity volumes, identified via sroot hash. It has a
+ dependency on the DM_VERITY module. This property is controlled by
+ the ``IPE_PROP_DM_VERITY`` config option, it will be automatically
+ selected when ``IPE_SECURITY``, ``DM_VERITY `` and
+ ``DM_VERITY_VERIFY_ROOTHASH_SIG`` are all enabled.
+ The format of this property is::
+
+ dmverity_roothash=DigestName:HexadecimalString
+
+ The supported DigestNames for dmverity_roothash are [#dmveritydigests]_ [#securedigest]_ :
+
+ + blake2b-512
+ + blake2s-256
+ + sha1
+ + sha256
+ + sha384
+ + sha512
+ + sha3-224
+ + sha3-256
+ + sha3-384
+ + sha3-512
+ + md4
+ + md5
+ + sm3
+ + rmd160
+
+dmverity_signature
+~~~~~~~~~~~~~~~~~~
+
+ This property can be utilized for authorization of all dm-verity
+ volumes that have a signed roothash that chains to a keyring
+ specified by dm-verity's configuration, either the system trusted
+ keyring, or the secondary keyring. It depends on
+ ``DM_VERITY_VERIFY_ROOTHASH_SIG`` config option and is controlled by
+ the ``IPE_PROP_DM_VERITY`` config option, it will be automatically
+ selected when ``IPE_SECURITY``, ``DM_VERITY `` and
+ ``DM_VERITY_VERIFY_ROOTHASH_SIG`` are all enabled.
+ The format of this property is::
+
+ dmverity_signature=(TRUE|FALSE)
+
+fsverity_digest
+~~~~~~~~~~~~~~~
+
+ This property can be utilized for authorization or revocation of
+ specific fsverity enabled file, identified via its fsverity digest.
+ It depends on ``FS_VERITY`` config option and is controlled by
+ ``CONFIG_IPE_PROP_FS_VERITY``. The format of this property is::
+
+ fsverity_digest=DigestName:HexadecimalString
+
+ The supported DigestNames for dmverity_roothash are [#fsveritydigest] [#securedigest]_ :
+
+ + sha256
+ + sha512
+
+fsverity_signature
+~~~~~~~~~~~~~~~~~~
+
+ This property can be utilized for authorization of all fsverity
+ enabled files that is verified by fsverity. The keyring that the
+ signature is verified against is subject to fsverity's configuration,
+ typically the fsverity keyring. It depends on
+ ``CONFIG_FS_VERITY_BUILTIN_SIGNATURES`` and it is controlled by
+ the Kconfig ``CONFIG_IPE_PROP_FS_VERITY``. The format of this
+ property is::
+
+ fsverity_signature=(TRUE|FALSE)
+
+Policy Examples
+---------------
+
+Allow all
+~~~~~~~~~
+
+::
+
+ policy_name=Allow_All policy_version=0.0.0
+ DEFAULT action=ALLOW
+
+Allow only initial superblock
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=Allow_All_Initial_SB policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE boot_verified=TRUE action=ALLOW
+
+Allow any signed dm-verity volume and the initial superblock
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=AllowSignedAndInitial policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE boot_verified=TRUE action=ALLOW
+ op=EXECUTE dmverity_signature=TRUE action=ALLOW
+
+Prohibit execution from a specific dm-verity volume
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=AllowSignedAndInitial policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE dmverity_roothash=sha256:cd2c5bae7c6c579edaae4353049d58eb5f2e8be0244bf05345bc8e5ed257baff action=DENY
+
+ op=EXECUTE boot_verified=TRUE action=ALLOW
+ op=EXECUTE dmverity_signature=TRUE action=ALLOW
+
+Allow only a specific dm-verity volume
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=AllowSignedAndInitial policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE dmverity_roothash=sha256:401fcec5944823ae12f62726e8184407a5fa9599783f030dec146938 action=ALLOW
+
+Allow any signed fs-verity file
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=AllowSignedFSVerity policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE fsverity_signature=TRUE action=ALLOW
+
+Prohibit execution of a specific fs-verity file
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+ policy_name=ProhibitSpecificFSVF policy_version=0.0.0
+ DEFAULT action=DENY
+
+ op=EXECUTE fsverity_digest=sha256:fd88f2b8824e197f850bf4c5109bea5cf0ee38104f710843bb72da796ba5af9e action=DENY
+ op=EXECUTE boot_verified=TRUE action=ALLOW
+ op=EXECUTE dmverity_signature=TRUE action=ALLOW
+
+Additional Information
+----------------------
+
+- `Github Repository <https://github.com/microsoft/ipe>`_
+- `Design Documentation </security/ipe>`_
+
+FAQ
+---
+
+Q:
+ What's the difference between other LSMs which provide a measure of
+ trust-based access control?
+
+A:
+
+ In general, there's two other LSMs that can provide similar functionality:
+ IMA, and Loadpin.
+
+ IMA and IPE are functionally very similar. The significant difference between
+ the two is the policy. [#devdoc]_
+
+ Loadpin and IPE differ fairly dramatically, as Loadpin controls only the IPE
+ equivalent of ``KERNEL_READ``, whereas IPE is capable of controlling execution,
+ on top of ``KERNEL_READ``. The trust model is also different; Loadpin roots its
+ trust in the initial super-block, whereas trust in IPE is stemmed from kernel
+ itself (via ``SYSTEM_TRUSTED_KEYS``).
+
+-----------
+
+.. [#diglim] 1: https://lore.kernel.org/bpf/[email protected]/T/
+
+.. [#interpreters] There is `some interest in solving this issue <https://lore.kernel.org/lkml/[email protected]/>`_.
+
+.. [#devdoc] Please see `Documentation/security/ipe.rst` for more on this topic.
+
+.. [#fsveritydigest] These hash algorithms are based on values accepted by fsverity-utils;
+ IPE does not impose any restrictions on the digest algorithm itself;
+ thus, this list may be out of date.
+
+.. [#dmveritydigests] These hash algorithms are based on values accepted by dm-verity,
+ specifically ``crypto_alloc_ahash`` in ``verity_ctr``; ``veritysetup``
+ does support more algorithms than the list above. IPE does not impose
+ any restrictions on the digest algorithm itself; thus, this list
+ may be out of date.
+
+.. [#securedigest] Please ensure you are using cryptographically secure hash functions;
+ just because something is *supported* does not mean it is *secure*.
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index c5e7bb4babf0..78ddd3bbca4d 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -2219,6 +2219,18 @@
ipcmni_extend [KNL] Extend the maximum number of unique System V
IPC identifiers from 32,768 to 16,777,216.

+ ipe.enforce= [IPE]
+ Format: <bool>
+ Determine whether IPE starts in permissive (0) or
+ enforce (1) mode. The default is enforce.
+
+ ipe.success_audit=
+ [IPE]
+ Format: <bool>
+ Start IPE with success auditing enabled, emitting
+ an audit event when a binary is allowed. The default
+ is 0.
+
irqaffinity= [SMP] Set the default irq affinity mask
The argument is a cpu list, as described above.

diff --git a/Documentation/security/index.rst b/Documentation/security/index.rst
index 6ed8d2fa6f9e..a5248d4fd510 100644
--- a/Documentation/security/index.rst
+++ b/Documentation/security/index.rst
@@ -18,3 +18,4 @@ Security Documentation
digsig
landlock
secrets/index
+ ipe
diff --git a/Documentation/security/ipe.rst b/Documentation/security/ipe.rst
new file mode 100644
index 000000000000..6a47a2ab5e39
--- /dev/null
+++ b/Documentation/security/ipe.rst
@@ -0,0 +1,420 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Integrity Policy Enforcement (IPE) - Kernel Documentation
+=========================================================
+
+.. NOTE::
+
+ This is documentation targeted at developers, instead of administrators.
+ If you're looking for documentation on the usage of IPE, please see
+ `Documentation/admin-guide/LSM/ipe.rst`
+
+Historical Motivation
+---------------------
+
+The original issue that prompted IPE's implementation was the creation
+of a locked-down system. This system would be born-secure, and have
+strong integrity guarantees over both the executable code, and specific
+*data files* on the system, that were critical to its function. These
+specific data files would not be readable unless they passed integrity
+policy. A mandatory access control system would be present, and
+as a result, xattrs would have to be protected. This lead to a selection
+of what would provide the integrity claims. At the time, there were two
+main mechanisms considered that could guarantee integrity for the system
+with these requirements:
+
+ 1. IMA + EVM Signatures
+ 2. DM-Verity
+
+Both options were carefully considered, however the choice to use DM-Verity
+over IMA+EVM as the *integrity mechanism* in the original use case of IPE
+was due to three main reasons:
+
+ 1. Protection of additional attack vectors:
+
+ * With IMA+EVM, without an encryption solution, the system is vulnerable
+ to offline attack against the aforemetioned specific data files.
+
+ Unlike executables, read operations (like those on the protected data
+ files), cannot be enforced to be globally integrtiy verified. This means
+ there must be some form of selector to determine whether a read should
+ enforce the integrity policy, or it should not.
+
+ At the time, this was done with mandatory access control labels. An IMA
+ policy would indicate what labels required integrity verification, which
+ presented an issue: EVM would protect the label, but if an attacker could
+ modify filesystem offline, the attacker could wipe all the xattrs -
+ including the SELinux labels that would be used to determine whether the
+ file should be subject to integrity policy.
+
+ With DM-Verity, as the xattrs are saved as part of the merkel tree, if
+ offline mount occurs against the filesystem protected by dm-verity, the
+ checksum no longer matches and the file fails to be read.
+
+ * As userspace binaries are paged in Linux, dm-verity also offers the
+ additional protection against a hostile block device. In such an attack,
+ the block device reports the appropriate content for the IMA hash
+ initially, passing the required integrity check. Then, on the page fault
+ that accesses the real data, will report the attacker's payload. Since
+ dm-verity will check the data when the page fault occurs (and the disk
+ access), this attack is mitigated.
+
+ 2. Performance:
+
+ * dm-verity provides integrity verification on demand as blocks are
+ read versus requiring the entire file being read into memory for
+ validation.
+
+ 3. Simplicity of signing:
+
+ * No need for two signatures (IMA, then EVM): one signature covers
+ an entire block device.
+ * Signatures can be stored externally to the filesystem metadata.
+ * The signature supports an x.509-based signing infrastructure.
+
+The next step was to choose a *policy* to enforce the integrity mechanism.
+The minimum requirements for the policy were:
+
+ 1. The policy itself must be integrity verified (preventing trivial
+ attack against it).
+ 2. The policy itself must be resistant to rollback attacks.
+ 3. The policy enforcement must have a permissive-like mode.
+ 4. The policy must be able to be updated, in its entirety, without
+ a reboot.
+ 5. Policy updates must be atomic.
+ 6. The policy must support *revocations* of previously authored
+ components.
+ 7. The policy must be auditable, at any point-of-time.
+
+IMA, as the only integrity policy mechanism at the time, was
+considered against these list of requirements, and did not fulfill
+all of the minimum requirements. Extending IMA to cover these
+requirements was considered, but ultimately discarded for a
+two reasons:
+
+ 1. Regression risk; many of these changes would result in
+ dramatic code changes to IMA, which is already present in the
+ kernel, and therefore might impact users.
+
+ 2. IMA was used in the system for measurement and attestation;
+ separation of measurement policy from local integrity policy
+ enforcement was considered favorable.
+
+Due to these reasons, it was decided that a new LSM should be created,
+whose responsibility would be only the local integrity policy enforcement.
+
+Role and Scope
+--------------
+
+IPE, as its name implies, is fundamentally an integrity policy enforcement
+solution; IPE does not mandate how integrity is provided, but instead
+leaves that decision to the system administrator to set the security bar,
+via the mechanisms that they select that suit their individual needs.
+There are several different integrity solutions that provide a different
+level of security guarantees; and IPE allows sysadmins to express policy for
+theoretically all of them.
+
+IPE does not have an inherent mechanism to ensure integrity on its own.
+Instead, there are more effective layers available for building systems that
+can guarantee integrity. It's important to note that the mechanism for proving
+integrity is independent of the policy for enforcing that integrity claim.
+
+Therefore, IPE was designed around:
+
+ 1. Easy integrations with integrity providers.
+ 2. Ease of use for platform administrators/sysadmins.
+
+Design Rationale:
+-----------------
+
+IPE was designed after evaluating existing integrity policy solutions
+in other operating systems and environments. In this survey of other
+implementations, there were a few pitfalls identified:
+
+ 1. Policies were not readable by humans, usually requiring a binary
+ intermediary format.
+ 2. A single, non-customizable action was implicitly taken as a default.
+ 3. Debugging the policy required manual steps to determine what rule was violated.
+ 4. Authoring a policy required an in-depth knowledge of the larger system,
+ or operating system.
+
+IPE attempts to avoid all of these pitfalls.
+
+Policy
+~~~~~~
+
+Plain Text
+^^^^^^^^^^
+
+IPE's policy is plain-text. This introduces slightly larger policy files than
+other LSMs, but solves two major problems that occurs with some integrity policy
+solutions on other platforms.
+
+The first issue is one of code maintenance and duplication. To author policies,
+the policy has to be some form of string representation (be it structured,
+through XML, JSON, YAML, etcetera), to allow the policy author to understand
+what is being written. In a hypothetical binary policy design, a serializer
+is necessary to write the policy from the human readable form, to the binary
+form, and a deserializer is needed to interpret the binary form into a data
+structure in the kernel.
+
+Eventually, another deserializer will be needed to transform the binary from
+back into the human-readable form with as much information preserved. This is because a
+user of this access control system will have to keep a lookup table of a checksum
+and the original file itself to try to understand what policies have been deployed
+on this system and what policies have not. For a single user, this may be alright,
+as old policies can be discarded almost immediately after the update takes hold.
+For users that manage computer fleets in the thousands, if not hundreds of thousands,
+with multiple different operating systems, and multiple different operational needs,
+this quickly becomes an issue, as stale policies from years ago may be present,
+quickly resulting in the need to recover the policy or fund extensive infrastructure
+to track what each policy contains.
+
+With now three separate serializer/deserializers, maintenance becomes costly. If the
+policy avoids the binary format, there is only one required serializer: from the
+human-readable form to the data structure in kernel, saving on code maintenance,
+and retaining operability.
+
+The second issue with a binary format is one of transparency. As IPE controls
+access based on the trust of the system's resources, it's policy must also be
+trusted to be changed. This is done through signatures, resulting in needing
+signing as a process. Signing, as a process, is typically done with a
+high security bar, as anything signed can be used to attack integrity
+enforcement systems. It is also important that, when signing something, that
+the signer is aware of what they are signing. A binary policy can cause
+obfuscation of that fact; what signers see is an opaque binary blob. A
+plain-text policy, on the other hand, the signers see the actual policy
+submitted for signing.
+
+Boot Policy
+~~~~~~~~~~~
+
+IPE, if configured appropriately, is able to enforce a policy as soon as a
+kernel is booted and usermode starts. That implies some level of storage
+of the policy to apply the minute usermode starts. Generally, that storage
+can be handled in one of three ways:
+
+ 1. The policy file(s) live on disk and the kernel loads the policy prior
+ to an code path that would result in an enforcement decision.
+ 2. The policy file(s) are passed by the bootloader to the kernel, who
+ parses the policy.
+ 3. There is a policy file that is compiled into the kernel that is
+ parsed and enforced on initialization.
+
+The first option has problems: the kernel reading files from userspace
+is typically discouraged and very uncommon in the kernel.
+
+The second option also has problems: Linux supports a variety of bootloaders
+across its entire ecosystem - every bootloader would have to support this
+new methodology or there must be an independent source. It would likely
+result in more drastic changes to the kernel startup than necessary.
+
+The third option is the best but it's important to be aware that the policy
+will take disk space against the kernel it's compiled in. It's important to
+keep this policy generalized enough that userspace can load a new, more
+complicated policy, but restrictive enough that it will not overauthorize
+and cause security issues.
+
+The initramfs provides a way that this bootup path can be established. The
+kernel starts with a minimal policy, that trusts the initramfs only. Inside
+the initramfs, when the real rootfs is mounted, but not yet transferred to,
+it deploys and activates a policy that trusts the new root filesystem.
+This prevents overauthorization at any step, and keeps the kernel policy
+to a minimal size.
+
+Startup
+^^^^^^^
+
+Not every system, however starts with an initramfs, so the startup policy
+compiled into the kernel will need some flexibility to express how trust
+is established for the next phase of the bootup. To this end, if we just
+make the compiled-in policy a full IPE policy, it allows system builders
+to express the first stage bootup requirements appropriately.
+
+Updatable, Rebootless Policy
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+As requirements change over time (vulnerabilities are found in previously
+trusted applications, keys roll, etcetera). Updating a kernel to change the
+meet those security goals is not always a suitable option, as updates are not
+always risk-free, and blocking a security update leaves systems vulnerable.
+This means IPE requires a policy that can be completely updated (allowing
+revocations of existing policy) from a source external to the kernel (allowing
+policies to be updated without updating the kernel).
+
+Additionally, since the kernel is stateless between invocations, and reading
+policy files off the disk from kernel space is a bad idea(tm), then the
+policy updates have to be done rebootlessly.
+
+To allow an update from an external source, it could be potentially malicious,
+so this policy needs to have a way to be identified as trusted. This is
+done via a signature chained to a trust source in the kernel. Arbitrarily,
+this is the ``SYSTEM_TRUSTED_KEYRING``, a keyring that is initially
+populated at kernel compile-time, as this matches the expectation that the
+author of the compiled-in policy described above is the same entity that can
+deploy policy updates.
+
+Anti-Rollback / Anti-Replay
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Over time, vulnerabilities are found and trusted resources may not be
+trusted anymore. IPE's policy has no exception to this. There can be
+instances where a mistaken policy author deploys an insecure policy,
+before correcting it with a secure policy.
+
+Assuming that as soon as the insecure policy is signed, and an attacker
+acquires the insecure policy, IPE needs a way to prevent rollback
+from the secure policy update to the insecure policy update.
+
+Initially, IPE's policy can have a policy_version that states the
+minimum required version across all policies that can be active on
+the system. This will prevent rollback while the system is live.
+
+.. WARNING::
+
+ However, since the kernel is stateless across boots, this policy
+ version will be reset to 0.0.0 on the next boot. System builders
+ need to be aware of this, and ensure the new secure policies are
+ deployed ASAP after a boot to ensure that the window of
+ opportunity is minimal for an attacker to deploy the insecure policy.
+
+Implicit Actions:
+~~~~~~~~~~~~~~~~~
+
+The issue of impicit actions only becomes visible when you consider
+a mixed level of security bars across multiple operations in a system.
+For example, consider a system that has strong integrity guarantees
+over both the executable code, and specific *data files* on the system,
+that were critical to its function. In this system, three types of policies
+are possible:
+
+ 1. A policy in which failure to match any rules in the policy results
+ in the action being denied.
+ 2. A policy in which failure to match any rules in the policy results
+ in the action being allowed.
+ 3. A policy in which the action taken when no rules are matched is
+ specified by the policy author.
+
+The first option could make a policy like this::
+
+ op=EXECUTE integrity_verified=YES action=ALLOW
+
+In the example system, this works well for the executables, as all
+executables should have integrity guarantees, without exception. The
+issue becomes with the second requirement about specific data files.
+This would result in a policy like this (assuming each line is
+evaluated in order)::
+
+ op=EXECUTE integrity_verified=YES action=ALLOW
+
+ op=READ integrity_verified=NO label=critical_t action=DENY
+ op=READ action=ALLOW
+
+This is somewhat clear if you read the docs, understand the policy
+is executed in order and that the default is a denial; however, the
+last line effectively changes that default to an ALLOW. This is
+required, because in a realistic system, there are some unverified
+reads (imagine appending to a log file).
+
+The second option, matching no rules results in an allow, is clearer
+for the specific data files::
+
+ op=READ integrity_verified=NO label=critical_t action=DENY
+
+And, like the first option, falls short with the opposite scenario,
+effectively needing to override the default::
+
+ op=EXECUTE integrity_verified=YES action=ALLOW
+ op=EXECUTE action=DENY
+
+ op=READ integrity_verified=NO label=critical_t action=DENY
+
+This leaves the third option. Instead of making users be clever
+and override the default with an empty rule, force the end-user
+to consider what the appropriate default should be for their
+scenario and explicitly state it::
+
+ DEFAULT op=EXECUTE action=DENY
+ op=EXECUTE integrity_verified=YES action=ALLOW
+
+ DEFAULT op=READ action=ALLOW
+ op=READ integrity_verified=NO label=critical_t action=DENY
+
+Policy Debugging:
+~~~~~~~~~~~~~~~~~
+
+When developing a policy, it is useful to know what line of the policy
+is being violated to reduce debugging costs; narrowing the scope of the
+investigation to the exact line that resulted in the action. Some integrity
+policy systems do not provide this information, instead providing the
+information that was used in the evaluation. This then requires a correlation
+with the policy to evaluate what went wrong.
+
+Instead, IPE just emits the rule that was matched. This limits the scope
+of the investigation to the exact policy line (in the case of a specific
+rule), or the section (in the case of a DEFAULT). This decreases iteration
+and investigation times when policy failures are observed while evaluating
+policies.
+
+IPE's policy engine is also designed in a way that it makes it obvious to
+a human of how to investigate a policy failure. Each line is evaluated in
+the sequence that is written, so the algorithm is very simple to follow
+for humans to recreate the steps and could have caused the failure. In other
+surveyed systems, optimizations occur (sorting rules, for instance) when loading
+the policy. In those systems, it requires multiple steps to debug, and the
+algorithm may not always be clear to the end-user without reading the code first.
+
+Simplified Policy:
+~~~~~~~~~~~~~~~~~~
+
+Finally, IPE's policy is designed for sysadmins, not kernel developers. Instead
+of covering individual LSM hooks (or syscalls), IPE covers operations. This means
+instead of sysadmins needing to know that the syscalls ``mmap``, ``mprotect``,
+``execve``, and ``uselib`` must have rules protecting them, they must simple know
+that they want to restrict code execution. This limits the amount of bypasses that
+could occur due to a lack of knowledge of the underlying system; whereas the
+maintainers of IPE, being kernel developers can make the correct choice to determine
+whether something maps to these operations, and under what conditions.
+
+Implementation Notes
+--------------------
+
+Anonymous Memory
+~~~~~~~~~~~~~~~~
+
+Anonymous memory isn't treated any differently from any other access in IPE.
+When anonymous memory is mapped with ``+X``, it still comes into the ``file_mmap``
+or ``file_mprotect`` hook, but with a ``NULL`` file object. This is submitted to
+the evaluation, like any other file, however, all current trust mechanisms will
+return false as there is nothing to evaluate. This means anonymous memory
+execution is subject to whatever the ``DEFAULT`` is for ``EXECUTE``.
+
+.. WARNING::
+
+ This also occurs with the ``kernel_load_data`` hook, which is used by signed
+ and compressed kernel modules. Using signed and compressed kernel modules with
+ IPE will always result in the ``DEFAULT`` action for ``KMODULE``.
+
+Securityfs Interface
+~~~~~~~~~~~~~~~~~~~~
+
+The per-policy securityfs tree is somewhat unique. For example, for
+a standard securityfs policy tree::
+
+ MyPolicy
+ |- active
+ |- delete
+ |- name
+ |- pkcs7
+ |- policy
+ |- update
+ |- version
+
+The policy is stored in the ``->i_private`` data of the MyPolicy inode.
+
+Tests
+-----
+
+IPE has KUnit Tests, testing primarily the parser. In addition, IPE has a
+python based integration test suits that can test both user interfaces and
+enforcement functionalities.
diff --git a/MAINTAINERS b/MAINTAINERS
index fb8d6a16f2a6..a5494fb9e385 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -10283,6 +10283,8 @@ M: Fan Wu <[email protected]>
L: [email protected]
S: Supported
T: git git://github.com/microsoft/ipe.git
+F: Documentation/admin-guide/LSM/ipe.rst
+F: Documentation/security/ipe.rst
F: scripts/ipe/
F: security/ipe/

--
2.25.1


2023-06-28 21:22:35

by Fan Wu

[permalink] [raw]
Subject: [RFC PATCH v10 06/17] security: add new securityfs delete function

When deleting a directory in the security file system, the existing
securityfs_remove requires the directory to be empty, otherwise
it will do nothing. This leads to a potential risk that the security
file system might be in an unclean state when the intentded deletion
did not happen.

This commit introduces a new function securityfs_recursive_remove
to recursively delete a directory without leaving an unclean state.

Co-developed-by: Christian Brauner (Microsoft) <[email protected]>
Signed-off-by: Fan Wu <[email protected]>

---
v1-v8:
+ Not present

v9:
+ Introduced

v10:
+ No changes
---
include/linux/security.h | 1 +
security/inode.c | 25 +++++++++++++++++++++++++
2 files changed, 26 insertions(+)

diff --git a/include/linux/security.h b/include/linux/security.h
index e2734e9e44d5..a88076ebc7b1 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -1971,6 +1971,7 @@ struct dentry *securityfs_create_symlink(const char *name,
const char *target,
const struct inode_operations *iops);
extern void securityfs_remove(struct dentry *dentry);
+extern void securityfs_recursive_remove(struct dentry *dentry);

#else /* CONFIG_SECURITYFS */

diff --git a/security/inode.c b/security/inode.c
index 6c326939750d..13358e8547e8 100644
--- a/security/inode.c
+++ b/security/inode.c
@@ -313,6 +313,31 @@ void securityfs_remove(struct dentry *dentry)
}
EXPORT_SYMBOL_GPL(securityfs_remove);

+static void remove_one(struct dentry *victim)
+{
+ simple_release_fs(&mount, &mount_count);
+}
+
+/**
+ * securityfs_recursive_remove - recursively removes a file or directory from the securityfs filesystem
+ *
+ * @dentry: a pointer to a the dentry of the file or directory to be removed.
+ *
+ * This function recursively removes a file or directory in securityfs that was
+ * previously created with a call to another securityfs function (like
+ * securityfs_create_file() or variants thereof.)
+ */
+void securityfs_recursive_remove(struct dentry *dentry)
+{
+ if (IS_ERR_OR_NULL(dentry))
+ return;
+
+ simple_pin_fs(&fs_type, &mount, &mount_count);
+ simple_recursive_removal(dentry, remove_one);
+ simple_release_fs(&mount, &mount_count);
+}
+EXPORT_SYMBOL_GPL(securityfs_recursive_remove);
+
#ifdef CONFIG_SECURITY
static struct dentry *lsm_dentry;
static ssize_t lsm_read(struct file *filp, char __user *buf, size_t count,
--
2.25.1


2023-07-07 15:18:20

by Mike Snitzer

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Wed, Jun 28 2023 at 5:09P -0400,
Fan Wu <[email protected]> wrote:

> From: Deven Bowers <[email protected]>
>
> dm-verity provides a strong guarantee of a block device's integrity. As
> a generic way to check the integrity of a block device, it provides
> those integrity guarantees to its higher layers, including the filesystem
> level.
>
> An LSM that control access to a resource on the system based on the
> available integrity claims can use this transitive property of
> dm-verity, by querying the underlying block_device of a particular
> file.
>
> The digest and signature information need to be stored in the block
> device to fulfill the next requirement of authorization via LSM policy.
> This will enable the LSM to perform revocation of devices that are still
> mounted, prohibiting execution of files that are no longer authorized
> by the LSM in question.
>
> This patch added two security hook calls in dm-verity to save the
> dm-verity roothash and the roothash signature to LSM blobs.
>
> Signed-off-by: Deven Bowers <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---

> diff --git a/drivers/md/dm-verity-target.c b/drivers/md/dm-verity-target.c
> index 26adcfea0302..54d46b2f2723 100644
> --- a/drivers/md/dm-verity-target.c
> +++ b/drivers/md/dm-verity-target.c
> @@ -1440,6 +1453,15 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
> ti->per_io_data_size = roundup(ti->per_io_data_size,
> __alignof__(struct dm_verity_io));
>
> + root_digest.digest = v->root_digest;
> + root_digest.digest_len = v->digest_size;
> + root_digest.algo = v->alg_name;
> +
> + r = security_bdev_setsecurity(bdev, DM_VERITY_ROOTHASH_SEC_NAME, &root_digest,
> + sizeof(root_digest));
> + if (r)
> + goto bad;
> +
> verity_verify_sig_opts_cleanup(&verify_args);
>
> dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
> diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
> index 4836508ea50c..33165dd7470f 100644
> --- a/drivers/md/dm-verity-verify-sig.c
> +++ b/drivers/md/dm-verity-verify-sig.c
> @@ -9,6 +9,9 @@
> #include <linux/verification.h>
> #include <keys/user-type.h>
> #include <linux/module.h>
> +#include <linux/security.h>
> +#include <linux/dm-verity.h>
> +#include "dm-core.h"

Why are you including dm-core.h here?

> #include "dm-verity.h"
> #include "dm-verity-verify-sig.h"
>
> @@ -97,14 +100,17 @@ int verity_verify_sig_parse_opt_args(struct dm_arg_set *as,
> * verify_verify_roothash - Verify the root hash of the verity hash device
> * using builtin trusted keys.
> *
> + * @bdev: block_device representing the device-mapper created block device.
> + * Used by the security hook, to set information about the block_device.
> * @root_hash: For verity, the roothash/data to be verified.
> * @root_hash_len: Size of the roothash/data to be verified.
> * @sig_data: The trusted signature that verifies the roothash/data.
> * @sig_len: Size of the signature.
> *
> */
> -int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
> - const void *sig_data, size_t sig_len)
> +int verity_verify_root_hash(struct block_device *bdev, const void *root_hash,
> + size_t root_hash_len, const void *sig_data,
> + size_t sig_len)
> {
> int ret;
>
> @@ -126,8 +132,12 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
> NULL,
> #endif
> VERIFYING_UNSPECIFIED_SIGNATURE, NULL, NULL);
> + if (ret)
> + return ret;
>
> - return ret;
> + return security_bdev_setsecurity(bdev,
> + DM_VERITY_SIGNATURE_SEC_NAME,
> + sig_data, sig_len);
> }
>
> void verity_verify_sig_opts_cleanup(struct dm_verity_sig_opts *sig_opts)

Both of your calls to security_bdev_setsecurity() to set your blobs in
the bdev are suspect because you're doing so from the verity_ctr().
The mapped_device has 2 dm_table slots (active and inactive). The
verity_ctr() becomes part of the inactive slot, there is an extra step
to bind the inactive table to the active table.

This leads to you changing the blobs in the global bdev _before_ the
table is actually active. It is possible that the inactive table will
simply be removed and the DM verity device put back in service;
leaving your blob(s) in the bdev inconsistent.

This issue has parallels to how we need to defer changing the global
queue_limits associated with a request_queue until _after_ all table
loading is settled and then the update is done just before resuming
the DM device (mapped_device) -- see dm_table_set_restrictions().

Unfortunately, this feels like it may require a new hook in the
target_type struct (e.g. ->finalize())

Mike

2023-07-08 05:39:26

by Paul Moore

[permalink] [raw]
Subject: Re: [PATCH RFC v10 7/17] ipe: add userspace interface

On Jun 28, 2023 Fan Wu <[email protected]> wrote:
>
> As is typical with LSMs, IPE uses securityfs as its interface with
> userspace. for a complete list of the interfaces and the respective
> inputs/outputs, please see the documentation under
> admin-guide/LSM/ipe.rst
>
> Signed-off-by: Deven Bowers <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---
> security/ipe/Makefile | 2 +
> security/ipe/fs.c | 101 ++++++++
> security/ipe/fs.h | 16 ++
> security/ipe/ipe.c | 3 +
> security/ipe/ipe.h | 2 +
> security/ipe/policy.c | 111 +++++++++
> security/ipe/policy.h | 9 +
> security/ipe/policy_fs.c | 481 +++++++++++++++++++++++++++++++++++++++
> 8 files changed, 725 insertions(+)
> create mode 100644 security/ipe/fs.c
> create mode 100644 security/ipe/fs.h
> create mode 100644 security/ipe/policy_fs.c

...

> diff --git a/security/ipe/policy.c b/security/ipe/policy.c
> index 4069ff075093..3e8e4a06a044 100644
> --- a/security/ipe/policy.c
> +++ b/security/ipe/policy.c
> @@ -7,9 +7,36 @@
> #include <linux/verification.h>
>
> #include "ipe.h"
> +#include "eval.h"
> +#include "fs.h"
> #include "policy.h"
> #include "policy_parser.h"
>
> +/* lock for synchronizing writers across ipe policy */
> +DEFINE_MUTEX(ipe_policy_lock);
> +
> +/**
> + * ver_to_u64 - Convert an internal ipe_policy_version to a u64.
> + * @p: Policy to extract the version from.
> + *
> + * Bits (LSB is index 0):
> + * [48,32] -> Major
> + * [32,16] -> Minor
> + * [16, 0] -> Revision
> + *
> + * Return: u64 version of the embedded version structure.
> + */
> +static inline u64 ver_to_u64(const struct ipe_policy *const p)
> +{
> + u64 r;
> +
> + r = (((u64)p->parsed->version.major) << 32)
> + | (((u64)p->parsed->version.minor) << 16)
> + | ((u64)(p->parsed->version.rev));
> +
> + return r;
> +}
> +
> /**
> * ipe_free_policy - Deallocate a given IPE policy.
> * @p: Supplies the policy to free.
> @@ -21,6 +48,7 @@ void ipe_free_policy(struct ipe_policy *p)
> if (IS_ERR_OR_NULL(p))
> return;
>
> + ipe_del_policyfs_node(p);
> free_parsed_policy(p->parsed);
> if (!p->pkcs7)
> kfree(p->text);
> @@ -39,6 +67,65 @@ static int set_pkcs7_data(void *ctx, const void *data, size_t len,
> return 0;
> }
>
> +/**
> + * ipe_update_policy - parse a new policy and replace @old with it.

What does "@old" refer to? I'm guessing you want to drop the "@".

> + * @root: Supplies a pointer to the securityfs inode saved the policy.
> + * @text: Supplies a pointer to the plain text policy.
> + * @textlen: Supplies the length of @text.
> + * @pkcs7: Supplies a pointer to a buffer containing a pkcs7 message.
> + * @pkcs7len: Supplies the length of @pkcs7len.
> + *
> + * @text/@textlen is mutually exclusive with @pkcs7/@pkcs7len - see
> + * ipe_new_policy.
> + *
> + * Return:
> + * * !IS_ERR - The old policy

"The old policy" is what?

> + * * -ENOENT - Policy doesn't exist
> + * * -EINVAL - New policy is invalid
> + */
> +struct ipe_policy *ipe_update_policy(struct inode *root,
> + const char *text, size_t textlen,
> + const char *pkcs7, size_t pkcs7len)
> +{
> + int rc = 0;
> + struct ipe_policy *old, *ap, *new = NULL;
> +
> + lockdep_assert_held(&ipe_policy_lock);
> +
> + old = (struct ipe_policy *)root->i_private;
> + if (!old)
> + return ERR_PTR(-ENOENT);
> +
> + new = ipe_new_policy(text, textlen, pkcs7, pkcs7len);
> + if (IS_ERR(new))
> + return new;
> +
> + if (strcmp(new->parsed->name, old->parsed->name)) {
> + rc = -EINVAL;
> + goto err;
> + }
> +
> + if (ver_to_u64(old) > ver_to_u64(new)) {
> + rc = -EINVAL;
> + goto err;
> + }
> +
> + root->i_private = new;
> +
> + ap = rcu_dereference_protected(ipe_active_policy,
> + lockdep_is_held(&ipe_policy_lock));
> + if (old == ap)
> + rcu_assign_pointer(ipe_active_policy, new);
> +
> + swap(new->policyfs, old->policyfs);

We don't have to worry about @new, but is there a guarantee that this
function is the only one attempting to modify @old?

*EDIT*: I found that @root is locked by the caller, that's good. I
would suggest adding this assumption/requirement to the function's
description. In general whenever a function requires something from
a caller it should be documented in the function's description.

> +out:
> + return (rc < 0) ? ERR_PTR(rc) : old;
> +err:
> + ipe_free_policy(new);
> + goto out;
> +}
> +

...

> diff --git a/security/ipe/policy_fs.c b/security/ipe/policy_fs.c
> new file mode 100644
> index 000000000000..52a120118cda
> --- /dev/null
> +++ b/security/ipe/policy_fs.c
> @@ -0,0 +1,481 @@

...

> +/**
> + * getactive - Read handler for "ipe/policies/$name/active".
> + * @f: Supplies a file structure representing the securityfs node.
> + * @data: Suppleis a buffer passed to the write syscall.
> + * @len: Supplies the length of @data.
> + * @offset: unused.
> + *
> + * @data will be populated with the 1 or 0 depending on if the
> + * corresponding policy is active.
> + *
> + * Return:
> + * * >0 - Success, Length of buffer written
> + * * <0 - Error
> + */
> +static ssize_t getactive(struct file *f, char __user *data,
> + size_t len, loff_t *offset)
> +{
> + int rc = 0;
> + const char *str;
> + struct inode *root = NULL;
> + const struct ipe_policy *p = NULL;
> +
> + root = d_inode(f->f_path.dentry->d_parent);
> +
> + inode_lock_shared(root);
> + p = (struct ipe_policy *)root->i_private;
> + if (!p) {
> + inode_unlock_shared(root);
> + return -ENOENT;
> + }
> + inode_unlock_shared(root);
> +
> + str = (p == rcu_access_pointer(ipe_active_policy)) ? "1" : "0";

The line above should be wrapped with a RCU lock.

> + rc = simple_read_from_buffer(data, len, offset, str, 1);
> +
> + return rc;
> +}

--
paul-moore.com

2023-07-08 05:39:33

by Paul Moore

[permalink] [raw]
Subject: Re: [PATCH RFC v10 6/17] security: add new securityfs delete function

On Jun 28, 2023 Fan Wu <[email protected]> wrote:
>
> When deleting a directory in the security file system, the existing
> securityfs_remove requires the directory to be empty, otherwise
> it will do nothing. This leads to a potential risk that the security
> file system might be in an unclean state when the intentded deletion
> did not happen.
>
> This commit introduces a new function securityfs_recursive_remove
> to recursively delete a directory without leaving an unclean state.
>
> Co-developed-by: "Christian Brauner (Microsoft)" <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---
> include/linux/security.h | 1 +
> security/inode.c | 25 +++++++++++++++++++++++++
> 2 files changed, 26 insertions(+)
>
> diff --git a/include/linux/security.h b/include/linux/security.h
> index e2734e9e44d5..a88076ebc7b1 100644
> --- a/include/linux/security.h
> +++ b/include/linux/security.h
> @@ -1971,6 +1971,7 @@ struct dentry *securityfs_create_symlink(const char *name,
> const char *target,
> const struct inode_operations *iops);
> extern void securityfs_remove(struct dentry *dentry);
> +extern void securityfs_recursive_remove(struct dentry *dentry);
>
> #else /* CONFIG_SECURITYFS */
>
> diff --git a/security/inode.c b/security/inode.c
> index 6c326939750d..13358e8547e8 100644
> --- a/security/inode.c
> +++ b/security/inode.c
> @@ -313,6 +313,31 @@ void securityfs_remove(struct dentry *dentry)
> }
> EXPORT_SYMBOL_GPL(securityfs_remove);
>
> +static void remove_one(struct dentry *victim)
> +{
> + simple_release_fs(&mount, &mount_count);
> +}
> +
> +/**
> + * securityfs_recursive_remove - recursively removes a file or directory from the securityfs filesystem

I really want to see lines less than or equal to 80 characters; I
would suggest this:

"securityfs_recursive_remove - recursively removes a file or directory"

> + * @dentry: a pointer to a the dentry of the file or directory to be removed.
> + *
> + * This function recursively removes a file or directory in securityfs that was
> + * previously created with a call to another securityfs function (like
> + * securityfs_create_file() or variants thereof.)
> + */
> +void securityfs_recursive_remove(struct dentry *dentry)
> +{
> + if (IS_ERR_OR_NULL(dentry))
> + return;
> +
> + simple_pin_fs(&fs_type, &mount, &mount_count);
> + simple_recursive_removal(dentry, remove_one);
> + simple_release_fs(&mount, &mount_count);
> +}
> +EXPORT_SYMBOL_GPL(securityfs_recursive_remove);
> +
> #ifdef CONFIG_SECURITY
> static struct dentry *lsm_dentry;
> static ssize_t lsm_read(struct file *filp, char __user *buf, size_t count,
> --
> 2.25.1

--
paul-moore.com

2023-07-08 05:53:30

by Paul Moore

[permalink] [raw]
Subject: Re: [PATCH RFC v10 1/17] security: add ipe lsm

On Jun 28, 2023 Fan Wu <[email protected]> wrote:
>
> Integrity Policy Enforcement (IPE) is an LSM that provides an
> complimentary approach to Mandatory Access Control than existing LSMs
> today.
>
> Existing LSMs have centered around the concept of access to a resource
> should be controlled by the current user's credentials. IPE's approach,
> is that access to a resource should be controlled by the system's trust
> of a current resource.
>
> The basis of this approach is defining a global policy to specify which
> resource can be trusted.
>
> Signed-off-by: Deven Bowers <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---
> MAINTAINERS | 7 +++++++
> security/Kconfig | 11 ++++++-----
> security/Makefile | 1 +
> security/ipe/Kconfig | 17 +++++++++++++++++
> security/ipe/Makefile | 10 ++++++++++
> security/ipe/ipe.c | 37 +++++++++++++++++++++++++++++++++++++
> security/ipe/ipe.h | 16 ++++++++++++++++
> 7 files changed, 94 insertions(+), 5 deletions(-)
> create mode 100644 security/ipe/Kconfig
> create mode 100644 security/ipe/Makefile
> create mode 100644 security/ipe/ipe.c
> create mode 100644 security/ipe/ipe.h

...

> diff --git a/MAINTAINERS b/MAINTAINERS
> index a82795114ad4..ad00887d38ea 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -10278,6 +10278,13 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity.git
> F: security/integrity/
> F: security/integrity/ima/
>
> +INTEGRITY POLICY ENFORCEMENT (IPE)
> +M: Fan Wu <[email protected]>
> +L: [email protected]
> +S: Supported
> +T: git git://github.com/microsoft/ipe.git

Using the raw git protocol doesn't seem to work with GH, I think you
need to refernce the git/https URL:

https://github.com/microsoft/ipe.git

> +F: security/ipe/
> +
> INTEL 810/815 FRAMEBUFFER DRIVER
> M: Antonino Daplas <[email protected]>
> L: [email protected]
> diff --git a/security/Kconfig b/security/Kconfig
> index 97abeb9b9a19..daa4626ea99c 100644
> --- a/security/Kconfig
> +++ b/security/Kconfig
> @@ -202,6 +202,7 @@ source "security/yama/Kconfig"
> source "security/safesetid/Kconfig"
> source "security/lockdown/Kconfig"
> source "security/landlock/Kconfig"
> +source "security/ipe/Kconfig"
>
> source "security/integrity/Kconfig"
>
> @@ -241,11 +242,11 @@ endchoice
>
> config LSM
> string "Ordered list of enabled LSMs"
> - default "landlock,lockdown,yama,loadpin,safesetid,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
> - default "landlock,lockdown,yama,loadpin,safesetid,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
> - default "landlock,lockdown,yama,loadpin,safesetid,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
> - default "landlock,lockdown,yama,loadpin,safesetid,bpf" if DEFAULT_SECURITY_DAC
> - default "landlock,lockdown,yama,loadpin,safesetid,selinux,smack,tomoyo,apparmor,bpf"
> + default "landlock,lockdown,yama,loadpin,safesetid,smack,selinux,tomoyo,apparmor,bpf,ipe" if DEFAULT_SECURITY_SMACK
> + default "landlock,lockdown,yama,loadpin,safesetid,apparmor,selinux,smack,tomoyo,bpf,ipe" if DEFAULT_SECURITY_APPARMOR
> + default "landlock,lockdown,yama,loadpin,safesetid,tomoyo,bpf,ipe" if DEFAULT_SECURITY_TOMOYO
> + default "landlock,lockdown,yama,loadpin,safesetid,bpf,ipe" if DEFAULT_SECURITY_DAC
> + default "landlock,lockdown,yama,loadpin,safesetid,selinux,smack,tomoyo,apparmor,bpf,ipe"

Generally speaking the BPF LSM should be the last entry in the LSM
list to help prevent issues caused by a BPF LSM returning an improper
error and shortcutting a LSM after it.

> help
> A comma-separated list of LSMs, in initialization order.
> Any LSMs left off this list, except for those with order

...

> diff --git a/security/ipe/Makefile b/security/ipe/Makefile
> new file mode 100644
> index 000000000000..571648579991
> --- /dev/null
> +++ b/security/ipe/Makefile
> @@ -0,0 +1,10 @@
> +# SPDX-License-Identifier: GPL-2.0
> +#
> +# Copyright (C) Microsoft Corporation. All rights reserved.
> +#
> +# Makefile for building the IPE module as part of the kernel tree.
> +#
> +
> +obj-$(CONFIG_SECURITY_IPE) += \
> + hooks.o \
> + ipe.o \

It doesn't look like security/ipe/hook.c is included in this patch.

It is important to ensure that each patch compiles after it is
applied.

--
paul-moore.com

2023-07-08 06:47:04

by Paul Moore

[permalink] [raw]
Subject: Re: [PATCH RFC v10 2/17] ipe: add policy parser

On Jun 28, 2023 Fan Wu <[email protected]> wrote:
>
> IPE's interpretation of the what the user trusts is accomplished through
> its policy. IPE's design is to not provide support for a single trust
> provider, but to support multiple providers to enable the end-user to
> choose the best one to seek their needs.
>
> This requires the policy to be rather flexible and modular so that
> integrity providers, like fs-verity, dm-verity, dm-integrity, or
> some other system, can plug into the policy with minimal code changes.
>
> Signed-off-by: Deven Bowers <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---
> security/ipe/Makefile | 2 +
> security/ipe/policy.c | 97 +++++++
> security/ipe/policy.h | 83 ++++++
> security/ipe/policy_parser.c | 488 +++++++++++++++++++++++++++++++++++
> security/ipe/policy_parser.h | 11 +
> 5 files changed, 681 insertions(+)
> create mode 100644 security/ipe/policy.c
> create mode 100644 security/ipe/policy.h
> create mode 100644 security/ipe/policy_parser.c
> create mode 100644 security/ipe/policy_parser.h

...

> diff --git a/security/ipe/policy.c b/security/ipe/policy.c
> new file mode 100644
> index 000000000000..4069ff075093
> --- /dev/null
> +++ b/security/ipe/policy.c
> @@ -0,0 +1,97 @@
> +// SPDX-License-Identifier: GPL-2.0
> +/*
> + * Copyright (C) Microsoft Corporation. All rights reserved.
> + */
> +
> +#include <linux/errno.h>
> +#include <linux/verification.h>
> +
> +#include "ipe.h"
> +#include "policy.h"
> +#include "policy_parser.h"
> +
> +/**
> + * ipe_free_policy - Deallocate a given IPE policy.
> + * @p: Supplies the policy to free.
> + *
> + * Safe to call on IS_ERR/NULL.
> + */
> +void ipe_free_policy(struct ipe_policy *p)
> +{
> + if (IS_ERR_OR_NULL(p))
> + return;
> +
> + free_parsed_policy(p->parsed);
> + if (!p->pkcs7)
> + kfree(p->text);

Since it's safe to kfree(NULL), you could kfree(p->text) without
having to check if p->pkcs7 was non-NULL, correct?

> + kfree(p->pkcs7);
> + kfree(p);
> +}

...

> diff --git a/security/ipe/policy.h b/security/ipe/policy.h
> new file mode 100644
> index 000000000000..113a037f0d71
> --- /dev/null
> +++ b/security/ipe/policy.h
> @@ -0,0 +1,83 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +/*
> + * Copyright (C) Microsoft Corporation. All rights reserved.
> + */
> +#ifndef _IPE_POLICY_H
> +#define _IPE_POLICY_H
> +
> +#include <linux/list.h>
> +#include <linux/types.h>
> +
> +enum ipe_op_type {
> + __IPE_OP_EXEC = 0,
> + __IPE_OP_FIRMWARE,
> + __IPE_OP_KERNEL_MODULE,
> + __IPE_OP_KEXEC_IMAGE,
> + __IPE_OP_KEXEC_INITRAMFS,
> + __IPE_OP_IMA_POLICY,
> + __IPE_OP_IMA_X509,
> + __IPE_OP_MAX
> +};

Thanks for capitalizing the enums, that helps make IPE consistent with
the majority of the kernel. However, when I talked about using
underscores for "__IPE_OP_MAX", I was talking about *only*
"__IPE_OP_MAX" to help indicate it is a sentinel value and not an enum
value that would normally be used by itself.

Here is what I was intending:

enum ipe_op_type {
IPE_OP_EXEC = 0,
IPE_OP_FIRMWARE,
...
IPE_OP_IMA_X509,
__IPE_OP_MAX
};

> +#define __IPE_OP_INVALID __IPE_OP_MAX

Similarly, I would remove the underscores from "__IPE_OP_INVALID":

#define IPE_OP_INVALID __IPE_OP_MAX

Both of these comments would apply to the other IPE enums as well.

> diff --git a/security/ipe/policy_parser.c b/security/ipe/policy_parser.c
> new file mode 100644
> index 000000000000..27e5767480b0
> --- /dev/null
> +++ b/security/ipe/policy_parser.c
> @@ -0,0 +1,488 @@

...

> +/**
> + * parse_header - Parse policy header information.
> + * @line: Supplies header line to be parsed.
> + * @p: Supplies the partial parsed policy.
> + *
> + * Return:
> + * * 0 - OK
> + * * !0 - Standard errno
> + */
> +static int parse_header(char *line, struct ipe_parsed_policy *p)
> +{
> + int rc = 0;
> + char *t, *ver = NULL;
> + substring_t args[MAX_OPT_ARGS];
> + size_t idx = 0;
> +
> + while ((t = strsep(&line, " \t")) != NULL) {

It might be nice to define a macro to help reinforce that " \t" are
the IPE policy delimiters, how about IPE_POLICY_DELIM?

#define IPE_POLICY_DELIM " \t"

> + int token;
> +
> + if (*t == '\0')
> + continue;

Why would you want to continue if you run into a NUL byte? You would
only run into a NUL byte if the line was trimmed due to comments or
whitespace, correct? If that is the case, wouldn't you want to
break out of this loop when hitting a NUL byte?

> + if (idx >= __IPE_HEADER_MAX) {
> + rc = -EBADMSG;
> + goto err;
> + }
> +
> + token = match_token(t, header_tokens, args);
> + if (token != idx) {
> + rc = -EBADMSG;
> + goto err;
> + }
> +
> + switch (token) {
> + case __IPE_HEADER_POLICY_NAME:
> + p->name = match_strdup(&args[0]);
> + if (!p->name)
> + rc = -ENOMEM;
> + break;
> + case __IPE_HEADER_POLICY_VERSION:
> + ver = match_strdup(&args[0]);
> + if (!ver) {
> + rc = -ENOMEM;
> + break;
> + }
> + rc = parse_version(ver, p);
> + break;
> + default:
> + rc = -EBADMSG;
> + }
> + if (rc)
> + goto err;
> + ++idx;
> + }
> +
> + if (idx != __IPE_HEADER_MAX) {
> + rc = -EBADMSG;
> + goto err;
> + }
> +
> +out:
> + kfree(ver);
> + return rc;
> +err:
> + kfree(p->name);
> + p->name = NULL;
> + goto out;

Do we need to worry about ipe_parsed_policy::name here? If we are
returning an error the caller will call free_parsed_policy() for us,
right? This would allow us to get rid of the 'err' jump label and
simply use 'out' for both success and failure.

> +}

...

> +/**
> + * parse_rule - parse a policy rule line.
> + * @line: Supplies rule line to be parsed.
> + * @p: Supplies the partial parsed policy.
> + *
> + * Return:
> + * * !IS_ERR - OK
> + * * -ENOMEM - Out of memory
> + * * -EBADMSG - Policy syntax error
> + */
> +static int parse_rule(char *line, struct ipe_parsed_policy *p)
> +{
> + int rc = 0;
> + bool first_token = true, is_default_rule = false;
> + bool op_parsed = false;
> + enum ipe_op_type op = __IPE_OP_INVALID;
> + enum ipe_action_type action = __IPE_ACTION_INVALID;
> + struct ipe_rule *r = NULL;
> + char *t;
> +
> + r = kzalloc(sizeof(*r), GFP_KERNEL);
> + if (!r)
> + return -ENOMEM;
> +
> + INIT_LIST_HEAD(&r->next);
> + INIT_LIST_HEAD(&r->props);
> +
> + while (t = strsep(&line, " \t"), line) {

See my previous comment about IPE_POLICY_DELIM.

> + if (*t == '\0')
> + continue;

I still wonder why continuing here is the desired behavior, can you
help me understand?

> + if (first_token && token_default(t)) {
> + is_default_rule = true;
> + } else {
> + if (!op_parsed) {
> + op = parse_operation(t);
> + if (op == __IPE_OP_INVALID)
> + rc = -EBADMSG;
> + else
> + op_parsed = true;
> + } else {
> + rc = parse_property(t, r);
> + }
> + }
> +
> + if (rc)
> + goto err;
> + first_token = false;
> + }
> +
> + action = parse_action(t);
> + if (action == __IPE_ACTION_INVALID) {
> + rc = -EBADMSG;
> + goto err;
> + }
> +
> + if (is_default_rule) {
> + if (!list_empty(&r->props)) {
> + rc = -EBADMSG;
> + } else if (op == __IPE_OP_INVALID) {
> + if (p->global_default_action != __IPE_ACTION_INVALID)
> + rc = -EBADMSG;
> + else
> + p->global_default_action = action;
> + } else {
> + if (p->rules[op].default_action != __IPE_ACTION_INVALID)
> + rc = -EBADMSG;
> + else
> + p->rules[op].default_action = action;
> + }
> + } else if (op != __IPE_OP_INVALID && action != __IPE_ACTION_INVALID) {
> + r->op = op;
> + r->action = action;
> + } else {
> + rc = -EBADMSG;
> + }
> +
> + if (rc)
> + goto err;
> + if (!is_default_rule)
> + list_add_tail(&r->next, &p->rules[op].rules);
> + else
> + free_rule(r);
> +
> +out:
> + return rc;
> +err:
> + free_rule(r);
> + goto out;

In keeping with the rule of not jumping to a label only to
immediately return, and considering that the only place where we jump
to 'out' is in the 'err' code, let's get rid of the 'out' label and
have 'err' "return rc" instead of "goto out".

> +}

--
paul-moore.com

2023-07-08 06:53:38

by Paul Moore

[permalink] [raw]
Subject: Re: [PATCH RFC v10 12/17] ipe: add support for dm-verity as a trust provider

On Jun 28, 2023 Fan Wu <[email protected]> wrote:
>
> Allows author of IPE policy to indicate trust for a singular dm-verity
> volume, identified by roothash, through "dmverity_roothash" and all
> signed dm-verity volumes, through "dmverity_signature".
>
> Signed-off-by: Deven Bowers <[email protected]>
> Signed-off-by: Fan Wu <[email protected]>
> ---
> security/ipe/Kconfig | 18 +++++
> security/ipe/Makefile | 1 +
> security/ipe/audit.c | 25 ++++++
> security/ipe/digest.c | 142 +++++++++++++++++++++++++++++++++++
> security/ipe/digest.h | 26 +++++++
> security/ipe/eval.c | 101 ++++++++++++++++++++++++-
> security/ipe/eval.h | 13 ++++
> security/ipe/hooks.c | 51 +++++++++++++
> security/ipe/hooks.h | 8 ++
> security/ipe/ipe.c | 15 ++++
> security/ipe/ipe.h | 4 +
> security/ipe/policy.h | 3 +
> security/ipe/policy_parser.c | 21 ++++++
> 13 files changed, 427 insertions(+), 1 deletion(-)
> create mode 100644 security/ipe/digest.c
> create mode 100644 security/ipe/digest.h

...

> diff --git a/security/ipe/hooks.c b/security/ipe/hooks.c
> index 6f94f5c8a0c3..9651e582791e 100644
> --- a/security/ipe/hooks.c
> +++ b/security/ipe/hooks.c
> @@ -192,3 +195,51 @@ void ipe_sb_free_security(struct super_block *mnt_sb)
> {
> ipe_invalidate_pinned_sb(mnt_sb);
> }
> +
> +#ifdef CONFIG_IPE_PROP_DM_VERITY
> +/**
> + * ipe_bdev_free_security - free IPE's LSM blob of block_devices.
> + * @bdev: Supplies a pointer to a block_device that contains the structure
> + * to free.
> + */
> +void ipe_bdev_free_security(struct block_device *bdev)
> +{
> + struct ipe_bdev *blob = ipe_bdev(bdev);
> +
> + kfree(blob->digest);
> + kfree(blob->digest_algo);
> +}
> +
> +/**
> + * ipe_bdev_setsecurity - save data from a bdev to IPE's LSM blob.
> + * @bdev: Supplies a pointer to a block_device that contains the LSM blob.
> + * @key: Supplies the string key that uniquely identifies the value.
> + * @value: Supplies the value to store.
> + * @len: The length of @value.
> + */
> +int ipe_bdev_setsecurity(struct block_device *bdev, const char *key,
> + const void *value, size_t len)
> +{
> + struct ipe_bdev *blob = ipe_bdev(bdev);

Before you can interpret the @key value, you need to first determine
which type of block device you have been handed. It is possible that
multiple block device types could share the same key with very
different meanings for that key, yes?

> + if (!strcmp(key, DM_VERITY_ROOTHASH_SEC_NAME)) {
> + const struct dm_verity_digest *digest = value;
> +
> + blob->digest = kmemdup(digest->digest, digest->digest_len, GFP_KERNEL);
> + if (!blob->digest)
> + return -ENOMEM;
> +
> + blob->digest_algo = kstrdup_const(digest->algo, GFP_KERNEL);
> + if (!blob->digest_algo)
> + return -ENOMEM;
> +
> + blob->digest_len = digest->digest_len;
> + return 0;
> + } else if (!strcmp(key, DM_VERITY_SIGNATURE_SEC_NAME)) {
> + blob->dm_verity_signed = true;
> + return 0;
> + }
> +
> + return -EOPNOTSUPP;
> +}
> +#endif /* CONFIG_IPE_PROP_DM_VERITY */

--
paul-moore.com

2023-07-12 04:34:48

by Fan Wu

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Fri, Jul 07, 2023 at 10:53:45AM -0400, Mike Snitzer wrote:
Thanks for the review!

> On Wed, Jun 28 2023 at 5:09P -0400,
> Fan Wu <[email protected]> wrote:
>
> > From: Deven Bowers <[email protected]>
> >
> > dm-verity provides a strong guarantee of a block device's integrity. As
> > a generic way to check the integrity of a block device, it provides
> > those integrity guarantees to its higher layers, including the filesystem
> > level.
> >
> > An LSM that control access to a resource on the system based on the
> > available integrity claims can use this transitive property of
> > dm-verity, by querying the underlying block_device of a particular
> > file.
> >
> > The digest and signature information need to be stored in the block
> > device to fulfill the next requirement of authorization via LSM policy.
> > This will enable the LSM to perform revocation of devices that are still
> > mounted, prohibiting execution of files that are no longer authorized
> > by the LSM in question.
> >
> > This patch added two security hook calls in dm-verity to save the
> > dm-verity roothash and the roothash signature to LSM blobs.
> >
> > Signed-off-by: Deven Bowers <[email protected]>
> > Signed-off-by: Fan Wu <[email protected]>
> > ---
...
> > diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
> > index 4836508ea50c..33165dd7470f 100644
> > --- a/drivers/md/dm-verity-verify-sig.c
> > +++ b/drivers/md/dm-verity-verify-sig.c
> > @@ -9,6 +9,9 @@
> > #include <linux/verification.h>
> > #include <keys/user-type.h>
> > #include <linux/module.h>
> > +#include <linux/security.h>
> > +#include <linux/dm-verity.h>
> > +#include "dm-core.h"
>
> Why are you including dm-core.h here?
This is used to get the complete definition of struct mapped_device to extract
the struct block_device from it.

>
> > #include "dm-verity.h"
> > #include "dm-verity-verify-sig.h"
> >
> > @@ -97,14 +100,17 @@ int verity_verify_sig_parse_opt_args(struct dm_arg_set *as,
> > * verify_verify_roothash - Verify the root hash of the verity hash device
> > * using builtin trusted keys.
> > *
> > + * @bdev: block_device representing the device-mapper created block device.
> > + * Used by the security hook, to set information about the block_device.
> > * @root_hash: For verity, the roothash/data to be verified.
> > * @root_hash_len: Size of the roothash/data to be verified.
> > * @sig_data: The trusted signature that verifies the roothash/data.
> > * @sig_len: Size of the signature.
> > *
> > */
> > -int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
> > - const void *sig_data, size_t sig_len)
> > +int verity_verify_root_hash(struct block_device *bdev, const void *root_hash,
> > + size_t root_hash_len, const void *sig_data,
> > + size_t sig_len)
> > {
> > int ret;
> >
> > @@ -126,8 +132,12 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
> > NULL,
> > #endif
> > VERIFYING_UNSPECIFIED_SIGNATURE, NULL, NULL);
> > + if (ret)
> > + return ret;
> >
> > - return ret;
> > + return security_bdev_setsecurity(bdev,
> > + DM_VERITY_SIGNATURE_SEC_NAME,
> > + sig_data, sig_len);
> > }
> >
> > void verity_verify_sig_opts_cleanup(struct dm_verity_sig_opts *sig_opts)
>
> Both of your calls to security_bdev_setsecurity() to set your blobs in
> the bdev are suspect because you're doing so from the verity_ctr().
> The mapped_device has 2 dm_table slots (active and inactive). The
> verity_ctr() becomes part of the inactive slot, there is an extra step
> to bind the inactive table to the active table.
>
> This leads to you changing the blobs in the global bdev _before_ the
> table is actually active. It is possible that the inactive table will
> simply be removed and the DM verity device put back in service;
> leaving your blob(s) in the bdev inconsistent.
>
> This issue has parallels to how we need to defer changing the global
> queue_limits associated with a request_queue until _after_ all table
> loading is settled and then the update is done just before resuming
> the DM device (mapped_device) -- see dm_table_set_restrictions().
>
> Unfortunately, this feels like it may require a new hook in the
> target_type struct (e.g. ->finalize())
>
> Mike
Thanks for pointing out this issue. We were calling security_bdev_setsecurity()
because the roothash signature data is only available in verity_ctr()
and it is discarded after verity_ctr() finishes.
After digging deeper into the table_load, I realized that we were indeed
wrong here.

Based on my understanding of your suggestion, it seems that the correct
approach would be to save the roothash signature into the struct dm_target
and then invoke security_bdev_setsecurity() before activating
the inactive table in the __bind function (where dm_table_set_restrictions is called).

To facilitate this process, it seems appropriate to introduce a new hook
called finalize() within the struct target_type. This hook would enable
targets to define tasks that need to be completed before activating
a new table.

In our specific case, we would add a finalize hook to the dm-verity module,
allowing us to call security_bdev_setsecurity() and associate the roothash
information in the struct dm_target with the struct block_device of
the struct mapped_device. Is this correct?

Thanks,
- Fan


2023-07-25 21:42:23

by Paul Moore

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Tue, Jul 11, 2023 at 11:43 PM Fan Wu <[email protected]> wrote:
> On Fri, Jul 07, 2023 at 10:53:45AM -0400, Mike Snitzer wrote:

...

> > Both of your calls to security_bdev_setsecurity() to set your blobs in
> > the bdev are suspect because you're doing so from the verity_ctr().
> > The mapped_device has 2 dm_table slots (active and inactive). The
> > verity_ctr() becomes part of the inactive slot, there is an extra step
> > to bind the inactive table to the active table.
> >
> > This leads to you changing the blobs in the global bdev _before_ the
> > table is actually active. It is possible that the inactive table will
> > simply be removed and the DM verity device put back in service;
> > leaving your blob(s) in the bdev inconsistent.
> >
> > This issue has parallels to how we need to defer changing the global
> > queue_limits associated with a request_queue until _after_ all table
> > loading is settled and then the update is done just before resuming
> > the DM device (mapped_device) -- see dm_table_set_restrictions().
> >
> > Unfortunately, this feels like it may require a new hook in the
> > target_type struct (e.g. ->finalize())
>
> Thanks for pointing out this issue. We were calling security_bdev_setsecurity()
> because the roothash signature data is only available in verity_ctr()
> and it is discarded after verity_ctr() finishes.
> After digging deeper into the table_load, I realized that we were indeed
> wrong here.
>
> Based on my understanding of your suggestion, it seems that the correct
> approach would be to save the roothash signature into the struct dm_target

Would you be doing this with a LSM hook, or would this live in the
device mapper layer?

> and then invoke security_bdev_setsecurity() before activating
> the inactive table in the __bind function (where dm_table_set_restrictions is called).
>
> To facilitate this process, it seems appropriate to introduce a new hook
> called finalize() within the struct target_type. This hook would enable
> targets to define tasks that need to be completed before activating
> a new table.
>
> In our specific case, we would add a finalize hook to the dm-verity module,
> allowing us to call security_bdev_setsecurity() and associate the roothash
> information in the struct dm_target with the struct block_device of
> the struct mapped_device. Is this correct?

Where would the finalize() hook be called?

--
paul-moore.com

2023-08-09 02:15:00

by Fan Wu

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Tue, Jul 25, 2023 at 04:43:48PM -0400, Paul Moore wrote:
> On Tue, Jul 11, 2023 at 11:43???PM Fan Wu <[email protected]> wrote:
> > On Fri, Jul 07, 2023 at 10:53:45AM -0400, Mike Snitzer wrote:
>
> ...
>
> > > Both of your calls to security_bdev_setsecurity() to set your blobs in
> > > the bdev are suspect because you're doing so from the verity_ctr().
> > > The mapped_device has 2 dm_table slots (active and inactive). The
> > > verity_ctr() becomes part of the inactive slot, there is an extra step
> > > to bind the inactive table to the active table.
> > >
> > > This leads to you changing the blobs in the global bdev _before_ the
> > > table is actually active. It is possible that the inactive table will
> > > simply be removed and the DM verity device put back in service;
> > > leaving your blob(s) in the bdev inconsistent.
> > >
> > > This issue has parallels to how we need to defer changing the global
> > > queue_limits associated with a request_queue until _after_ all table
> > > loading is settled and then the update is done just before resuming
> > > the DM device (mapped_device) -- see dm_table_set_restrictions().
> > >
> > > Unfortunately, this feels like it may require a new hook in the
> > > target_type struct (e.g. ->finalize())
> >
> > Thanks for pointing out this issue. We were calling security_bdev_setsecurity()
> > because the roothash signature data is only available in verity_ctr()
> > and it is discarded after verity_ctr() finishes.
> > After digging deeper into the table_load, I realized that we were indeed
> > wrong here.
> >
> > Based on my understanding of your suggestion, it seems that the correct
> > approach would be to save the roothash signature into the struct dm_target
>
Sorry for the delay in responding. It took me a while to test out the design idea
suggested by Mike.

The current implementation is indeed incorrect. However, I've been able to develop
a working prototype that addresses the problem identified in the existing implementation.
I still need some additional time to fine-tune and clean up the prototype.

My goal is to have everything ready and send it out next month.

> Would you be doing this with a LSM hook, or would this live in the
> device mapper layer?
>
In my implemention, it is a new hook in the device mapper layer.
The hook is triggered just before activating an inactive table of a mapped device.
So in our case, we use the hook to attached the dm-verity's roothash metadata
to the block_device struct of mapped device.

> > and then invoke security_bdev_setsecurity() before activating
> > the inactive table in the __bind function (where dm_table_set_restrictions is called).
> >
> > To facilitate this process, it seems appropriate to introduce a new hook
> > called finalize() within the struct target_type. This hook would enable
> > targets to define tasks that need to be completed before activating
> > a new table.
> >
> > In our specific case, we would add a finalize hook to the dm-verity module,
> > allowing us to call security_bdev_setsecurity() and associate the roothash
> > information in the struct dm_target with the struct block_device of
> > the struct mapped_device. Is this correct?
>
> Where would the finalize() hook be called?

It is in the __bind function in drivers/md/dm.c, calling just before
rcu_assign_pointer(md->map, (void *)t) which activates the inactive table.

-Fan

2023-08-09 03:16:58

by Alasdair G Kergon

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Tue, Aug 08, 2023 at 03:45:03PM -0700, Fan Wu wrote:
> On Tue, Jul 25, 2023 at 04:43:48PM -0400, Paul Moore wrote:
> > Where would the finalize() hook be called?
>
> It is in the __bind function in drivers/md/dm.c, calling just before
> rcu_assign_pointer(md->map, (void *)t) which activates the inactive table.

That would be after the existing commit point, meaning the table swap
cannot be cancelled there, so is the finalize() you are proposing void()
i.e. designed so it always succeeds?

Alasdair


2023-08-09 19:13:30

by Fan Wu

[permalink] [raw]
Subject: Re: [RFC PATCH v10 11/17] dm-verity: consume root hash digest and signature data via LSM hook

On Wed, Aug 09, 2023 at 12:40:23AM +0100, Alasdair G Kergon wrote:
> On Tue, Aug 08, 2023 at 03:45:03PM -0700, Fan Wu wrote:
> > On Tue, Jul 25, 2023 at 04:43:48PM -0400, Paul Moore wrote:
> > > Where would the finalize() hook be called?
> >
> > It is in the __bind function in drivers/md/dm.c, calling just before
> > rcu_assign_pointer(md->map, (void *)t) which activates the inactive table.
>
> That would be after the existing commit point, meaning the table swap
> cannot be cancelled there, so is the finalize() you are proposing void()
> i.e. designed so it always succeeds?
>
> Alasdair

Thanks for the input.

Actually, no, the hook can be failed. I noticed the existing call before rcu_assign_pointer(md->map, (void *)t);
(https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/md/dm.c#n2255)
can also be failed so I was following the same pattern.

Could you explain a bit more about the "commit point"? It sounds like it might be better to move
the hook call just before the commit point instead.

-Fan