Skip to contentSkip to conversation

IMA: restrict the accepted digest algorithms for the security.ima xattr

PATCH Superseded THOBY Simon 3 participants 20 messages Aug 4, 2021 – Aug 10, 2021

Subsystems (4)

v6 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v6 cover IMA: restrict the accepted digest algorithms for the security.ima xattr

IMA protects files by storing a hash (or a signature thereof) of their content in the security.ima xattr. While the security.ima xattr itself is protected by EVM with either a HMAC or a digital signature, no mechanism is currently in place to ensure that the security.ima xattr was generated with a strong digest algorithm, and any hash defined in the kernel will be accepted, even obsolete formats like MD4 and MD5.

The kernel itself will only write this xattr with the 'ima_hash' parameter, fixed at init, but it will also happily accept userland writes for said xattr, and those writes may use arbitrary hash algorithms as long as the kernel have support for it.

One important point is safeguarding users from mislabelling their files when using userland utilities to update their files, as this is the kind of behavior one can observe with evmctl (evmctl ima_hash defaults to sha1). Another group that may be interested is those that have deployed IMA years ago, possibly using algorithms that was then deemed sufficiently collision-resistant, but that proved to be weak with the passage of time (note that this could also happen in the future with algorithms considered safe today). This patch provides a migration path of sorts for these users.

This patch series gives users the ability to restrict the algorithms accepted by their system, both when writing/updating xattrs, and when appraising files, while retaining a permissive behavior by default to preserve backward compatibility.

To provide these features, alter the behavior of setxattr to only accept hashes built in the kernel, instead of any hash listed in the kernel (complete list crypto/hash_info.c). In addition, the user can define in his IMA policy the list of digest algorithms allowed for writing to the security.ima xattr. In that case, only algorithms present in that list are accepted for writing.

In addition, users may opt-in to allowlist hash algorithms for ppraising thanks to the new "appraise_hash" IMA policy option. By default IMA will keep accepting any hash algorithm, but specifying that option will make appraisal of files hashed with another algorithm fail.

Even when using this option to restrict accepted hashes, a migration to a new algorithm is still possible. Suppose your policy states you must migrate from 'old_algo' (e.g. sha1) to 'new_algo' (e.g. one of sha256/384/512). You can upgrade without relaxing the hash requirements:
alter your policy rules from 'appraise_hash=old_algo' to 'appraise_hash=old_algo,new_algo', load a new SETXATTR_CHECK policy rule that accept writes using 'new_algo', reboot, relabel all your files with 'new_algo', alter your policy rules from 'appraise_hash=old_algo,new_algo' to 'appraise_hash=new_algo', and you're done.
While this represent a significant amount of work, it is important to showcase that this patchset is flexible enough to let users upgrade if needed.

Here is also a short description of the new audit messages, but I can send it in a followup mail if that is not the proper place:

When writing the xattr with an algorithm not built in the kernel (here the kernel was built with CONFIG_CRYPTO_MD5 unset), e.g. with "evmctl ima_hash -a md5 /usr/bin/strace":

	audit(1628066120.418:121): pid=1344 uid=0 auid=0 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 op=collect_data cause=unavailable-hash-algorithm comm="evmctl" name="/usr/bin/strace" dev="dm-0" ino=2632657 res=0 errno=0

With the same command and the policy rule
"appraise func=SETXATTR_CHECK appraise_hash=sha256,sha384,sha512", we get:

	audit(1628066210.141:127): pid=1362 uid=0 auid=0 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 op=collect_data cause=denied-hash-algorithm comm="evmctl" name="/usr/bin/strace" dev="dm-0" ino=2632657 res=0 errno=0

Note that the cause is now 'denied-hash-algorithm' instead of 'unavailable-hash-algorithm'. We get that audit message for any algorithm outside of sha256/384/512 (including MD5). In a sense, 'denied-hash-algorithm' take predecence over 'unavailable-hash-algorithm'.

When appraising files, e.g. trying to execute a file whose xattr was hashed with sha1 while the policy rule
"appraise func=BPRM_CHECK fowner=0 appraise_hash=sha256" is enabled:

	audit(1628066349.230:130): pid=1369 uid=0 auid=0 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 op=collect_data cause=denied-hash-algorithm comm="bash" name="/usr/bin/strace" dev="dm-0" ino=2632657 res=0 errno=0

This yields the same error message when appraising a file and updating a xattr with an invalid algorithm. Maybe that is not a desired behavior ?

This series is based on the following repo/branch:
repo: https://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity.git
branch: next-integrity-testing
commit e37be5343ae2b9419aea1442b07e5d2428b437b4 ("Merge branch 'ima-buffer-measurement-changes-v4' into next-integrity")

Changelog since v5:
- Adapt a few places where lines were longer than 80 characters (suggested by Mimi Zohar)
- Rebase on top on next-integrity-testing (suggested by Mimi Zohar)
- Replace "whitelist" with "allowlist" (suggested by both Mimi Zohar and Lakshmi Ramasubramanian)
- Fix a broken kernel-doc (suggested by Mimi Zohar)
- Prune the feature that updated "func=SETXATTR_CHECK" (suggested by Mimi Zohar)
- Update the commit messages with suggestions from Lakshmi Ramasubramanian
- Short-circuit a bit the evaluation in ima_appraise.c/validate_hash_algo to return earlier in case of memory exhaustion (suggested by Lakshmi Ramasubramanian)
- Renamed "forbidden-hash-algorithm" in ima_main.c to reduce the number of

Changelog since v4:
- Deleting the ability to remove SETXATTR_CHECK rules, as it added a lot of concurrency troubles while creating a special case for SETXATTR_CHECK rules only, which is rarely a good idea (suggested by Mimi Zohar)
- Change from #ifdef CONFIG_... to IS_ENABLED (suggested by Mimi Zohar)
- Various fixes (code style, english grammar errors, double initialization to zero) reported by Mimi Zohar
- Fixed a logic inversion error introduced in v4 where checks where performed when no SETXATTR_CHECK rule was enabled.
- Do not log partial audit messages under memory pressure (suggested by Mimi Zohar)

Changelog since v3:
- fixed an issue where the first write to the policy would ignore the SETXATTR_CHECK attribute
- fixed potential concurrency issues (I would greatly like external opinions on this, because I clearly don't know much about RCU. Beside maybe it's better to completely ignore the duplicates SETXATTR_CHECK issue and not update the IMA policy in any case)
- remove the CONFIG_CRYPTO_MD5 requirement for IMA (suggested by Mimi Zohar)
- updated commit messages to follow more closely the kernel style guide (suggested by Mimi Zohar)
- moved the hash verification code on appraisal a bit later, to prevent issues when using the code with IMA in a disable/auditing mode (suggested by Mimi Zohar)
- limit the 'appraise_hash' parameter to the 'appraise' action (suggested by Mimi Zohar)

Changelog since v2:
- remove the SecureBoot-specific behavior (suggested by Mimi Zohar)
- users can now tweak through policy both the algorithms for appraising files (a feature already present in v2) and for writing with the new SETXATTR_CHECK value for the 'func' ima policy flag
- updating 'forbidden-hash-algorithm' to 'denied-hash-algorithm' and 'unsupported-hash-algorithm' to disambiguate cases when the user asked for an algorithm not present in the kernel and when the system vendor explicitly opted in to a restricted list of accepted algorithms (suggested by Mimi Zohar)
- change the order of the patches to be bisect-safe while retaining the guarantee that a policy cannot be accepted but not enforced (suggested by Mimi Zohar)

Changelog since v1:
- Remove the two boot parameters (suggested by Mimi Zohar)
- filter out hash algorithms not compiled in the kernel on xattr writes (suggested by Mimi Zohar)
- add a special case when secure boot is enabled: only the ima_hash algorithm is accepted on userland writes
- add a policy option to opt-in to restricting digest algorithms at a per-rule granularity (suggested by Mimi Zohar)

Simon Thoby (5):
IMA: remove the dependency on CRYPTO_MD5
IMA: block writes of the security.ima xattr with unsupported
algorithms
IMA: add support to restrict the hash algorithms used for file
appraisal
IMA: add a policy option to restrict xattr hash algorithms on
appraisal
IMA: introduce a new policy option func=SETXATTR_CHECK

 Documentation/ABI/testing/ima_policy  |  15 ++-
 security/integrity/ima/Kconfig        |   1 -
 security/integrity/ima/ima.h          |  14 ++-
 security/integrity/ima/ima_api.c      |   6 +-
 security/integrity/ima/ima_appraise.c |  73 ++++++++++-
 security/integrity/ima/ima_main.c     |  23 +++-
 security/integrity/ima/ima_policy.c   | 169 +++++++++++++++++++++++---
 7 files changed, 267 insertions(+), 34 deletions(-)
Signature · 1 line
2.31.1
#1 lore raw

PATCH v6 1/5 IMA: remove the dependency on CRYPTO_MD5

MD5 is a weak digest algorithm that shouldn't be used for cryptographic operation. It hinders the efficiency of a patch set that aims to limit the digests allowed for the extended file attribute namely security.ima. MD5 is no longer a requirement for IMA, nor should it be used there.

Remove the CRYPTO_MD5 dependency for IMA.

---
 security/integrity/ima/Kconfig    | 1 -
 security/integrity/ima/ima_main.c | 3 ++-
 2 files changed, 2 insertions(+), 2 deletions(-)
security/integrity/ima/Kconfig +0 -1
index d0ceada99243..f3a9cc201c8c 100644
@@ -6,7 +6,6 @@ config IMA
 	select SECURITYFS
 	select CRYPTO
 	select CRYPTO_HMAC
-	select CRYPTO_MD5
 	select CRYPTO_SHA1
 	select CRYPTO_HASH_INFO
 	select TCG_TPM if HAS_IOMEM && !UML
security/integrity/ima/ima_main.c +2 -1
index 1cba6beb5a60..b70ee0125168 100644
@@ -53,7 +53,8 @@ static int __init hash_setup(char *str)
 	if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
 		if (strncmp(str, "sha1", 4) == 0) {
 			ima_hash_algo = HASH_ALGO_SHA1;
-		} else if (strncmp(str, "md5", 3) == 0) {
+		} else if (IS_ENABLED(CONFIG_CRYPTO_MD5)
+			   && strncmp(str, "md5", 3) == 0) {
 			ima_hash_algo = HASH_ALGO_MD5;
 		} else {
 			pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
Signature · 1 line
2.31.1
Reviewed-by on v6 1/5
#2 lore raw

Re: [PATCH v6 1/5] IMA: remove the dependency on CRYPTO_MD5

Quoted 6 lines · THOBY Simon

MD5 is a weak digest algorithm that shouldn't be used for cryptographic operation. It hinders the efficiency of a patch set that aims to limit the digests allowed for the extended file attribute namely security.ima. MD5 is no longer a requirement for IMA, nor should it be used there.

Remove the CRYPTO_MD5 dependency for IMA.

Quoted 34 lines
---
  security/integrity/ima/Kconfig    | 1 -
  security/integrity/ima/ima_main.c | 3 ++-
  2 files changed, 2 insertions(+), 2 deletions(-)
security/integrity/ima/Kconfig +0 -1
index d0ceada99243..f3a9cc201c8c 100644
@@ -6,7 +6,6 @@ config IMA
  	select SECURITYFS
  	select CRYPTO
  	select CRYPTO_HMAC
-	select CRYPTO_MD5
  	select CRYPTO_SHA1
  	select CRYPTO_HASH_INFO
  	select TCG_TPM if HAS_IOMEM && !UML
security/integrity/ima/ima_main.c +2 -1
index 1cba6beb5a60..b70ee0125168 100644
@@ -53,7 +53,8 @@ static int __init hash_setup(char *str)
  	if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
  		if (strncmp(str, "sha1", 4) == 0) {
  			ima_hash_algo = HASH_ALGO_SHA1;
-		} else if (strncmp(str, "md5", 3) == 0) {
+		} else if (IS_ENABLED(CONFIG_CRYPTO_MD5)
+			   && strncmp(str, "md5", 3) == 0) {
  			ima_hash_algo = HASH_ALGO_MD5;
  		} else {
  			pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
maintainer
#3 lore raw

Re: [PATCH v6 1/5] IMA: remove the dependency on CRYPTO_MD5

In reply to THOBY Simon
Quoted 30 lines · THOBY Simon

MD5 is a weak digest algorithm that shouldn't be used for cryptographic operation. It hinders the efficiency of a patch set that aims to limit the digests allowed for the extended file attribute namely security.ima. MD5 is no longer a requirement for IMA, nor should it be used there.

Remove the CRYPTO_MD5 dependency for IMA.

---
 security/integrity/ima/Kconfig    | 1 -
 security/integrity/ima/ima_main.c | 3 ++-
 2 files changed, 2 insertions(+), 2 deletions(-)
security/integrity/ima/Kconfig +0 -1
index d0ceada99243..f3a9cc201c8c 100644
@@ -6,7 +6,6 @@ config IMA
 	select SECURITYFS
 	select CRYPTO
 	select CRYPTO_HMAC
-	select CRYPTO_MD5
 	select CRYPTO_SHA1
 	select CRYPTO_HASH_INFO
 	select TCG_TPM if HAS_IOMEM && !UML
security/integrity/ima/ima_main.c +0 -0
index 1cba6beb5a60..b70ee0125168 100644

security/integrity/ima/ima_main.c static int __init hash_setup(char *str) · line 60

Quoted 9 lines
security/integrity/ima/ima_main.c +2 -1
@@ -53,7 +53,8 @@ static int __init hash_setup(char *str)
 	if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
 		if (strncmp(str, "sha1", 4) == 0) {
 			ima_hash_algo = HASH_ALGO_SHA1;
-		} else if (strncmp(str, "md5", 3) == 0) {
+		} else if (IS_ENABLED(CONFIG_CRYPTO_MD5)
+			   && strncmp(str, "md5", 3) == 0) {
 			ima_hash_algo = HASH_ALGO_MD5;
 		} else {
 			pr_err("invalid hash algorithm \"%s\" for template \"%s\"",

FYI, with the non "ima" template formats and MD5 is not configured, it fails with the following messages:

ima: Can not allocate md5 (reason: -2)
ima: Allocating md5 failed, going to use default hash algorithm sha256

thanks,

Mimi

#4 lore raw

PATCH v6 2/5 IMA: block writes of the security.ima xattr with unsupported algorithms

In reply to THOBY Simon

By default, writes to the extended attributes security.ima will be allowed even if the hash algorithm used for the xattr is not compiled in the kernel (which does not make sense because the kernel would not be able to appraise that file as it lacks support for validating the hash).

Prevent writes to the security.ima xattr if the hash algorithm used is not available in the current kernel. Lo an audit message if such an operation is attempted.

---
 security/integrity/ima/ima.h          |  2 +-
 security/integrity/ima/ima_appraise.c | 49 ++++++++++++++++++++++++++-
 2 files changed, 49 insertions(+), 2 deletions(-)
security/integrity/ima/ima.h +1 -1
index 2f4c20b16ad7..829478dabeeb 100644
@@ -319,7 +319,7 @@ int ima_must_appraise(struct user_namespace *mnt_userns, struct inode *inode,
 void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file);
 enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint,
 					   enum ima_hooks func);
-enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
+enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
 				 int xattr_len);
 int ima_read_xattr(struct dentry *dentry,
 		   struct evm_ima_xattr_data **xattr_value);
security/integrity/ima/ima_appraise.c +48 -1

67 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v6 2/5
#5 lore raw

Re: [PATCH v6 2/5] IMA: block writes of the security.ima xattr with unsupported algorithms

Quoted 9 lines · THOBY Simon

By default, writes to the extended attributes security.ima will be allowed even if the hash algorithm used for the xattr is not compiled in the kernel (which does not make sense because the kernel would not be able to appraise that file as it lacks support for validating the hash).

Prevent writes to the security.ima xattr if the hash algorithm used is not available in the current kernel. Lo an audit message if such an operation is attempted.

Typo: Lo => Log

Quoted 95 lines
---
  security/integrity/ima/ima.h          |  2 +-
  security/integrity/ima/ima_appraise.c | 49 ++++++++++++++++++++++++++-
  2 files changed, 49 insertions(+), 2 deletions(-)
security/integrity/ima/ima.h +1 -1
index 2f4c20b16ad7..829478dabeeb 100644
@@ -319,7 +319,7 @@ int ima_must_appraise(struct user_namespace *mnt_userns, struct inode *inode,
  void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file);
  enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint,
  					   enum ima_hooks func);
-enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
+enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
  				 int xattr_len);
  int ima_read_xattr(struct dentry *dentry,
  		   struct evm_ima_xattr_data **xattr_value);
security/integrity/ima/ima_appraise.c +48 -1
index 63bec42c353f..ed1a98f6ee19 100644
@@ -171,7 +171,7 @@ static void ima_cache_flags(struct integrity_iint_cache *iint,
  	}
  }
 
-enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
+enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
  				 int xattr_len)
  {
  	struct signature_v2_hdr *sig;
@@ -575,6 +575,51 @@ static void ima_reset_appraise_flags(struct inode *inode, int digsig)
  		clear_bit(IMA_DIGSIG, &iint->atomic_flags);
  }
 
+/**
+ * validate_hash_algo() - Block setxattr with invalid digests
+ * @dentry: object being setxattr()'ed
+ * @xattr_value: value supplied by userland for the xattr
+ * @xattr_value_len: length of xattr_value
+ *
+ * Context: called when the user tries to write the security.ima xattr.
+ * The xattr value is mapped to some hash algorithm, and this algorithm
+ * must be built in the kernel for the setxattr to be allowed.
+ *
+ * Emit an audit message when the algorithm is invalid.
+ *
+ * Return: 0 on success, else an error.
+ */
+static int validate_hash_algo(struct dentry *dentry,
+				   const struct evm_ima_xattr_data *xattr_value,
+				   size_t xattr_value_len)
+{
+	int result = 0;
+	char *path = NULL, *pathbuf = NULL;
+	enum hash_algo xattr_hash_algo;
+
+	xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
+
+	if (likely(xattr_hash_algo == ima_hash_algo ||
+		   crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
+		return result;
+
+	result = -EACCES;
+
+	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
+	if (!pathbuf)
+		return result;
+
+	path = dentry_path(dentry, pathbuf, PATH_MAX);
+
+	integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
+			    "collect_data", "unavailable-hash-algorithm",
+			    result, 0);
+
+	kfree(pathbuf);
+
+	return result;
+}
+
  int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
  		       const void *xattr_value, size_t xattr_value_len)
  {
@@ -595,6 +640,8 @@ int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
  		ima_reset_appraise_flags(d_backing_inode(dentry), digsig);
  		if (result == 1)
  			result = 0;
+
+		result = validate_hash_algo(dentry, xvalue, xattr_value_len);
  	}
  	return result;
  }
maintainer
#6 lore raw

Re: [PATCH v6 2/5] IMA: block writes of the security.ima xattr with unsupported algorithms

In reply to THOBY Simon
Quoted 9 lines · THOBY Simon

By default, writes to the extended attributes security.ima will be allowed even if the hash algorithm used for the xattr is not compiled in the kernel (which does not make sense because the kernel would not be able to appraise that file as it lacks support for validating the hash).

Prevent writes to the security.ima xattr if the hash algorithm used is not available in the current kernel. Lo an audit message if such an operation is attempted.

Both "log" and "audit" can be used as verbs. Perhaps update the first
line to be "Prevent and audit writes...", making the last line unnecessary.

Quoted 34 lines
---
 security/integrity/ima/ima.h          |  2 +-
 security/integrity/ima/ima_appraise.c | 49 ++++++++++++++++++++++++++-
 2 files changed, 49 insertions(+), 2 deletions(-)
security/integrity/ima/ima.h +1 -1
index 2f4c20b16ad7..829478dabeeb 100644
@@ -319,7 +319,7 @@ int ima_must_appraise(struct user_namespace *mnt_userns, struct inode *inode,
 void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file);
 enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint,
 					   enum ima_hooks func);
-enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
+enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
 				 int xattr_len);
 int ima_read_xattr(struct dentry *dentry,
 		   struct evm_ima_xattr_data **xattr_value);
security/integrity/ima/ima_appraise.c +1 -1
index 63bec42c353f..ed1a98f6ee19 100644
@@ -171,7 +171,7 @@ static void ima_cache_flags(struct integrity_iint_cache *iint,
 	}
 }
 
-enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
+enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
 				 int xattr_len)
 {
 	struct signature_v2_hdr *sig;

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 578

Quoted 4 lines
security/integrity/ima/ima_appraise.c +1 -0
@@ -575,6 +575,51 @@ static void ima_reset_appraise_flags(struct inode *inode, int digsig)
 		clear_bit(IMA_DIGSIG, &iint->atomic_flags);
 }
 
+/**

Just a reminder, static functions don't require kernel-doc.

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 579

Quoted 1 line
security/integrity/ima/ima_appraise.c +1 -0
+ * validate_hash_algo() - Block setxattr with invalid digests

The digest might be valid, but the algorithm is unsupported. Perhaps "Block setxattr with unsupported hash algorithms" would be more accurate.

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 580

Quoted 1 line
security/integrity/ima/ima_appraise.c +1 -0
+ * @dentry: object being setxattr()'ed

^object of the setxattr()

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 581

Quoted 1 line
security/integrity/ima/ima_appraise.c +1 -0
+ * @xattr_value: value supplied by userland for the xattr

userland supplied xattr value

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 584

Quoted 3 lines
security/integrity/ima/ima_appraise.c +3 -0
+ * @xattr_value_len: length of xattr_value
+ *
+ * Context: called when the user tries to write the security.ima xattr.

Hm, "context" is probably unnecessary.

From here:

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 589

Quoted 5 lines
security/integrity/ima/ima_appraise.c +5 -0
+ * The xattr value is mapped to some hash algorithm, and this algorithm
+ * must be built in the kernel for the setxattr to be allowed.
+ *
+ * Emit an audit message when the algorithm is invalid.
+ *

to here: is the longer summary, which would be before the "Context:" if it is defined.

Quoted 7 lines
security/integrity/ima/ima_appraise.c +7 -0
+ * Return: 0 on success, else an error.
+ */
+static int validate_hash_algo(struct dentry *dentry,
+				   const struct evm_ima_xattr_data *xattr_value,
+				   size_t xattr_value_len)
+{
+	int result = 0;

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 606

Quoted 10 lines
security/integrity/ima/ima_appraise.c +10 -0
+	char *path = NULL, *pathbuf = NULL;
+	enum hash_algo xattr_hash_algo;
+
+	xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
+
+	if (likely(xattr_hash_algo == ima_hash_algo ||
+		   crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
+		return result;
+
+	result = -EACCES;

Unless there is a common function exit, I would just hard code the return value.

Quoted 20 lines
security/integrity/ima/ima_appraise.c +16 -0
+
+	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
+	if (!pathbuf)
+		return result;
+
+	path = dentry_path(dentry, pathbuf, PATH_MAX);
+
+	integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
+			    "collect_data", "unavailable-hash-algorithm",
+			    result, 0);
+
+	kfree(pathbuf);
+
+	return result;
+}
+
 int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
 		       const void *xattr_value, size_t xattr_value_len)
 {

security/integrity/ima/ima_appraise.c int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name, · line 644

Quoted 5 lines
security/integrity/ima/ima_appraise.c +2 -0
@@ -595,6 +640,8 @@ int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
 		ima_reset_appraise_flags(d_backing_inode(dentry), digsig);
 		if (result == 1)
 			result = 0;
+
+		result = validate_hash_algo(dentry, xvalue, xattr_value_len);

On failure to validate the hash algorithm, the file will unnecessarily be re-verified. Only on success the appraise flags should be reset.

thanks,

Mimi

Quoted 3 lines
security/integrity/ima/ima_appraise.c +0 -0
 	}
 	return result;
 }
maintainer
#7 lore raw

Re: [PATCH v6 2/5] IMA: block writes of the security.ima xattr with unsupported algorithms

In reply to THOBY Simon
Quoted 15 lines · THOBY Simon
security/integrity/ima/ima_appraise.c +15 -0
+static int validate_hash_algo(struct dentry *dentry,
+                                  const struct evm_ima_xattr_data *xattr_value,
+                                  size_t xattr_value_len)
+{
+       int result = 0;
+       char *path = NULL, *pathbuf = NULL;
+       enum hash_algo xattr_hash_algo;
+
+       xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
+
+       if (likely(xattr_hash_algo == ima_hash_algo ||
+                  crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
+               return result;
+
+       result = -EACCES;

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 616

Quoted 10 lines
security/integrity/ima/ima_appraise.c +10 -0
+
+       pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
+       if (!pathbuf)
+               return result;
+
+       path = dentry_path(dentry, pathbuf, PATH_MAX);
+
+       integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
+                           "collect_data", "unavailable-hash-algorithm",
+                           result, 0);

"collect_data" refers to calculating the file hash, ima_collect_measurement(), which may be stored in the measurement list, used for verifying the signature and/or included in the audit record.

validate_hash_algo() verifies the hash algorithm before allowing the file hash or signature to be written as security.ima. Instead of "collect_data" it should be "set_data" or something similar.

thanks,

Mimi

Quoted 4 lines
security/integrity/ima/ima_appraise.c +4 -0
+
+       kfree(pathbuf);
+
+       return result;
#8 lore raw

Re: [PATCH v6 2/5] IMA: block writes of the security.ima xattr with unsupported algorithms

Hi Mimi,

Quoted 31 lines · Mimi Zohar
Quoted 15 lines · THOBY Simon
security/integrity/ima/ima_appraise.c +15 -0
+static int validate_hash_algo(struct dentry *dentry,
+                                  const struct evm_ima_xattr_data *xattr_value,
+                                  size_t xattr_value_len)
+{
+       int result = 0;
+       char *path = NULL, *pathbuf = NULL;
+       enum hash_algo xattr_hash_algo;
+
+       xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
+
+       if (likely(xattr_hash_algo == ima_hash_algo ||
+                  crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
+               return result;
+
+       result = -EACCES;

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 616

Quoted 10 lines
security/integrity/ima/ima_appraise.c +10 -0
+
+       pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
+       if (!pathbuf)
+               return result;
+
+       path = dentry_path(dentry, pathbuf, PATH_MAX);
+
+       integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
+                           "collect_data", "unavailable-hash-algorithm",
+                           result, 0);

"collect_data" refers to calculating the file hash, ima_collect_measurement(), which may be stored in the measurement list, used for verifying the signature and/or included in the audit record.

Quoted 3 lines

validate_hash_algo() verifies the hash algorithm before allowing the file hash or signature to be written as security.ima. Instead of "collect_data" it should be "set_data" or something similar.

I will update that in the next patchset.

Quoted 11 lines

thanks,

Mimi

security/integrity/ima/ima_appraise.c static void ima_reset_appraise_flags(struct inode *inode, int digsig) · line 620

Quoted 4 lines
security/integrity/ima/ima_appraise.c +4 -0
+
+       kfree(pathbuf);
+
+       return result;

Thanks,
Simon

#9 lore raw

PATCH v6 3/5 IMA: add support to restrict the hash algorithms used for file appraisal

In reply to THOBY Simon

The kernel accepts any hash algorithm as a value for the security.ima xattr. Users may wish to restrict the accepted algorithms to only support strong cryptographic ones.

Provide the plumbing to restrict the permitted set of hash algorithms used for verifying file hashes and digest algorithms stored in security.ima xattr.

This do not apply only to IMA in hash mode, it also works with digital signatures, where the hash from which the signature is derived (by signing it with the trusted private key) must obey the same restrictions.

---
 security/integrity/ima/ima.h          |  6 +++---
 security/integrity/ima/ima_api.c      |  6 ++++--
 security/integrity/ima/ima_appraise.c |  5 +++--
 security/integrity/ima/ima_main.c     | 18 +++++++++++++++---
 security/integrity/ima/ima_policy.c   | 18 ++++++++++++++++--
 5 files changed, 41 insertions(+), 12 deletions(-)
security/integrity/ima/ima.h +3 -3
index 829478dabeeb..8db0238a0fd6 100644
@@ -47,7 +47,7 @@ enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
 extern int ima_policy_flag;
 
 /* set during initialization */
-extern int ima_hash_algo;
+extern int ima_hash_algo __ro_after_init;
 extern int ima_sha1_idx __ro_after_init;
 extern int ima_hash_algo_idx __ro_after_init;
 extern int ima_extra_slots __ro_after_init;
@@ -254,7 +254,7 @@ int ima_get_action(struct user_namespace *mnt_userns, struct inode *inode,
 		   const struct cred *cred, u32 secid, int mask,
 		   enum ima_hooks func, int *pcr,
 		   struct ima_template_desc **template_desc,
-		   const char *func_data);
+		   const char *func_data, unsigned int *allowed_hashes);
 int ima_must_measure(struct inode *inode, int mask, enum ima_hooks func);
 int ima_collect_measurement(struct integrity_iint_cache *iint,
 			    struct file *file, void *buf, loff_t size,
@@ -285,7 +285,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 		     const struct cred *cred, u32 secid, enum ima_hooks func,
 		     int mask, int flags, int *pcr,
 		     struct ima_template_desc **template_desc,
-		     const char *func_data);
+		     const char *func_data, unsigned int *allowed_hashes);
 void ima_init_policy(void);
 void ima_update_policy(void);
 void ima_update_policy_flag(void);
security/integrity/ima/ima_api.c +4 -2
index d8e321cc6936..3dc41d997dc5 100644
@@ -172,6 +172,7 @@ void ima_add_violation(struct file *file, const unsigned char *filename,
  * @pcr: pointer filled in if matched measure policy sets pcr=
  * @template_desc: pointer filled in if matched measure policy sets template=
  * @func_data: func specific data, may be NULL
+ * @allowed_hashes: allowlist of hash algorithms for the IMA xattr
  *
  * The policy is defined in terms of keypairs:
  *		subj=, obj=, type=, func=, mask=, fsmagic=
@@ -188,14 +189,15 @@ int ima_get_action(struct user_namespace *mnt_userns, struct inode *inode,
 		   const struct cred *cred, u32 secid, int mask,
 		   enum ima_hooks func, int *pcr,
 		   struct ima_template_desc **template_desc,
-		   const char *func_data)
+		   const char *func_data, unsigned int *allowed_hashes)
 {
 	int flags = IMA_MEASURE | IMA_AUDIT | IMA_APPRAISE | IMA_HASH;
 
 	flags &= ima_policy_flag;
 
 	return ima_match_policy(mnt_userns, inode, cred, secid, func, mask,
-				flags, pcr, template_desc, func_data);
+				flags, pcr, template_desc, func_data,
+				allowed_hashes);
 }
 
 /*
security/integrity/ima/ima_appraise.c +3 -2
index ed1a98f6ee19..9aa0334b8e54 100644
@@ -77,8 +77,9 @@ int ima_must_appraise(struct user_namespace *mnt_userns, struct inode *inode,
 		return 0;
 
 	security_task_getsecid_subj(current, &secid);
-	return ima_match_policy(mnt_userns, inode, current_cred(), secid, func,
-				mask, IMA_APPRAISE | IMA_HASH, NULL, NULL, NULL);
+	return ima_match_policy(mnt_userns, inode, current_cred(), secid,
+				func, mask, IMA_APPRAISE | IMA_HASH, NULL,
+				NULL, NULL, NULL);
 }
 
 static int ima_fix_xattr(struct dentry *dentry,
security/integrity/ima/ima_main.c +15 -3
index b70ee0125168..205138e7016d 100644
@@ -216,6 +216,7 @@ static int process_measurement(struct file *file, const struct cred *cred,
 	int xattr_len = 0;
 	bool violation_check;
 	enum hash_algo hash_algo;
+	unsigned int allowed_hashes = 0;
 
 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
 		return 0;
@@ -225,7 +226,8 @@ static int process_measurement(struct file *file, const struct cred *cred,
 	 * Included is the appraise submask.
 	 */
 	action = ima_get_action(file_mnt_user_ns(file), inode, cred, secid,
-				mask, func, &pcr, &template_desc, NULL);
+				mask, func, &pcr, &template_desc, NULL,
+				&allowed_hashes);
 	violation_check = ((func == FILE_CHECK || func == MMAP_CHECK) &&
 			   (ima_policy_flag & IMA_MEASURE));
 	if (!action && !violation_check)
@@ -362,6 +364,16 @@ static int process_measurement(struct file *file, const struct cred *cred,
 
 	if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
 		rc = 0;
+
+	/* Ensure the digest was generated using an allowed algorithm */
+	if (rc == 0 && must_appraise && allowed_hashes != 0 &&
+	    (allowed_hashes & (1U << hash_algo)) == 0) {
+		rc = -EACCES;
+
+		integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
+				    pathname, "collect_data",
+				    "denied-hash-algorithm", rc, 0);
+	}
 out_locked:
 	if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
 	     !(iint->flags & IMA_NEW_FILE))
@@ -439,7 +451,7 @@ int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
 	inode = file_inode(vma->vm_file);
 	action = ima_get_action(file_mnt_user_ns(vma->vm_file), inode,
 				current_cred(), secid, MAY_EXEC, MMAP_CHECK,
-				&pcr, &template, NULL);
+				&pcr, &template, NULL, NULL);
 
 	/* Is the mmap'ed file in policy? */
 	if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
@@ -897,7 +909,7 @@ int process_buffer_measurement(struct user_namespace *mnt_userns,
 		security_task_getsecid_subj(current, &secid);
 		action = ima_get_action(mnt_userns, inode, current_cred(),
 					secid, 0, func, &pcr, &template,
-					func_data);
+					func_data, NULL);
 		if (!(action & IMA_MEASURE) && !digest)
 			return -ENOENT;
 	}
security/integrity/ima/ima_policy.c +16 -2
index fd5d46e511f1..a5b6162535f3 100644
@@ -35,6 +35,7 @@
 #define IMA_FSNAME	0x0200
 #define IMA_KEYRINGS	0x0400
 #define IMA_LABEL	0x0800
+#define IMA_VALIDATE_HASH	0x1000
 
 #define UNKNOWN		0
 #define MEASURE		0x0001	/* same as IMA_MEASURE */
@@ -79,6 +80,7 @@ struct ima_rule_entry {
 	bool (*uid_op)(kuid_t, kuid_t);    /* Handlers for operators       */
 	bool (*fowner_op)(kuid_t, kuid_t); /* uid_eq(), uid_gt(), uid_lt() */
 	int pcr;
+	unsigned int allowed_hashes;
 	struct {
 		void *rule;	/* LSM file metadata specific */
 		char *args_p;	/* audit value */
@@ -90,6 +92,14 @@ struct ima_rule_entry {
 	struct ima_template_desc *template;
 };
 
+/*
+ * sanity check in case the kernels gains more hash algorithms that can
+ * fit in an unsigned int
+ */
+static_assert(
+	8 * sizeof(unsigned int) >= HASH_ALGO__LAST,
+	"The bitfield allowed_hashes in ima_rule_entry is too small to contain all the supported hash algorithms, consider using a bigger type");
+
 /*
  * Without LSM specific knowledge, the default policy can only be
  * written in terms of .action, .func, .mask, .fsmagic, .uid, and .fowner
@@ -646,6 +656,7 @@ static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
  * @pcr: set the pcr to extend
  * @template_desc: the template that should be used for this rule
  * @func_data: func specific data, may be NULL
+ * @allowed_hashes: allowlist of hash algorithms for the IMA xattr
  *
  * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
  * conditions.
@@ -658,7 +669,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 		     const struct cred *cred, u32 secid, enum ima_hooks func,
 		     int mask, int flags, int *pcr,
 		     struct ima_template_desc **template_desc,
-		     const char *func_data)
+		     const char *func_data, unsigned int *allowed_hashes)
 {
 	struct ima_rule_entry *entry;
 	int action = 0, actmask = flags | (flags << 1);
@@ -684,8 +695,11 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 			action &= ~IMA_HASH;
 			if (ima_fail_unverifiable_sigs)
 				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
-		}
 
+			if (allowed_hashes &&
+			    entry->flags & IMA_VALIDATE_HASH)
+				*allowed_hashes = entry->allowed_hashes;
+		}
 
 		if (entry->action & IMA_DO_MASK)
 			actmask &= ~(entry->action | entry->action << 1);
Signature · 1 line
2.31.1
Reviewed-by on v6 3/5
#10 lore raw

Re: [PATCH v6 3/5] IMA: add support to restrict the hash algorithms used for file appraisal

Quoted 4 lines · THOBY Simon

The kernel accepts any hash algorithm as a value for the security.ima xattr. Users may wish to restrict the accepted algorithms to only support strong cryptographic ones.

Quoted 8 lines

Provide the plumbing to restrict the permitted set of hash algorithms used for verifying file hashes and digest algorithms stored in security.ima xattr.

This do not apply only to IMA in hash mode, it also works with digital signatures, where the hash from which the signature is derived (by signing it with the trusted private key) must obey the same restrictions.

Quoted 211 lines
---
  security/integrity/ima/ima.h          |  6 +++---
  security/integrity/ima/ima_api.c      |  6 ++++--
  security/integrity/ima/ima_appraise.c |  5 +++--
  security/integrity/ima/ima_main.c     | 18 +++++++++++++++---
  security/integrity/ima/ima_policy.c   | 18 ++++++++++++++++--
  5 files changed, 41 insertions(+), 12 deletions(-)
security/integrity/ima/ima.h +3 -3
index 829478dabeeb..8db0238a0fd6 100644
@@ -47,7 +47,7 @@ enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
  extern int ima_policy_flag;
 
  /* set during initialization */
-extern int ima_hash_algo;
+extern int ima_hash_algo __ro_after_init;
  extern int ima_sha1_idx __ro_after_init;
  extern int ima_hash_algo_idx __ro_after_init;
  extern int ima_extra_slots __ro_after_init;
@@ -254,7 +254,7 @@ int ima_get_action(struct user_namespace *mnt_userns, struct inode *inode,
  		   const struct cred *cred, u32 secid, int mask,
  		   enum ima_hooks func, int *pcr,
  		   struct ima_template_desc **template_desc,
-		   const char *func_data);
+		   const char *func_data, unsigned int *allowed_hashes);
  int ima_must_measure(struct inode *inode, int mask, enum ima_hooks func);
  int ima_collect_measurement(struct integrity_iint_cache *iint,
  			    struct file *file, void *buf, loff_t size,
@@ -285,7 +285,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
  		     const struct cred *cred, u32 secid, enum ima_hooks func,
  		     int mask, int flags, int *pcr,
  		     struct ima_template_desc **template_desc,
-		     const char *func_data);
+		     const char *func_data, unsigned int *allowed_hashes);
  void ima_init_policy(void);
  void ima_update_policy(void);
  void ima_update_policy_flag(void);
security/integrity/ima/ima_api.c +4 -2
index d8e321cc6936..3dc41d997dc5 100644
@@ -172,6 +172,7 @@ void ima_add_violation(struct file *file, const unsigned char *filename,
   * @pcr: pointer filled in if matched measure policy sets pcr=
   * @template_desc: pointer filled in if matched measure policy sets template=
   * @func_data: func specific data, may be NULL
+ * @allowed_hashes: allowlist of hash algorithms for the IMA xattr
   *
   * The policy is defined in terms of keypairs:
   *		subj=, obj=, type=, func=, mask=, fsmagic=
@@ -188,14 +189,15 @@ int ima_get_action(struct user_namespace *mnt_userns, struct inode *inode,
  		   const struct cred *cred, u32 secid, int mask,
  		   enum ima_hooks func, int *pcr,
  		   struct ima_template_desc **template_desc,
-		   const char *func_data)
+		   const char *func_data, unsigned int *allowed_hashes)
  {
  	int flags = IMA_MEASURE | IMA_AUDIT | IMA_APPRAISE | IMA_HASH;
 
  	flags &= ima_policy_flag;
 
  	return ima_match_policy(mnt_userns, inode, cred, secid, func, mask,
-				flags, pcr, template_desc, func_data);
+				flags, pcr, template_desc, func_data,
+				allowed_hashes);
  }
 
  /*
security/integrity/ima/ima_appraise.c +3 -2
index ed1a98f6ee19..9aa0334b8e54 100644
@@ -77,8 +77,9 @@ int ima_must_appraise(struct user_namespace *mnt_userns, struct inode *inode,
  		return 0;
 
  	security_task_getsecid_subj(current, &secid);
-	return ima_match_policy(mnt_userns, inode, current_cred(), secid, func,
-				mask, IMA_APPRAISE | IMA_HASH, NULL, NULL, NULL);
+	return ima_match_policy(mnt_userns, inode, current_cred(), secid,
+				func, mask, IMA_APPRAISE | IMA_HASH, NULL,
+				NULL, NULL, NULL);
  }
 
  static int ima_fix_xattr(struct dentry *dentry,
security/integrity/ima/ima_main.c +15 -3
index b70ee0125168..205138e7016d 100644
@@ -216,6 +216,7 @@ static int process_measurement(struct file *file, const struct cred *cred,
  	int xattr_len = 0;
  	bool violation_check;
  	enum hash_algo hash_algo;
+	unsigned int allowed_hashes = 0;
 
  	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
  		return 0;
@@ -225,7 +226,8 @@ static int process_measurement(struct file *file, const struct cred *cred,
  	 * Included is the appraise submask.
  	 */
  	action = ima_get_action(file_mnt_user_ns(file), inode, cred, secid,
-				mask, func, &pcr, &template_desc, NULL);
+				mask, func, &pcr, &template_desc, NULL,
+				&allowed_hashes);
  	violation_check = ((func == FILE_CHECK || func == MMAP_CHECK) &&
  			   (ima_policy_flag & IMA_MEASURE));
  	if (!action && !violation_check)
@@ -362,6 +364,16 @@ static int process_measurement(struct file *file, const struct cred *cred,
 
  	if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
  		rc = 0;
+
+	/* Ensure the digest was generated using an allowed algorithm */
+	if (rc == 0 && must_appraise && allowed_hashes != 0 &&
+	    (allowed_hashes & (1U << hash_algo)) == 0) {
+		rc = -EACCES;
+
+		integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
+				    pathname, "collect_data",
+				    "denied-hash-algorithm", rc, 0);
+	}
  out_locked:
  	if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
  	     !(iint->flags & IMA_NEW_FILE))
@@ -439,7 +451,7 @@ int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
  	inode = file_inode(vma->vm_file);
  	action = ima_get_action(file_mnt_user_ns(vma->vm_file), inode,
  				current_cred(), secid, MAY_EXEC, MMAP_CHECK,
-				&pcr, &template, NULL);
+				&pcr, &template, NULL, NULL);
 
  	/* Is the mmap'ed file in policy? */
  	if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
@@ -897,7 +909,7 @@ int process_buffer_measurement(struct user_namespace *mnt_userns,
  		security_task_getsecid_subj(current, &secid);
  		action = ima_get_action(mnt_userns, inode, current_cred(),
  					secid, 0, func, &pcr, &template,
-					func_data);
+					func_data, NULL);
  		if (!(action & IMA_MEASURE) && !digest)
  			return -ENOENT;
  	}
security/integrity/ima/ima_policy.c +16 -2
index fd5d46e511f1..a5b6162535f3 100644
@@ -35,6 +35,7 @@
  #define IMA_FSNAME	0x0200
  #define IMA_KEYRINGS	0x0400
  #define IMA_LABEL	0x0800
+#define IMA_VALIDATE_HASH	0x1000
 
  #define UNKNOWN		0
  #define MEASURE		0x0001	/* same as IMA_MEASURE */
@@ -79,6 +80,7 @@ struct ima_rule_entry {
  	bool (*uid_op)(kuid_t, kuid_t);    /* Handlers for operators       */
  	bool (*fowner_op)(kuid_t, kuid_t); /* uid_eq(), uid_gt(), uid_lt() */
  	int pcr;
+	unsigned int allowed_hashes;
  	struct {
  		void *rule;	/* LSM file metadata specific */
  		char *args_p;	/* audit value */
@@ -90,6 +92,14 @@ struct ima_rule_entry {
  	struct ima_template_desc *template;
  };
 
+/*
+ * sanity check in case the kernels gains more hash algorithms that can
+ * fit in an unsigned int
+ */
+static_assert(
+	8 * sizeof(unsigned int) >= HASH_ALGO__LAST,
+	"The bitfield allowed_hashes in ima_rule_entry is too small to contain all the supported hash algorithms, consider using a bigger type");
+
  /*
   * Without LSM specific knowledge, the default policy can only be
   * written in terms of .action, .func, .mask, .fsmagic, .uid, and .fowner
@@ -646,6 +656,7 @@ static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
   * @pcr: set the pcr to extend
   * @template_desc: the template that should be used for this rule
   * @func_data: func specific data, may be NULL
+ * @allowed_hashes: allowlist of hash algorithms for the IMA xattr
   *
   * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
   * conditions.
@@ -658,7 +669,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
  		     const struct cred *cred, u32 secid, enum ima_hooks func,
  		     int mask, int flags, int *pcr,
  		     struct ima_template_desc **template_desc,
-		     const char *func_data)
+		     const char *func_data, unsigned int *allowed_hashes)
  {
  	struct ima_rule_entry *entry;
  	int action = 0, actmask = flags | (flags << 1);
@@ -684,8 +695,11 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
  			action &= ~IMA_HASH;
  			if (ima_fail_unverifiable_sigs)
  				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
-		}
 
+			if (allowed_hashes &&
+			    entry->flags & IMA_VALIDATE_HASH)
+				*allowed_hashes = entry->allowed_hashes;
+		}
 
  		if (entry->action & IMA_DO_MASK)
  			actmask &= ~(entry->action | entry->action << 1);
maintainer
#11 lore raw

Re: [PATCH v6 3/5] IMA: add support to restrict the hash algorithms used for file appraisal

In reply to THOBY Simon
Quoted 7 lines · THOBY Simon

The kernel accepts any hash algorithm as a value for the security.ima xattr. Users may wish to restrict the accepted algorithms to only support strong cryptographic ones.

Provide the plumbing to restrict the permitted set of hash algorithms used for verifying file hashes and digest algorithms stored in security.ima xattr.

simplify by saying "file hashes and signatures stored ..."

Quoted 5 lines

This do not apply only to IMA in hash mode, it also works with digital signatures, where the hash from which the signature is derived (by signing it with the trusted private key) must obey the same restrictions.

The patch is limited to appraisal. Is the above paragraph needed?

Quoted 3 lines

This patch restricts the "hash algorithms". Looking this over again after some time, does truncating variable names here, and in the other patches, to just "_hash|_hashes" make sense? Perhaps the emphasis should not be on "hash", but on "algo".

security/integrity/ima/ima_policy.c int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode, · line 705

Quoted 13 lines
security/integrity/ima/ima_policy.c +4 -1
@@ -684,8 +695,11 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 			action &= ~IMA_HASH;
 			if (ima_fail_unverifiable_sigs)
 				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
-		}
 
+			if (allowed_hashes &&
+			    entry->flags & IMA_VALIDATE_HASH)
+				*allowed_hashes = entry->allowed_hashes;
+		}
 
 		if (entry->action & IMA_DO_MASK)
 			actmask &= ~(entry->action | entry->action << 1);

"allowed_hashes" sounds like a set of digests. Instead of "allowed_hashes" and "IMA_VALIDATE_HASH", should it be "allowed_algo" and "IMA_ALLOWED_ALGO"?

thanks,

Mimi

#12 lore raw

Re: [PATCH v6 3/5] IMA: add support to restrict the hash algorithms used for file appraisal

Hi Mimi,

Quoted 10 lines · Mimi Zohar
Quoted 7 lines · THOBY Simon

The kernel accepts any hash algorithm as a value for the security.ima xattr. Users may wish to restrict the accepted algorithms to only support strong cryptographic ones.

Provide the plumbing to restrict the permitted set of hash algorithms used for verifying file hashes and digest algorithms stored in security.ima xattr.

simplify by saying "file hashes and signatures stored ..."

Will fix in the next iteration.

Quoted 8 lines
Quoted 6 lines

This do not apply only to IMA in hash mode, it also works with digital signatures, where the hash from which the signature is derived (by signing it with the trusted private key) must obey the same restrictions.

The patch is limited to appraisal. Is the above paragraph needed?

Yes, what I was (badly) trying to say is that the appraisal check work both when the security.ima xattr contains digital signatures and when it contains hashes, as digital signatures can also be generated with different algorithms. Except, as you pointed out, by talking about "hash mode" here, I introduced a confusion where the reader can believe I'm talking of the "hash" IMA policy action. I will try to clarify that.

Quoted 9 lines
Quoted 4 lines

This patch restricts the "hash algorithms". Looking this over again after some time, does truncating variable names here, and in the other patches, to just "_hash|_hashes" make sense? Perhaps the emphasis should not be on "hash", but on "algo".

I will update that (and patch 4/5 consequently).

Quoted 20 lines
Quoted 4 lines
security/integrity/ima/ima_policy.c +0 -0
@@ -684,8 +695,11 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 			action &= ~IMA_HASH;
 			if (ima_fail_unverifiable_sigs)

security/integrity/ima/ima_policy.c int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode, · line 705

Quoted 10 lines
security/integrity/ima/ima_policy.c +4 -1
 				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
-		}
 
+			if (allowed_hashes &&
+			    entry->flags & IMA_VALIDATE_HASH)
+				*allowed_hashes = entry->allowed_hashes;
+		}
 
 		if (entry->action & IMA_DO_MASK)
 			actmask &= ~(entry->action | entry->action << 1);

"allowed_hashes" sounds like a set of digests. Instead of "allowed_hashes" and "IMA_VALIDATE_HASH", should it be "allowed_algo" and "IMA_ALLOWED_ALGO"?

Quoted 4 lines

thanks,

Mimi

Thanks,
Simon

#13 lore raw

PATCH v6 4/5 IMA: add a policy option to restrict xattr hash algorithms on appraisal

In reply to THOBY Simon

The kernel has the ability to restrict the set of hash algorithms it accepts for the security.ima xattr when it appraises files.

Define a new IMA policy rule option "appraise_hash=", using the mentioned mechanism to expose a user-toggable policy knob to opt-in to that restriction and select the desired set of algorithms that must be accepted.

When a policy rule uses the 'appraise_hash' option, appraisal of a file referenced by that rule will now fail if the digest algorithm employed to hash the file was not one of those explicitly listed in the option. In its absence, any hash algorithm compiled in the kernel will be accepted.

For example, on a system where SELinux is properly deployed, the rule
appraise func=BPRM_CHECK obj_type=iptables_exec_t appraise_hash=sha256,sha384
will block the execution of iptables if the xattr security.ima of its executables were not hashed with either sha256 or sha384.

---
 Documentation/ABI/testing/ima_policy |  6 ++-
 security/integrity/ima/ima_policy.c  | 75 ++++++++++++++++++++++++++--
 2 files changed, 76 insertions(+), 5 deletions(-)
Documentation/ABI/testing/ima_policy +5 -1
index 070779e8d836..aeb622698047 100644
@@ -27,7 +27,7 @@ Description:
 			lsm:	[[subj_user=] [subj_role=] [subj_type=]
 				 [obj_user=] [obj_role=] [obj_type=]]
 			option:	[[appraise_type=]] [template=] [permit_directio]
-				[appraise_flag=] [keyrings=]
+				[appraise_flag=] [appraise_hash=] [keyrings=]
 		  base:
 			func:= [BPRM_CHECK][MMAP_CHECK][CREDS_CHECK][FILE_CHECK][MODULE_CHECK]
 			        [FIRMWARE_CHECK]
@@ -55,6 +55,10 @@ Description:
 			label:= [selinux]|[kernel_info]|[data_label]
 			data_label:= a unique string used for grouping and limiting critical data.
 			For example, "selinux" to measure critical data for SELinux.
+			appraise_hash:= comma-separated list of hash algorithms
+			For example, "sha256,sha512" to only accept to appraise
+			files where the security.ima xattr was hashed with one
+			of these two algorithms.
 
 		  default policy:
 			# PROC_SUPER_MAGIC
security/integrity/ima/ima_policy.c +71 -4

129 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v6 4/5
#14 lore raw

Re: [PATCH v6 4/5] IMA: add a policy option to restrict xattr hash algorithms on appraisal

Hi Simon,

Quoted 12 lines · THOBY Simon
---
  Documentation/ABI/testing/ima_policy |  6 ++-
  security/integrity/ima/ima_policy.c  | 75 ++++++++++++++++++++++++++--
  2 files changed, 76 insertions(+), 5 deletions(-)
security/integrity/ima/ima_policy.c +3 -0
+static unsigned int ima_parse_appraise_hash(char *arg)
+{
+	unsigned int res = 0;

security/integrity/ima/ima_policy.c static bool ima_validate_rule(struct ima_rule_entry *entry) · line 1204

Quoted 10 lines
security/integrity/ima/ima_policy.c +10 -0
+	int idx;
+	char *token;
+
+	while ((token = strsep(&arg, ",")) != NULL) {
+		idx = match_string(hash_algo_name, HASH_ALGO__LAST, token);
+
+		if (idx < 0) {
+			pr_err("unknown hash algorithm \"%s\", ignoring",
+			       token);
+			continue;

Is it right to ignore an invalid digest algorithm given in the IMA policy rule? Should "invalid ima policy" error be reported instead?

Other changes look good.

-lakshmi

Quoted 77 lines
security/integrity/ima/ima_policy.c +52 -0
+		}
+
+		/* Add the hash algorithm to the 'allowed' bitfield */
+		res |= (1U << idx);
+	}
+
+	return res;
+}
+
  static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
  {
  	struct audit_buffer *ab;
@@ -1522,6 +1546,26 @@ static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
  			else
  				result = -EINVAL;
  			break;
+		case Opt_appraise_hash:
+			ima_log_string(ab, "appraise_hash", args[0].from);
+
+			if (entry->allowed_hashes) {
+				result = -EINVAL;
+				break;
+			}
+
+			entry->allowed_hashes =
+				ima_parse_appraise_hash(args[0].from);
+
+			/* invalid or empty list of algorithms */
+			if (!entry->allowed_hashes) {
+				result = -EINVAL;
+				break;
+			}
+
+			entry->flags |= IMA_VALIDATE_HASH;
+
+			break;
  		case Opt_permit_directio:
  			entry->flags |= IMA_PERMIT_DIRECTIO;
  			break;
@@ -1714,6 +1758,23 @@ static void ima_show_rule_opt_list(struct seq_file *m,
  		seq_printf(m, "%s%s", i ? "|" : "", opt_list->items[i]);
  }
 
+static void ima_policy_show_appraise_hash(struct seq_file *m,
+					  unsigned int allowed_hashes)
+{
+	int idx, list_size = 0;
+
+	for (idx = 0; idx < HASH_ALGO__LAST; idx++) {
+		if (!(allowed_hashes & (1U << idx)))
+			continue;
+
+		/* only add commas if the list contains multiple entries */
+		if (list_size++)
+			seq_puts(m, ",");
+
+		seq_puts(m, hash_algo_name[idx]);
+	}
+}
+
  int ima_policy_show(struct seq_file *m, void *v)
  {
  	struct ima_rule_entry *entry = v;
@@ -1825,6 +1886,12 @@ int ima_policy_show(struct seq_file *m, void *v)
  		seq_puts(m, " ");
  	}
 
+	if (entry->flags & IMA_VALIDATE_HASH) {
+		seq_puts(m, "appraise_hash=");
+		ima_policy_show_appraise_hash(m, entry->allowed_hashes);
+		seq_puts(m, " ");
+	}
+
  	for (i = 0; i < MAX_LSM_RULES; i++) {
  		if (entry->lsm[i].rule) {
  			switch (i) {
#15 lore raw

Re: [PATCH v6 4/5] IMA: add a policy option to restrict xattr hash algorithms on appraisal

Quoted 12 lines · Lakshmi Ramasubramanian

Hi Simon,

Quoted 7 lines · THOBY Simon

---
  Documentation/ABI/testing/ima_policy |  6 ++- security/integrity/ima/ima_policy.c  | 75 ++++++++++++++++++++++++++--

  2 files changed, 76 insertions(+), 5 deletions(-)
Quoted 14 lines

security/integrity/ima/ima_policy.c static bool ima_validate_rule(struct ima_rule_entry *entry) · line 1204

Quoted 13 lines

  +static unsigned int ima_parse_appraise_hash(char *arg)

security/integrity/ima/ima_policy.c +12 -0
+{
+    unsigned int res = 0;
+    int idx;
+    char *token;
+
+    while ((token = strsep(&arg, ",")) != NULL) {
+        idx = match_string(hash_algo_name, HASH_ALGO__LAST, token);
+
+        if (idx < 0) {
+            pr_err("unknown hash algorithm \"%s\", ignoring",
+                   token);
+            continue;

Is it right to ignore an invalid digest algorithm given in the IMA policy rule? Should "invalid ima policy" error be reported instead?

Um no you're right, better be strict in what we accept, or users may start depending on it. I'll update that.

Thanks,
Simon

Quoted 82 lines

Other changes look good.

 -lakshmi

Quoted 75 lines

+        }

security/integrity/ima/ima_policy.c +8 -0
+
+        /* Add the hash algorithm to the 'allowed' bitfield */
+        res |= (1U << idx);
+    }
+
+    return res;
+}
+

  static int ima_parse_rule(char *rule, struct ima_rule_entry *entry) {
      struct audit_buffer *ab;

(quoted diff) +0 -0
@@ -1522,6 +1546,26 @@ static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)

              else
                  result = -EINVAL;
              break;
+        case Opt_appraise_hash:
+            ima_log_string(ab, "appraise_hash", args[0].from);

security/integrity/ima/ima_policy.c +18 -0
+
+            if (entry->allowed_hashes) {
+                result = -EINVAL;
+                break;
+            }
+
+            entry->allowed_hashes =
+                ima_parse_appraise_hash(args[0].from);
+
+            /* invalid or empty list of algorithms */
+            if (!entry->allowed_hashes) {
+                result = -EINVAL;
+                break;
+            }
+
+            entry->flags |= IMA_VALIDATE_HASH;
+
+            break;

          case Opt_permit_directio:
              entry->flags |= IMA_PERMIT_DIRECTIO; break;

security/integrity/ima/ima_policy.c +21 -0
@@ -1714,6 +1758,23 @@ static void ima_show_rule_opt_list(struct seq_file *m,
           seq_printf(m, "%s%s", i ? "|" : "", opt_list->items[i]);
   }
   +static void ima_policy_show_appraise_hash(struct seq_file *m,
+                      unsigned int allowed_hashes)
+{
+    int idx, list_size = 0;
+
+    for (idx = 0; idx < HASH_ALGO__LAST; idx++) {
+        if (!(allowed_hashes & (1U << idx)))
+            continue;
+
+        /* only add commas if the list contains multiple entries */
+        if (list_size++)
+            seq_puts(m, ",");
+
+        seq_puts(m, hash_algo_name[idx]);
+    }
+}
+
   int ima_policy_show(struct seq_file *m, void *v)
   {
       struct ima_rule_entry *entry = v;
@@ -1825,6 +1886,12 @@ int ima_policy_show(struct seq_file *m, void *v)
           seq_puts(m, " ");
       }
   +    if (entry->flags & IMA_VALIDATE_HASH) {
+        seq_puts(m, "appraise_hash=");
+        ima_policy_show_appraise_hash(m, entry->allowed_hashes);
+        seq_puts(m, " ");
+    }
+
       for (i = 0; i < MAX_LSM_RULES; i++) {
           if (entry->lsm[i].rule) {
               switch (i) {
maintainer
#16 lore raw

Re: [PATCH v6 4/5] IMA: add a policy option to restrict xattr hash algorithms on appraisal

In reply to THOBY Simon

Documentation/ABI/testing/ima_policy Description: · line 30

Quoted 10 lines · THOBY Simon
Documentation/ABI/testing/ima_policy +1 -1
index 070779e8d836..aeb622698047 100644
@@ -27,7 +27,7 @@ Description:
 			lsm:	[[subj_user=] [subj_role=] [subj_type=]
 				 [obj_user=] [obj_role=] [obj_type=]]
 			option:	[[appraise_type=]] [template=] [permit_directio]
-				[appraise_flag=] [keyrings=]
+				[appraise_flag=] [appraise_hash=] [keyrings=]

Continuing the suggestion from 3/5, perhaps the new option should be named "appraise_algo=".

Quoted 4 lines
Documentation/ABI/testing/ima_policy +0 -0
 		  base:
 			func:= [BPRM_CHECK][MMAP_CHECK][CREDS_CHECK][FILE_CHECK][MODULE_CHECK]
 			        [FIRMWARE_CHECK]

Documentation/ABI/testing/ima_policy Description: · line 64

Quoted 10 lines
Documentation/ABI/testing/ima_policy +4 -0
@@ -55,6 +55,10 @@ Description:
 			label:= [selinux]|[kernel_info]|[data_label]
 			data_label:= a unique string used for grouping and limiting critical data.
 			For example, "selinux" to measure critical data for SELinux.
+			appraise_hash:= comma-separated list of hash algorithms
+			For example, "sha256,sha512" to only accept to appraise
+			files where the security.ima xattr was hashed with one
+			of these two algorithms.
 
 		  default policy:
 			# PROC_SUPER_MAGIC

thanks,

Mimi

#17 lore raw

PATCH v6 5/5 IMA: introduce a new policy option func=SETXATTR_CHECK

In reply to THOBY Simon

While users can restrict the accepted hash algorithms for the security.ima xattr file signature when appraising said file, users cannot restrict the algorithms that can be set on that attribute:
any algorithm built in the kernel is accepted on a write.

Define a new value for the ima policy option 'func' that restricts globally the hash algorithms accepted when writing the security.ima xattr.

When a policy contains a rule of the form
appraise func=SETXATTR_CHECK appraise_hash=sha256,sha384,sha512
only values corresponding to one of these three digest algorithms will be accepted for writing the security.ima xattr. Attempting to write the attribute using another algorithm (or "free-form" data) will be denied with an audit log message.
In the absence of such a policy rule, the default is still to only accept hash algorithms built in the kernel (with all the limitations that entails).

---
 Documentation/ABI/testing/ima_policy  |  9 +++-
 security/integrity/ima/ima.h          |  6 ++-
 security/integrity/ima/ima_appraise.c | 29 ++++++++--
 security/integrity/ima/ima_main.c     |  2 +-
 security/integrity/ima/ima_policy.c   | 76 +++++++++++++++++++++++----
 5 files changed, 104 insertions(+), 18 deletions(-)
Documentation/ABI/testing/ima_policy +8 -1
index aeb622698047..537be0e1720e 100644
@@ -30,9 +30,10 @@ Description:
 				[appraise_flag=] [appraise_hash=] [keyrings=]
 		  base:
 			func:= [BPRM_CHECK][MMAP_CHECK][CREDS_CHECK][FILE_CHECK][MODULE_CHECK]
-			        [FIRMWARE_CHECK]
+				[FIRMWARE_CHECK]
 				[KEXEC_KERNEL_CHECK] [KEXEC_INITRAMFS_CHECK]
 				[KEXEC_CMDLINE] [KEY_CHECK] [CRITICAL_DATA]
+				[SETXATTR_CHECK]
 			mask:= [[^]MAY_READ] [[^]MAY_WRITE] [[^]MAY_APPEND]
 			       [[^]MAY_EXEC]
 			fsmagic:= hex value
@@ -138,3 +139,9 @@ Description:
 		keys added to .builtin_trusted_keys or .ima keyring:
 
 			measure func=KEY_CHECK keyrings=.builtin_trusted_keys|.ima
+
+		Example of the special SETXATTR_CHECK appraise rule, that
+		restricts the hash algorithms allowed when writing to the
+		security.ima xattr of a file:
+
+			appraise func=SETXATTR_CHECK appraise_hash=sha256,sha384,sha512
security/integrity/ima/ima.h +5 -1
index 8db0238a0fd6..7f2aa875fd72 100644
@@ -46,6 +46,9 @@ enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
 /* current content of the policy */
 extern int ima_policy_flag;
 
+/* bitset of digests algorithms allowed in the setxattr hook */
+extern atomic_t ima_setxattr_allowed_hash_algorithms;
+
 /* set during initialization */
 extern int ima_hash_algo __ro_after_init;
 extern int ima_sha1_idx __ro_after_init;
@@ -198,6 +201,7 @@ static inline unsigned int ima_hash_key(u8 *digest)
 	hook(KEXEC_CMDLINE, kexec_cmdline)		\
 	hook(KEY_CHECK, key)				\
 	hook(CRITICAL_DATA, critical_data)		\
+	hook(SETXATTR_CHECK, setxattr_check)		\
 	hook(MAX_CHECK, none)
 
 #define __ima_hook_enumify(ENUM, str)	ENUM,
@@ -288,7 +292,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
 		     const char *func_data, unsigned int *allowed_hashes);
 void ima_init_policy(void);
 void ima_update_policy(void);
-void ima_update_policy_flag(void);
+void ima_update_policy_flags(void);
 ssize_t ima_parse_add_rule(char *);
 void ima_delete_rules(void);
 int ima_check_policy(void);
security/integrity/ima/ima_appraise.c +24 -5
index 9aa0334b8e54..4949aabce36c 100644
@@ -597,12 +597,32 @@ static int validate_hash_algo(struct dentry *dentry,
 	int result = 0;
 	char *path = NULL, *pathbuf = NULL;
 	enum hash_algo xattr_hash_algo;
+	const char *errmsg = "unavailable-hash-algorithm";
+	unsigned int allowed_hashes;
 
 	xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
 
-	if (likely(xattr_hash_algo == ima_hash_algo ||
-		   crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
-		return result;
+	allowed_hashes = atomic_read(&ima_setxattr_allowed_hash_algorithms);
+
+	if (allowed_hashes) {
+		/* success if the algorithm is allowed in the ima policy */
+		if (allowed_hashes & (1U << xattr_hash_algo))
+			return result;
+
+		/*
+		 * We use a different audit message when the hash algorithm
+		 * is denied by a policy rule, instead of not being built
+		 * in the kernel image
+		 */
+		errmsg = "denied-hash-algorithm";
+	} else {
+		if (likely(xattr_hash_algo == ima_hash_algo))
+			return result;
+
+		/* allow any xattr using an algorithm built in the kernel */
+		if (crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0))
+			return result;
+	}
 
 	result = -EACCES;
 
@@ -613,8 +633,7 @@ static int validate_hash_algo(struct dentry *dentry,
 	path = dentry_path(dentry, pathbuf, PATH_MAX);
 
 	integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
-			    "collect_data", "unavailable-hash-algorithm",
-			    result, 0);
+			    "collect_data", errmsg, result, 0);
 
 	kfree(pathbuf);
 
security/integrity/ima/ima_main.c +1 -1
index 205138e7016d..f6389f0ff81b 100644
@@ -1052,7 +1052,7 @@ static int __init init_ima(void)
 		pr_warn("Couldn't register LSM notifier, error %d\n", error);
 
 	if (!error)
-		ima_update_policy_flag();
+		ima_update_policy_flags();
 
 	return error;
 }
security/integrity/ima/ima_policy.c +66 -10

122 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v6 5/5
#18 lore raw

Re: [PATCH v6 5/5] IMA: introduce a new policy option func=SETXATTR_CHECK

Quoted 33 lines · THOBY Simon

While users can restrict the accepted hash algorithms for the security.ima xattr file signature when appraising said file, users cannot restrict the algorithms that can be set on that attribute:
any algorithm built in the kernel is accepted on a write.

Define a new value for the ima policy option 'func' that restricts globally the hash algorithms accepted when writing the security.ima xattr.

When a policy contains a rule of the form
appraise func=SETXATTR_CHECK appraise_hash=sha256,sha384,sha512
only values corresponding to one of these three digest algorithms will be accepted for writing the security.ima xattr. Attempting to write the attribute using another algorithm (or "free-form" data) will be denied with an audit log message.
In the absence of such a policy rule, the default is still to only accept hash algorithms built in the kernel (with all the limitations that entails).

---
  Documentation/ABI/testing/ima_policy  |  9 +++-
  security/integrity/ima/ima.h          |  6 ++-
  security/integrity/ima/ima_appraise.c | 29 ++++++++--
  security/integrity/ima/ima_main.c     |  2 +-
  security/integrity/ima/ima_policy.c   | 76 +++++++++++++++++++++++----
  5 files changed, 104 insertions(+), 18 deletions(-)
Documentation/ABI/testing/ima_policy +0 -0
index aeb622698047..537be0e1720e 100644

Documentation/ABI/testing/ima_policy Description: · line 33

Quoted 5 lines
Documentation/ABI/testing/ima_policy +1 -1
@@ -30,9 +30,10 @@ Description:
  				[appraise_flag=] [appraise_hash=] [keyrings=]
  		  base:
  			func:= [BPRM_CHECK][MMAP_CHECK][CREDS_CHECK][FILE_CHECK][MODULE_CHECK]
-			        [FIRMWARE_CHECK]
+				[FIRMWARE_CHECK]

Is there a white space in the above line that is showing up as a change in this patch?

Other changes look good.

-lakshmi

Quoted 243 lines
Documentation/ABI/testing/ima_policy +7 -0
  				[KEXEC_KERNEL_CHECK] [KEXEC_INITRAMFS_CHECK]
  				[KEXEC_CMDLINE] [KEY_CHECK] [CRITICAL_DATA]
+				[SETXATTR_CHECK]
  			mask:= [[^]MAY_READ] [[^]MAY_WRITE] [[^]MAY_APPEND]
  			       [[^]MAY_EXEC]
  			fsmagic:= hex value
@@ -138,3 +139,9 @@ Description:
  		keys added to .builtin_trusted_keys or .ima keyring:
 
  			measure func=KEY_CHECK keyrings=.builtin_trusted_keys|.ima
+
+		Example of the special SETXATTR_CHECK appraise rule, that
+		restricts the hash algorithms allowed when writing to the
+		security.ima xattr of a file:
+
+			appraise func=SETXATTR_CHECK appraise_hash=sha256,sha384,sha512
security/integrity/ima/ima.h +5 -1
index 8db0238a0fd6..7f2aa875fd72 100644
@@ -46,6 +46,9 @@ enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
  /* current content of the policy */
  extern int ima_policy_flag;
 
+/* bitset of digests algorithms allowed in the setxattr hook */
+extern atomic_t ima_setxattr_allowed_hash_algorithms;
+
  /* set during initialization */
  extern int ima_hash_algo __ro_after_init;
  extern int ima_sha1_idx __ro_after_init;
@@ -198,6 +201,7 @@ static inline unsigned int ima_hash_key(u8 *digest)
  	hook(KEXEC_CMDLINE, kexec_cmdline)		\
  	hook(KEY_CHECK, key)				\
  	hook(CRITICAL_DATA, critical_data)		\
+	hook(SETXATTR_CHECK, setxattr_check)		\
  	hook(MAX_CHECK, none)
 
  #define __ima_hook_enumify(ENUM, str)	ENUM,
@@ -288,7 +292,7 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
  		     const char *func_data, unsigned int *allowed_hashes);
  void ima_init_policy(void);
  void ima_update_policy(void);
-void ima_update_policy_flag(void);
+void ima_update_policy_flags(void);
  ssize_t ima_parse_add_rule(char *);
  void ima_delete_rules(void);
  int ima_check_policy(void);
security/integrity/ima/ima_appraise.c +24 -5
index 9aa0334b8e54..4949aabce36c 100644
@@ -597,12 +597,32 @@ static int validate_hash_algo(struct dentry *dentry,
  	int result = 0;
  	char *path = NULL, *pathbuf = NULL;
  	enum hash_algo xattr_hash_algo;
+	const char *errmsg = "unavailable-hash-algorithm";
+	unsigned int allowed_hashes;
 
  	xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
 
-	if (likely(xattr_hash_algo == ima_hash_algo ||
-		   crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0)))
-		return result;
+	allowed_hashes = atomic_read(&ima_setxattr_allowed_hash_algorithms);
+
+	if (allowed_hashes) {
+		/* success if the algorithm is allowed in the ima policy */
+		if (allowed_hashes & (1U << xattr_hash_algo))
+			return result;
+
+		/*
+		 * We use a different audit message when the hash algorithm
+		 * is denied by a policy rule, instead of not being built
+		 * in the kernel image
+		 */
+		errmsg = "denied-hash-algorithm";
+	} else {
+		if (likely(xattr_hash_algo == ima_hash_algo))
+			return result;
+
+		/* allow any xattr using an algorithm built in the kernel */
+		if (crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0))
+			return result;
+	}
 
  	result = -EACCES;
 
@@ -613,8 +633,7 @@ static int validate_hash_algo(struct dentry *dentry,
  	path = dentry_path(dentry, pathbuf, PATH_MAX);
 
  	integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
-			    "collect_data", "unavailable-hash-algorithm",
-			    result, 0);
+			    "collect_data", errmsg, result, 0);
 
  	kfree(pathbuf);
 
security/integrity/ima/ima_main.c +1 -1
index 205138e7016d..f6389f0ff81b 100644
@@ -1052,7 +1052,7 @@ static int __init init_ima(void)
  		pr_warn("Couldn't register LSM notifier, error %d\n", error);
 
  	if (!error)
-		ima_update_policy_flag();
+		ima_update_policy_flags();
 
  	return error;
  }
security/integrity/ima/ima_policy.c +66 -10
index 831ce0c690ec..c83f7c199610 100644
@@ -53,6 +53,8 @@ int ima_policy_flag;
  static int temp_ima_appraise;
  static int build_ima_appraise __ro_after_init;
 
+atomic_t ima_setxattr_allowed_hash_algorithms;
+
  #define MAX_LSM_RULES 6
  enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
  	LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
@@ -720,24 +722,57 @@ int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
  	return action;
  }
 
-/*
- * Initialize the ima_policy_flag variable based on the currently
- * loaded policy.  Based on this flag, the decision to short circuit
- * out of a function or not call the function in the first place
- * can be made earlier.
+/**
+ * ima_update_policy_flags() - Update global IMA variables
+ *
+ * Update ima_policy_flag and ima_setxattr_allowed_hash_algorithms
+ * based on the currently loaded policy.
+ *
+ * With ima_policy_flag, the decision to short circuit out of a function
+ * or not call the function in the first place can be made earlier.
+ *
+ * With ima_setxattr_allowed_hash_algorithms, the policy can restrict the
+ * set of hash algorithms accepted when updating the security.ima xattr of
+ * a file.
+ *
+ * Context: called after a policy update and at system initialization.
   */
-void ima_update_policy_flag(void)
+void ima_update_policy_flags(void)
  {
  	struct ima_rule_entry *entry;
+	int new_policy_flag = 0;
 
+	rcu_read_lock();
  	list_for_each_entry(entry, ima_rules, list) {
+		/*
+		 * SETXATTR_CHECK rules do not implement a full policy check
+		 * because rule checking would probably have an important
+		 * performance impact on setxattr(). As a consequence, only one
+		 * SETXATTR_CHECK can be active at a given time.
+		 * Because we want to preserve that property, we set out to use
+		 * atomic_cmpxchg. Either:
+		 * - the atomic was non-zero: a setxattr hash policy is
+		 *   already enforced, we do nothing
+		 * - the atomic was zero: no setxattr policy was set, enable
+		 *   the setxattr hash policy
+		 */
+		if (entry->func == SETXATTR_CHECK) {
+			atomic_cmpxchg(&ima_setxattr_allowed_hash_algorithms,
+				       0, entry->allowed_hashes);
+			/* SETXATTR_CHECK doesn't impact ima_policy_flag */
+			continue;
+		}
+
  		if (entry->action & IMA_DO_MASK)
-			ima_policy_flag |= entry->action;
+			new_policy_flag |= entry->action;
  	}
+	rcu_read_unlock();
 
  	ima_appraise |= (build_ima_appraise | temp_ima_appraise);
  	if (!ima_appraise)
-		ima_policy_flag &= ~IMA_APPRAISE;
+		new_policy_flag &= ~IMA_APPRAISE;
+
+	ima_policy_flag = new_policy_flag;
  }
 
  static int ima_appraise_flag(enum ima_hooks func)
@@ -903,7 +938,9 @@ void __init ima_init_policy(void)
  			  ARRAY_SIZE(critical_data_rules),
  			  IMA_DEFAULT_POLICY);
 
-	ima_update_policy_flag();
+	atomic_set(&ima_setxattr_allowed_hash_algorithms, 0);
+
+	ima_update_policy_flags();
  }
 
  /* Make sure we have a valid policy, at least containing some rules. */
@@ -943,7 +980,7 @@ void ima_update_policy(void)
  		 */
  		kfree(arch_policy_entry);
  	}
-	ima_update_policy_flag();
+	ima_update_policy_flags();
 
  	/* Custom IMA policy has been loaded */
  	ima_process_queued_keys();
@@ -1176,6 +1213,23 @@ static bool ima_validate_rule(struct ima_rule_entry *entry)
  		if (ima_rule_contains_lsm_cond(entry))
  			return false;
 
+		break;
+	case SETXATTR_CHECK:
+		/* any action other than APPRAISE is unsupported */
+		if (entry->action != APPRAISE)
+			return false;
+
+		/* SETXATTR_CHECK requires an appraise_hash parameter */
+		if (!(entry->flags & IMA_VALIDATE_HASH))
+			return false;
+
+		/*
+		 * full policies are not supported, they would have too
+		 * much of a performance impact
+		 */
+		if (entry->flags & ~(IMA_FUNC | IMA_VALIDATE_HASH))
+			return false;
+
  		break;
  	default:
  		return false;
@@ -1332,6 +1386,8 @@ static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
  				entry->func = KEY_CHECK;
  			else if (strcmp(args[0].from, "CRITICAL_DATA") == 0)
  				entry->func = CRITICAL_DATA;
+			else if (strcmp(args[0].from, "SETXATTR_CHECK") == 0)
+				entry->func = SETXATTR_CHECK;
  			else
  				result = -EINVAL;
  			if (!result)
maintainer
#19 lore raw

Re: [PATCH v6 5/5] IMA: introduce a new policy option func=SETXATTR_CHECK

Quoted 15 lines · Lakshmi Ramasubramanian

Documentation/ABI/testing/ima_policy Description: · line 33

Quoted 10 lines · THOBY Simon
Quoted 1 line

Documentation/ABI/testing/ima_policy

Quoted 1 line
Documentation/ABI/testing/ima_policy +0 -0

index aeb622698047..537be0e1720e 100644

Documentation/ABI/testing/ima_policy +1 -1
@@ -30,9 +30,10 @@ Description:
  				[appraise_flag=] [appraise_hash=] [keyrings=]
  		  base:
  			func:= [BPRM_CHECK][MMAP_CHECK][CREDS_CHECK][FILE_CHECK][MODULE_CHECK]
-			        [FIRMWARE_CHECK]
+				[FIRMWARE_CHECK]

Is there a white space in the above line that is showing up as a change in this patch?

Blanks are being replaced with a tab.

Mimi