From 16f3112687e59deb862ebb8f3649310a352b038a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 14 Jun 2022 21:09:53 +1200 Subject: [PATCH 01/68] CVE-2022-32746 s4/dsdb/objectclass_attrs: Fix typo BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/objectclass_attrs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/dsdb/samdb/ldb_modules/objectclass_attrs.c b/source4/dsdb/samdb/ldb_modules/objectclass_attrs.c index 6ab46a729a2..2a77353cdfc 100644 --- a/source4/dsdb/samdb/ldb_modules/objectclass_attrs.c +++ b/source4/dsdb/samdb/ldb_modules/objectclass_attrs.c @@ -263,7 +263,7 @@ static int attr_handler(struct oc_context *ac) LDB_CONTROL_AS_SYSTEM_OID); if (!dsdb_module_am_system(ac->module) && !as_system) { ldb_asprintf_errstring(ldb, - "objectclass_attrs: attribute '%s' on entry '%s' must can only be modified as system", + "objectclass_attrs: attribute '%s' on entry '%s' can only be modified as system", msg->elements[i].name, ldb_dn_get_linearized(msg->dn)); return LDB_ERR_CONSTRAINT_VIOLATION; -- 2.25.1 From c83967ad71ae1fbacb6cec696face96aef1d2e22 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 21 Jun 2022 15:37:15 +1200 Subject: [PATCH 02/68] CVE-2022-32746 s4:dsdb:tests: Add test for deleting a disallowed SPN If an account has an SPN that requires Write Property to set, we should still be able to delete it with just Validated Write. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- selftest/knownfail.d/acl-spn-delete | 1 + source4/dsdb/tests/python/acl.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 selftest/knownfail.d/acl-spn-delete diff --git a/selftest/knownfail.d/acl-spn-delete b/selftest/knownfail.d/acl-spn-delete new file mode 100644 index 00000000000..32018413c49 --- /dev/null +++ b/selftest/knownfail.d/acl-spn-delete @@ -0,0 +1 @@ +^samba4.ldap.acl.python.*__main__.AclSPNTests.test_delete_disallowed_spn\( diff --git a/source4/dsdb/tests/python/acl.py b/source4/dsdb/tests/python/acl.py index 70dca9b7678..3e5f7a44a79 100755 --- a/source4/dsdb/tests/python/acl.py +++ b/source4/dsdb/tests/python/acl.py @@ -2285,6 +2285,32 @@ class AclSPNTests(AclTests): else: self.fail(f'able to add disallowed SPN {not_allowed_spn}') + def test_delete_disallowed_spn(self): + # Grant Validated-SPN property. + mod = f'(OA;;SW;{security.GUID_DRS_VALIDATE_SPN};;{self.user_sid1})' + self.sd_utils.dacl_add_ace(self.computerdn, mod) + + spn_base = f'HOST/{self.computername}' + + not_allowed_spn = f'{spn_base}/{self.dcctx.get_domain_name()}' + + # Add a disallowed SPN as admin. + msg = Message(Dn(self.ldb_admin, self.computerdn)) + msg['servicePrincipalName'] = MessageElement(not_allowed_spn, + FLAG_MOD_ADD, + 'servicePrincipalName') + self.ldb_admin.modify(msg) + + # Ensure we are able to delete a disallowed SPN. + msg = Message(Dn(self.ldb_user1, self.computerdn)) + msg['servicePrincipalName'] = MessageElement(not_allowed_spn, + FLAG_MOD_DELETE, + 'servicePrincipalName') + try: + self.ldb_user1.modify(msg) + except LdbError: + self.fail(f'unable to delete disallowed SPN {not_allowed_spn}') + # tests SEC_ADS_LIST vs. SEC_ADS_LIST_OBJECT @DynamicTestCase -- 2.25.1 From 59cd645b3958eeb7b359ed5b488820070873fac8 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 21 Jun 2022 14:41:02 +1200 Subject: [PATCH 03/68] CVE-2022-32746 s4/dsdb/partition: Fix LDB flags comparison LDB_FLAG_MOD_* values are not actually flags, and the previous comparison was equivalent to (req_msg->elements[el_idx].flags & LDB_FLAG_MOD_MASK) != 0 which is true whenever any of the LDB_FLAG_MOD_* values are set. Correct the expression to what it was probably intended to be. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/partition.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/partition.c b/source4/dsdb/samdb/ldb_modules/partition.c index 2544a106d13..2d90ca5d1b3 100644 --- a/source4/dsdb/samdb/ldb_modules/partition.c +++ b/source4/dsdb/samdb/ldb_modules/partition.c @@ -493,8 +493,8 @@ static int partition_copy_all_callback_action( * them here too */ for (el_idx=0; el_idx < req_msg->num_elements; el_idx++) { - if (req_msg->elements[el_idx].flags & LDB_FLAG_MOD_DELETE - || ((req_msg->elements[el_idx].flags & LDB_FLAG_MOD_REPLACE) && + if (LDB_FLAG_MOD_TYPE(req_msg->elements[el_idx].flags) == LDB_FLAG_MOD_DELETE + || ((LDB_FLAG_MOD_TYPE(req_msg->elements[el_idx].flags) == LDB_FLAG_MOD_REPLACE) && req_msg->elements[el_idx].num_values == 0)) { if (ldb_msg_find_element(modify_msg, req_msg->elements[el_idx].name) != NULL) { -- 2.25.1 From e46e43f76e7731c90ef4c47caa67d233d8c62d9a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 21 Jun 2022 14:49:51 +1200 Subject: [PATCH 04/68] CVE-2022-32746 s4:torture: Fix LDB flags comparison LDB_FLAG_MOD_* values are not actually flags, and the previous comparison was equivalent to (el->flags & LDB_FLAG_MOD_MASK) == 0 which is only true if none of the LDB_FLAG_MOD_* values are set. Correct the expression to what it was probably intended to be. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/torture/drs/rpc/dssync.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source4/torture/drs/rpc/dssync.c b/source4/torture/drs/rpc/dssync.c index f63e8a4ae7d..047bee116e9 100644 --- a/source4/torture/drs/rpc/dssync.c +++ b/source4/torture/drs/rpc/dssync.c @@ -527,7 +527,9 @@ static bool test_analyse_objects(struct torture_context *tctx, el = &new_msg->elements[idx]; a = dsdb_attribute_by_lDAPDisplayName(ldap_schema, el->name); - if (!(el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE))) { + if (LDB_FLAG_MOD_TYPE(el->flags) != LDB_FLAG_MOD_ADD && + LDB_FLAG_MOD_TYPE(el->flags) != LDB_FLAG_MOD_REPLACE) + { /* DRS only value */ is_warning = false; } else if (a->linkID & 1) { -- 2.25.1 From b436fa43f29da677513e4fb6bf5c4f9f69280be0 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 21 Jun 2022 15:22:47 +1200 Subject: [PATCH 05/68] CVE-2022-32746 s4/dsdb/acl: Fix LDB flags comparison LDB_FLAG_MOD_* values are not actually flags, and the previous comparison was equivalent to (el->flags & LDB_FLAG_MOD_MASK) == 0 which is only true if none of the LDB_FLAG_MOD_* values are set, so we would not successfully return if the element was a DELETE. Correct the expression to what it was intended to be. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- selftest/knownfail.d/acl-spn-delete | 1 - source4/dsdb/samdb/ldb_modules/acl.c | 5 +++-- 2 files changed, 3 insertions(+), 3 deletions(-) delete mode 100644 selftest/knownfail.d/acl-spn-delete diff --git a/selftest/knownfail.d/acl-spn-delete b/selftest/knownfail.d/acl-spn-delete deleted file mode 100644 index 32018413c49..00000000000 --- a/selftest/knownfail.d/acl-spn-delete +++ /dev/null @@ -1 +0,0 @@ -^samba4.ldap.acl.python.*__main__.AclSPNTests.test_delete_disallowed_spn\( diff --git a/source4/dsdb/samdb/ldb_modules/acl.c b/source4/dsdb/samdb/ldb_modules/acl.c index 21e83276bfd..8016a2d4bd0 100644 --- a/source4/dsdb/samdb/ldb_modules/acl.c +++ b/source4/dsdb/samdb/ldb_modules/acl.c @@ -734,8 +734,9 @@ static int acl_check_spn(TALLOC_CTX *mem_ctx, * If not add or replace (eg delete), * return success */ - if ((el->flags - & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE)) == 0) { + if (LDB_FLAG_MOD_TYPE(el->flags) != LDB_FLAG_MOD_ADD && + LDB_FLAG_MOD_TYPE(el->flags) != LDB_FLAG_MOD_REPLACE) + { talloc_free(tmp_ctx); return LDB_SUCCESS; } -- 2.25.1 From ef8e25cf53f218c63f6becd8724a20d4e0cba6f7 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 16 Feb 2022 12:43:52 +1300 Subject: [PATCH 06/68] CVE-2022-32746 ldb:rdn_name: Use LDB_FLAG_MOD_TYPE() for flags equality check Now unrelated flags will no longer affect the result. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- lib/ldb/modules/rdn_name.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldb/modules/rdn_name.c b/lib/ldb/modules/rdn_name.c index e69ad9315ae..25cffe07591 100644 --- a/lib/ldb/modules/rdn_name.c +++ b/lib/ldb/modules/rdn_name.c @@ -545,7 +545,7 @@ static int rdn_name_modify(struct ldb_module *module, struct ldb_request *req) if (e != NULL) { ldb_asprintf_errstring(ldb, "Modify of 'distinguishedName' on %s not permitted, must use 'rename' operation instead", ldb_dn_get_linearized(req->op.mod.message->dn)); - if (e->flags == LDB_FLAG_MOD_REPLACE) { + if (LDB_FLAG_MOD_TYPE(e->flags) == LDB_FLAG_MOD_REPLACE) { return LDB_ERR_CONSTRAINT_VIOLATION; } else { return LDB_ERR_UNWILLING_TO_PERFORM; -- 2.25.1 From f2ee4c78d95e744d83a85f472f9d2d487cc3cf3a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 14 Jun 2022 19:49:19 +1200 Subject: [PATCH 07/68] CVE-2022-32746 s4/dsdb/repl_meta_data: Use LDB_FLAG_MOD_TYPE() for flags equality check Now unrelated flags will no longer affect the result. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/repl_meta_data.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index d3baf3ae7dd..85d1359db98 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -3525,7 +3525,7 @@ static int replmd_modify(struct ldb_module *module, struct ldb_request *req) return ldb_module_operr(module); } - if (req->op.mod.message->elements[0].flags != LDB_FLAG_MOD_REPLACE) { + if (LDB_FLAG_MOD_TYPE(req->op.mod.message->elements[0].flags) != LDB_FLAG_MOD_REPLACE) { return ldb_module_operr(module); } @@ -3558,11 +3558,11 @@ static int replmd_modify(struct ldb_module *module, struct ldb_request *req) return ldb_module_operr(module); } - if (req->op.mod.message->elements[0].flags != LDB_FLAG_MOD_DELETE) { + if (LDB_FLAG_MOD_TYPE(req->op.mod.message->elements[0].flags) != LDB_FLAG_MOD_DELETE) { return ldb_module_operr(module); } - if (req->op.mod.message->elements[1].flags != LDB_FLAG_MOD_ADD) { + if (LDB_FLAG_MOD_TYPE(req->op.mod.message->elements[1].flags) != LDB_FLAG_MOD_ADD) { return ldb_module_operr(module); } @@ -3645,7 +3645,7 @@ static int replmd_modify(struct ldb_module *module, struct ldb_request *req) return ldb_module_operr(module); } - if (msg->elements[0].flags != LDB_FLAG_MOD_ADD) { + if (LDB_FLAG_MOD_TYPE(msg->elements[0].flags) != LDB_FLAG_MOD_ADD) { talloc_free(ac); return ldb_module_operr(module); } -- 2.25.1 From 738955d0e14ead23c3ca2e8c0ce1d042332de73d Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 14 Jun 2022 21:11:33 +1200 Subject: [PATCH 08/68] CVE-2022-32746 s4/dsdb/tombstone_reanimate: Use LDB_FLAG_MOD_TYPE() for flags equality check Now unrelated flags will no longer affect the result. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c b/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c index 64e05195798..5f8911c66be 100644 --- a/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c +++ b/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c @@ -104,7 +104,7 @@ static bool is_tombstone_reanimate_request(struct ldb_request *req, if (el_dn == NULL) { return false; } - if (el_dn->flags != LDB_FLAG_MOD_REPLACE) { + if (LDB_FLAG_MOD_TYPE(el_dn->flags) != LDB_FLAG_MOD_REPLACE) { return false; } if (el_dn->num_values != 1) { @@ -117,7 +117,7 @@ static bool is_tombstone_reanimate_request(struct ldb_request *req, return false; } - if (el_deleted->flags != LDB_FLAG_MOD_DELETE) { + if (LDB_FLAG_MOD_TYPE(el_deleted->flags) != LDB_FLAG_MOD_DELETE) { return false; } -- 2.25.1 From 77d87117744a0d96fa758e68dd0a4c2fc759b413 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 14 Jun 2022 21:12:39 +1200 Subject: [PATCH 09/68] CVE-2022-32746 s4/registry: Use LDB_FLAG_MOD_TYPE() for flags equality check Now unrelated flags will no longer affect the result. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- source4/lib/registry/ldb.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/lib/registry/ldb.c b/source4/lib/registry/ldb.c index e089355975b..db383a560da 100644 --- a/source4/lib/registry/ldb.c +++ b/source4/lib/registry/ldb.c @@ -859,7 +859,7 @@ static WERROR ldb_set_value(struct hive_key *parent, /* Try first a "modify" and if this doesn't work do try an "add" */ for (i = 0; i < msg->num_elements; i++) { - if (msg->elements[i].flags != LDB_FLAG_MOD_DELETE) { + if (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) != LDB_FLAG_MOD_DELETE) { msg->elements[i].flags = LDB_FLAG_MOD_REPLACE; } } -- 2.25.1 From 513574283d9985b9a74b9faecf57355fea178dc0 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Mon, 21 Feb 2022 16:10:32 +1300 Subject: [PATCH 10/68] CVE-2022-32746 ldb: Add flag to mark message element values as shared When making a shallow copy of an ldb message, mark the message elements of the copy as sharing their values with the message elements in the original message. This flag value will be heeded in the next commit. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- lib/ldb/common/ldb_msg.c | 43 +++++++++++++++++++++++++++++++----- lib/ldb/include/ldb_module.h | 6 +++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/lib/ldb/common/ldb_msg.c b/lib/ldb/common/ldb_msg.c index 57dfc5a04c2..2a9ce384bb9 100644 --- a/lib/ldb/common/ldb_msg.c +++ b/lib/ldb/common/ldb_msg.c @@ -833,11 +833,7 @@ void ldb_msg_sort_elements(struct ldb_message *msg) ldb_msg_element_compare_name); } -/* - shallow copy a message - copying only the elements array so that the caller - can safely add new elements without changing the message -*/ -struct ldb_message *ldb_msg_copy_shallow(TALLOC_CTX *mem_ctx, +static struct ldb_message *ldb_msg_copy_shallow_impl(TALLOC_CTX *mem_ctx, const struct ldb_message *msg) { struct ldb_message *msg2; @@ -863,6 +859,35 @@ failed: return NULL; } +/* + shallow copy a message - copying only the elements array so that the caller + can safely add new elements without changing the message +*/ +struct ldb_message *ldb_msg_copy_shallow(TALLOC_CTX *mem_ctx, + const struct ldb_message *msg) +{ + struct ldb_message *msg2; + unsigned int i; + + msg2 = ldb_msg_copy_shallow_impl(mem_ctx, msg); + if (msg2 == NULL) { + return NULL; + } + + for (i = 0; i < msg2->num_elements; ++i) { + /* + * Mark this message's elements as sharing their values with the + * original message, so that we don't inadvertently modify or + * free them. We don't mark the original message element as + * shared, so the original message element should not be + * modified or freed while the shallow copy lives. + */ + struct ldb_message_element *el = &msg2->elements[i]; + el->flags |= LDB_FLAG_INTERNAL_SHARED_VALUES; + } + + return msg2; +} /* copy a message, allocating new memory for all parts @@ -873,7 +898,7 @@ struct ldb_message *ldb_msg_copy(TALLOC_CTX *mem_ctx, struct ldb_message *msg2; unsigned int i, j; - msg2 = ldb_msg_copy_shallow(mem_ctx, msg); + msg2 = ldb_msg_copy_shallow_impl(mem_ctx, msg); if (msg2 == NULL) return NULL; if (msg2->dn != NULL) { @@ -894,6 +919,12 @@ struct ldb_message *ldb_msg_copy(TALLOC_CTX *mem_ctx, goto failed; } } + + /* + * Since we copied this element's values, we can mark them as + * not shared. + */ + el->flags &= ~LDB_FLAG_INTERNAL_SHARED_VALUES; } return msg2; diff --git a/lib/ldb/include/ldb_module.h b/lib/ldb/include/ldb_module.h index 8c1e5ee7936..4c7c85a17f0 100644 --- a/lib/ldb/include/ldb_module.h +++ b/lib/ldb/include/ldb_module.h @@ -96,6 +96,12 @@ struct ldb_module; */ #define LDB_FLAG_INTERNAL_FORCE_UNIQUE_INDEX 0x100 +/* + * indicates that this element's values are shared with another element (for + * example, in a shallow copy of an ldb_message) and should not be freed + */ +#define LDB_FLAG_INTERNAL_SHARED_VALUES 0x200 + /* an extended match rule that always fails to match */ #define SAMBA_LDAP_MATCH_ALWAYS_FALSE "1.3.6.1.4.1.7165.4.5.1" -- 2.25.1 From a7a59c540ba13777109b33470dbd2d2c4938eb9d Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 16 Feb 2022 12:35:13 +1300 Subject: [PATCH 11/68] CVE-2022-32746 ldb: Ensure shallow copy modifications do not affect original message Using the newly added ldb flag, we can now detect when a message has been shallow-copied so that its elements share their values with the original message elements. Then when adding values to the copied message, we now make a copy of the shared values array first. This should prevent a use-after-free that occurred in LDB modules when new values were added to a shallow copy of a message by calling talloc_realloc() on the original values array, invalidating the 'values' pointer in the original message element. The original values pointer can later be used in the database audit logging module which logs database requests, and potentially cause a crash. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- lib/ldb/common/ldb_msg.c | 52 ++++++++++++++++++++++++++++++++------ lib/ldb/include/ldb.h | 6 +++++ source4/dsdb/common/util.c | 20 +++++---------- 3 files changed, 56 insertions(+), 22 deletions(-) diff --git a/lib/ldb/common/ldb_msg.c b/lib/ldb/common/ldb_msg.c index 2a9ce384bb9..44d3b29e9a7 100644 --- a/lib/ldb/common/ldb_msg.c +++ b/lib/ldb/common/ldb_msg.c @@ -417,6 +417,47 @@ int ldb_msg_add(struct ldb_message *msg, return LDB_SUCCESS; } +/* + * add a value to a message element + */ +int ldb_msg_element_add_value(TALLOC_CTX *mem_ctx, + struct ldb_message_element *el, + const struct ldb_val *val) +{ + struct ldb_val *vals; + + if (el->flags & LDB_FLAG_INTERNAL_SHARED_VALUES) { + /* + * Another message is using this message element's values array, + * so we don't want to make any modifications to the original + * message, or potentially invalidate its own values by calling + * talloc_realloc(). Make a copy instead. + */ + el->flags &= ~LDB_FLAG_INTERNAL_SHARED_VALUES; + + vals = talloc_array(mem_ctx, struct ldb_val, + el->num_values + 1); + if (vals == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + if (el->values != NULL) { + memcpy(vals, el->values, el->num_values * sizeof(struct ldb_val)); + } + } else { + vals = talloc_realloc(mem_ctx, el->values, struct ldb_val, + el->num_values + 1); + if (vals == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + } + el->values = vals; + el->values[el->num_values] = *val; + el->num_values++; + + return LDB_SUCCESS; +} + /* add a value to a message */ @@ -426,7 +467,6 @@ int ldb_msg_add_value(struct ldb_message *msg, struct ldb_message_element **return_el) { struct ldb_message_element *el; - struct ldb_val *vals; int ret; el = ldb_msg_find_element(msg, attr_name); @@ -437,14 +477,10 @@ int ldb_msg_add_value(struct ldb_message *msg, } } - vals = talloc_realloc(msg->elements, el->values, struct ldb_val, - el->num_values+1); - if (!vals) { - return LDB_ERR_OPERATIONS_ERROR; + ret = ldb_msg_element_add_value(msg->elements, el, val); + if (ret != LDB_SUCCESS) { + return ret; } - el->values = vals; - el->values[el->num_values] = *val; - el->num_values++; if (return_el) { *return_el = el; diff --git a/lib/ldb/include/ldb.h b/lib/ldb/include/ldb.h index bc44157eaf4..129beefeaf5 100644 --- a/lib/ldb/include/ldb.h +++ b/lib/ldb/include/ldb.h @@ -1981,6 +1981,12 @@ int ldb_msg_add_empty(struct ldb_message *msg, int flags, struct ldb_message_element **return_el); +/** + add a value to a message element +*/ +int ldb_msg_element_add_value(TALLOC_CTX *mem_ctx, + struct ldb_message_element *el, + const struct ldb_val *val); /** add a element to a ldb_message */ diff --git a/source4/dsdb/common/util.c b/source4/dsdb/common/util.c index 5da75f2d28f..ce6f85eed1c 100644 --- a/source4/dsdb/common/util.c +++ b/source4/dsdb/common/util.c @@ -815,7 +815,7 @@ int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, const char *value) { struct ldb_message_element *el; - struct ldb_val val, *vals; + struct ldb_val val; char *v; unsigned int i; bool found = false; @@ -850,14 +850,10 @@ int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, } } - vals = talloc_realloc(msg->elements, el->values, struct ldb_val, - el->num_values + 1); - if (vals == NULL) { + ret = ldb_msg_element_add_value(msg->elements, el, &val); + if (ret != LDB_SUCCESS) { return ldb_oom(sam_ldb); } - el->values = vals; - el->values[el->num_values] = val; - ++(el->num_values); return LDB_SUCCESS; } @@ -871,7 +867,7 @@ int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, const char *value) { struct ldb_message_element *el; - struct ldb_val val, *vals; + struct ldb_val val; char *v; unsigned int i; bool found = false; @@ -906,14 +902,10 @@ int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, } } - vals = talloc_realloc(msg->elements, el->values, struct ldb_val, - el->num_values + 1); - if (vals == NULL) { + ret = ldb_msg_element_add_value(msg->elements, el, &val); + if (ret != LDB_SUCCESS) { return ldb_oom(sam_ldb); } - el->values = vals; - el->values[el->num_values] = val; - ++(el->num_values); return LDB_SUCCESS; } -- 2.25.1 From c0127af98b2af828c635bd5a97b732cc5d151567 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 16 Feb 2022 16:30:03 +1300 Subject: [PATCH 12/68] CVE-2022-32746 ldb: Add functions for appending to an ldb_message Currently, there are many places where we use ldb_msg_add_empty() to add an empty element to a message, and then call ldb_msg_add_value() or similar to add values to that element. However, this performs an unnecessary search of the message's elements to locate the new element. Moreover, if an element with the same attribute name already exists earlier in the message, the values will be added to that element, instead of to the intended newly added element. A similar pattern exists where we add values to a message, and then call ldb_msg_find_element() to locate that message element and sets its flags to (e.g.) LDB_FLAG_MOD_REPLACE. This also performs an unnecessary search, and may locate the wrong message element for setting the flags. To avoid these problems, add functions for appending a value to a message, so that a particular value can be added to the end of a message in a single operation. For ADD requests, it is important that no two message elements share the same attribute name, otherwise things will break. (Normally, ldb_msg_normalize() is called before processing the request to help ensure this.) Thus, we must be careful not to append an attribute to an ADD message, unless we are sure (e.g. through ldb_msg_find_element()) that an existing element for that attribute is not present. These functions will be used in the next commit. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- lib/ldb/common/ldb_msg.c | 165 ++++++++++++++++++++++++++++++++++++++- lib/ldb/include/ldb.h | 24 ++++++ 2 files changed, 185 insertions(+), 4 deletions(-) diff --git a/lib/ldb/common/ldb_msg.c b/lib/ldb/common/ldb_msg.c index 44d3b29e9a7..9cd7998e21c 100644 --- a/lib/ldb/common/ldb_msg.c +++ b/lib/ldb/common/ldb_msg.c @@ -509,12 +509,15 @@ int ldb_msg_add_steal_value(struct ldb_message *msg, /* - add a string element to a message + add a string element to a message, specifying flags */ -int ldb_msg_add_string(struct ldb_message *msg, - const char *attr_name, const char *str) +int ldb_msg_add_string_flags(struct ldb_message *msg, + const char *attr_name, const char *str, + int flags) { struct ldb_val val; + int ret; + struct ldb_message_element *el = NULL; val.data = discard_const_p(uint8_t, str); val.length = strlen(str); @@ -524,7 +527,25 @@ int ldb_msg_add_string(struct ldb_message *msg, return LDB_SUCCESS; } - return ldb_msg_add_value(msg, attr_name, &val, NULL); + ret = ldb_msg_add_value(msg, attr_name, &val, &el); + if (ret != LDB_SUCCESS) { + return ret; + } + + if (flags != 0) { + el->flags = flags; + } + + return LDB_SUCCESS; +} + +/* + add a string element to a message +*/ +int ldb_msg_add_string(struct ldb_message *msg, + const char *attr_name, const char *str) +{ + return ldb_msg_add_string_flags(msg, attr_name, str, 0); } /* @@ -586,6 +607,142 @@ int ldb_msg_add_fmt(struct ldb_message *msg, return ldb_msg_add_steal_value(msg, attr_name, &val); } +static int ldb_msg_append_value_impl(struct ldb_message *msg, + const char *attr_name, + const struct ldb_val *val, + int flags, + struct ldb_message_element **return_el) +{ + struct ldb_message_element *el = NULL; + int ret; + + ret = ldb_msg_add_empty(msg, attr_name, flags, &el); + if (ret != LDB_SUCCESS) { + return ret; + } + + ret = ldb_msg_element_add_value(msg->elements, el, val); + if (ret != LDB_SUCCESS) { + return ret; + } + + if (return_el != NULL) { + *return_el = el; + } + + return LDB_SUCCESS; +} + +/* + append a value to a message +*/ +int ldb_msg_append_value(struct ldb_message *msg, + const char *attr_name, + const struct ldb_val *val, + int flags) +{ + return ldb_msg_append_value_impl(msg, attr_name, val, flags, NULL); +} + +/* + append a value to a message, stealing it into the 'right' place +*/ +int ldb_msg_append_steal_value(struct ldb_message *msg, + const char *attr_name, + struct ldb_val *val, + int flags) +{ + int ret; + struct ldb_message_element *el = NULL; + + ret = ldb_msg_append_value_impl(msg, attr_name, val, flags, &el); + if (ret == LDB_SUCCESS) { + talloc_steal(el->values, val->data); + } + return ret; +} + +/* + append a string element to a message, stealing it into the 'right' place +*/ +int ldb_msg_append_steal_string(struct ldb_message *msg, + const char *attr_name, char *str, + int flags) +{ + struct ldb_val val; + + val.data = (uint8_t *)str; + val.length = strlen(str); + + if (val.length == 0) { + /* allow empty strings as non-existent attributes */ + return LDB_SUCCESS; + } + + return ldb_msg_append_steal_value(msg, attr_name, &val, flags); +} + +/* + append a string element to a message +*/ +int ldb_msg_append_string(struct ldb_message *msg, + const char *attr_name, const char *str, int flags) +{ + struct ldb_val val; + + val.data = discard_const_p(uint8_t, str); + val.length = strlen(str); + + if (val.length == 0) { + /* allow empty strings as non-existent attributes */ + return LDB_SUCCESS; + } + + return ldb_msg_append_value(msg, attr_name, &val, flags); +} + +/* + append a DN element to a message + WARNING: this uses the linearized string from the dn, and does not + copy the string. +*/ +int ldb_msg_append_linearized_dn(struct ldb_message *msg, const char *attr_name, + struct ldb_dn *dn, int flags) +{ + char *str = ldb_dn_alloc_linearized(msg, dn); + + if (str == NULL) { + /* we don't want to have unknown DNs added */ + return LDB_ERR_OPERATIONS_ERROR; + } + + return ldb_msg_append_steal_string(msg, attr_name, str, flags); +} + +/* + append a printf formatted element to a message +*/ +int ldb_msg_append_fmt(struct ldb_message *msg, int flags, + const char *attr_name, const char *fmt, ...) +{ + struct ldb_val val; + va_list ap; + char *str = NULL; + + va_start(ap, fmt); + str = talloc_vasprintf(msg, fmt, ap); + va_end(ap); + + if (str == NULL) { + return LDB_ERR_OPERATIONS_ERROR; + } + + val.data = (uint8_t *)str; + val.length = strlen(str); + + return ldb_msg_append_steal_value(msg, attr_name, &val, flags); +} + /* compare two ldb_message_element structures assumes case sensitive comparison diff --git a/lib/ldb/include/ldb.h b/lib/ldb/include/ldb.h index 129beefeaf5..63d8aedd672 100644 --- a/lib/ldb/include/ldb.h +++ b/lib/ldb/include/ldb.h @@ -2002,12 +2002,36 @@ int ldb_msg_add_steal_value(struct ldb_message *msg, struct ldb_val *val); int ldb_msg_add_steal_string(struct ldb_message *msg, const char *attr_name, char *str); +int ldb_msg_add_string_flags(struct ldb_message *msg, + const char *attr_name, const char *str, + int flags); int ldb_msg_add_string(struct ldb_message *msg, const char *attr_name, const char *str); int ldb_msg_add_linearized_dn(struct ldb_message *msg, const char *attr_name, struct ldb_dn *dn); int ldb_msg_add_fmt(struct ldb_message *msg, const char *attr_name, const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); +/** + append a element to a ldb_message +*/ +int ldb_msg_append_value(struct ldb_message *msg, + const char *attr_name, + const struct ldb_val *val, + int flags); +int ldb_msg_append_steal_value(struct ldb_message *msg, + const char *attr_name, + struct ldb_val *val, + int flags); +int ldb_msg_append_steal_string(struct ldb_message *msg, + const char *attr_name, char *str, + int flags); +int ldb_msg_append_string(struct ldb_message *msg, + const char *attr_name, const char *str, + int flags); +int ldb_msg_append_linearized_dn(struct ldb_message *msg, const char *attr_name, + struct ldb_dn *dn, int flags); +int ldb_msg_append_fmt(struct ldb_message *msg, int flags, + const char *attr_name, const char *fmt, ...) PRINTF_ATTRIBUTE(4,5); /** compare two message elements - return 0 on match -- 2.25.1 From 18b73e01ca4c67d27e08e505c0d29ff5c99d26ea Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Mon, 21 Feb 2022 16:27:37 +1300 Subject: [PATCH 13/68] CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message This aims to minimise usage of the error-prone pattern of searching for a just-added message element in order to make modifications to it (and potentially finding the wrong element). BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton --- lib/ldb/ldb_map/ldb_map.c | 5 +- lib/ldb/ldb_map/ldb_map_inbound.c | 9 +- lib/ldb/modules/rdn_name.c | 22 +--- source3/passdb/pdb_samba_dsdb.c | 14 +-- source4/dns_server/dnsserver_common.c | 12 +- source4/dsdb/common/util.c | 114 ++++++++++++++---- source4/dsdb/samdb/ldb_modules/descriptor.c | 10 +- source4/dsdb/samdb/ldb_modules/objectguid.c | 20 +-- .../dsdb/samdb/ldb_modules/partition_init.c | 14 +-- .../dsdb/samdb/ldb_modules/repl_meta_data.c | 24 +--- source4/dsdb/samdb/ldb_modules/samldb.c | 78 +++++------- .../samdb/ldb_modules/tombstone_reanimate.c | 12 +- source4/nbt_server/wins/winsdb.c | 13 +- source4/rpc_server/lsa/dcesrv_lsa.c | 55 +++------ source4/winbind/idmap.c | 10 +- 15 files changed, 183 insertions(+), 229 deletions(-) diff --git a/lib/ldb/ldb_map/ldb_map.c b/lib/ldb/ldb_map/ldb_map.c index b453dff80d2..c7b0c228631 100644 --- a/lib/ldb/ldb_map/ldb_map.c +++ b/lib/ldb/ldb_map/ldb_map.c @@ -946,10 +946,7 @@ struct ldb_request *map_build_fixup_req(struct map_context *ac, if ( ! dn || ! ldb_dn_validate(msg->dn)) { goto failed; } - if (ldb_msg_add_empty(msg, IS_MAPPED, LDB_FLAG_MOD_REPLACE, NULL) != 0) { - goto failed; - } - if (ldb_msg_add_string(msg, IS_MAPPED, dn) != 0) { + if (ldb_msg_append_string(msg, IS_MAPPED, dn, LDB_FLAG_MOD_REPLACE) != 0) { goto failed; } diff --git a/lib/ldb/ldb_map/ldb_map_inbound.c b/lib/ldb/ldb_map/ldb_map_inbound.c index 324295737da..50b9427c26c 100644 --- a/lib/ldb/ldb_map/ldb_map_inbound.c +++ b/lib/ldb/ldb_map/ldb_map_inbound.c @@ -569,12 +569,9 @@ static int map_modify_do_local(struct map_context *ac) /* No local record present, add it instead */ /* Add local 'IS_MAPPED' */ /* TODO: use GUIDs here instead */ - if (ldb_msg_add_empty(ac->local_msg, IS_MAPPED, - LDB_FLAG_MOD_ADD, NULL) != 0) { - return LDB_ERR_OPERATIONS_ERROR; - } - ret = ldb_msg_add_linearized_dn(ac->local_msg, IS_MAPPED, - ac->remote_req->op.mod.message->dn); + ret = ldb_msg_append_linearized_dn(ac->local_msg, IS_MAPPED, + ac->remote_req->op.mod.message->dn, + LDB_FLAG_MOD_ADD); if (ret != 0) { return LDB_ERR_OPERATIONS_ERROR; } diff --git a/lib/ldb/modules/rdn_name.c b/lib/ldb/modules/rdn_name.c index 25cffe07591..3cb62bf567b 100644 --- a/lib/ldb/modules/rdn_name.c +++ b/lib/ldb/modules/rdn_name.c @@ -308,16 +308,10 @@ static int rdn_rename_callback(struct ldb_request *req, struct ldb_reply *ares) } rdn_val = ldb_val_dup(msg, rdn_val_p); - if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) { + if (ldb_msg_append_value(msg, rdn_name, &rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { goto error; } - if (ldb_msg_add_value(msg, rdn_name, &rdn_val, NULL) != 0) { - goto error; - } - if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) { - goto error; - } - if (ldb_msg_add_value(msg, "name", &rdn_val, NULL) != 0) { + if (ldb_msg_append_value(msg, "name", &rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { goto error; } @@ -466,11 +460,7 @@ static int rdn_name_modify(struct ldb_module *module, struct ldb_request *req) if (ret != 0) { return ldb_module_oom(module); } - ret = ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_ADD, NULL); - if (ret != 0) { - return ldb_module_oom(module); - } - ret = ldb_msg_add_value(msg, rdn_name, &rdn_val, NULL); + ret = ldb_msg_append_value(msg, rdn_name, &rdn_val, LDB_FLAG_MOD_ADD); if (ret != 0) { return ldb_module_oom(module); } @@ -479,11 +469,7 @@ static int rdn_name_modify(struct ldb_module *module, struct ldb_request *req) if (ret != 0) { return ldb_module_oom(module); } - ret = ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_ADD, NULL); - if (ret != 0) { - return ldb_module_oom(module); - } - ret = ldb_msg_add_value(msg, "name", &rdn_val, NULL); + ret = ldb_msg_append_value(msg, "name", &rdn_val, LDB_FLAG_MOD_ADD); if (ret != 0) { return ldb_module_oom(module); } diff --git a/source3/passdb/pdb_samba_dsdb.c b/source3/passdb/pdb_samba_dsdb.c index 4f1d2f697f0..d9c31e57186 100644 --- a/source3/passdb/pdb_samba_dsdb.c +++ b/source3/passdb/pdb_samba_dsdb.c @@ -2776,18 +2776,10 @@ static bool pdb_samba_dsdb_set_trusteddom_pw(struct pdb_methods *m, } msg->num_elements = 0; - ret = ldb_msg_add_empty(msg, "trustAuthOutgoing", - LDB_FLAG_MOD_REPLACE, NULL); + ret = ldb_msg_append_value(msg, "trustAuthOutgoing", + &new_val, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { - DEBUG(0, ("ldb_msg_add_empty() failed\n")); - TALLOC_FREE(tmp_ctx); - ldb_transaction_cancel(state->ldb); - return false; - } - ret = ldb_msg_add_value(msg, "trustAuthOutgoing", - &new_val, NULL); - if (ret != LDB_SUCCESS) { - DEBUG(0, ("ldb_msg_add_value() failed\n")); + DEBUG(0, ("ldb_msg_append_value() failed\n")); TALLOC_FREE(tmp_ctx); ldb_transaction_cancel(state->ldb); return false; diff --git a/source4/dns_server/dnsserver_common.c b/source4/dns_server/dnsserver_common.c index 71aeee8169d..03f76d4a871 100644 --- a/source4/dns_server/dnsserver_common.c +++ b/source4/dns_server/dnsserver_common.c @@ -1124,15 +1124,9 @@ WERROR dns_common_replace(struct ldb_context *samdb, } if (was_tombstoned || become_tombstoned) { - ret = ldb_msg_add_empty(msg, "dNSTombstoned", - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - werr = DNS_ERR(SERVER_FAILURE); - goto exit; - } - - ret = ldb_msg_add_fmt(msg, "dNSTombstoned", "%s", - become_tombstoned ? "TRUE" : "FALSE"); + ret = ldb_msg_append_fmt(msg, LDB_FLAG_MOD_REPLACE, + "dNSTombstoned", "%s", + become_tombstoned ? "TRUE" : "FALSE"); if (ret != LDB_SUCCESS) { werr = DNS_ERR(SERVER_FAILURE); goto exit; diff --git a/source4/dsdb/common/util.c b/source4/dsdb/common/util.c index ce6f85eed1c..551857a526c 100644 --- a/source4/dsdb/common/util.c +++ b/source4/dsdb/common/util.c @@ -923,6 +923,16 @@ int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct l return ldb_msg_add_string(msg, attr_name, s); } +int samdb_msg_add_int_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, int v, int flags) +{ + const char *s = talloc_asprintf(mem_ctx, "%d", v); + if (s == NULL) { + return ldb_oom(sam_ldb); + } + return ldb_msg_add_string_flags(msg, attr_name, s, flags); +} + /* * Add an unsigned int element to a message * @@ -941,6 +951,12 @@ int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v); } +int samdb_msg_add_uint_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, unsigned int v, int flags) +{ + return samdb_msg_add_int_flags(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags); +} + /* add a (signed) int64_t element to a message */ @@ -972,6 +988,68 @@ int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struc return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v); } +/* + append a int element to a message +*/ +int samdb_msg_append_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, int v, int flags) +{ + const char *s = talloc_asprintf(mem_ctx, "%d", v); + if (s == NULL) { + return ldb_oom(sam_ldb); + } + return ldb_msg_append_string(msg, attr_name, s, flags); +} + +/* + * Append an unsigned int element to a message + * + * The issue here is that we have not yet first cast to int32_t explicitly, + * before we cast to an signed int to printf() into the %d or cast to a + * int64_t before we then cast to a long long to printf into a %lld. + * + * There are *no* unsigned integers in Active Directory LDAP, even the RID + * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities. + * (See the schema, and the syntax definitions in schema_syntax.c). + * + */ +int samdb_msg_append_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, unsigned int v, int flags) +{ + return samdb_msg_append_int(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags); +} + +/* + append a (signed) int64_t element to a message +*/ +int samdb_msg_append_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, int64_t v, int flags) +{ + const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v); + if (s == NULL) { + return ldb_oom(sam_ldb); + } + return ldb_msg_append_string(msg, attr_name, s, flags); +} + +/* + * Append an unsigned int64_t (uint64_t) element to a message + * + * The issue here is that we have not yet first cast to int32_t explicitly, + * before we cast to an signed int to printf() into the %d or cast to a + * int64_t before we then cast to a long long to printf into a %lld. + * + * There are *no* unsigned integers in Active Directory LDAP, even the RID + * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities. + * (See the schema, and the syntax definitions in schema_syntax.c). + * + */ +int samdb_msg_append_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, + const char *attr_name, uint64_t v, int flags) +{ + return samdb_msg_append_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v, flags); +} + /* add a samr_Password element to a message */ @@ -2813,15 +2891,8 @@ NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, tdo_msg->num_elements = 0; TALLOC_FREE(tdo_msg->elements); - ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming", - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - ldb_transaction_cancel(ldb); - TALLOC_FREE(frame); - return NT_STATUS_NO_MEMORY; - } - ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming", - &new_val, NULL); + ret = ldb_msg_append_value(tdo_msg, "trustAuthIncoming", + &new_val, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { ldb_transaction_cancel(ldb); TALLOC_FREE(frame); @@ -3186,6 +3257,7 @@ int dsdb_find_guid_by_dn(struct ldb_context *ldb, /* adds the given GUID to the given ldb_message. This value is added for the given attr_name (may be either "objectGUID" or "parentGUID"). + This function is used in processing 'add' requests. */ int dsdb_msg_add_guid(struct ldb_message *msg, struct GUID *guid, @@ -5670,7 +5742,8 @@ int dsdb_user_obj_set_defaults(struct ldb_context *ldb, } /** - * Sets 'sAMAccountType on user object based on userAccountControl + * Sets 'sAMAccountType on user object based on userAccountControl. + * This function is used in processing both 'add' and 'modify' requests. * @param ldb Current ldb_context * @param usr_obj ldb_message representing User object * @param user_account_control Value for userAccountControl flags @@ -5682,21 +5755,19 @@ int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message * { int ret; uint32_t account_type; - struct ldb_message_element *el; account_type = ds_uf2atype(user_account_control); if (account_type == 0) { ldb_set_errstring(ldb, "dsdb: Unrecognized account type!"); return LDB_ERR_UNWILLING_TO_PERFORM; } - ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj, - "sAMAccountType", - account_type); + ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj, + "sAMAccountType", + account_type, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(usr_obj, "sAMAccountType"); - el->flags = LDB_FLAG_MOD_REPLACE; if (account_type_p) { *account_type_p = account_type; @@ -5706,7 +5777,8 @@ int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message * } /** - * Determine and set primaryGroupID based on userAccountControl value + * Determine and set primaryGroupID based on userAccountControl value. + * This function is used in processing both 'add' and 'modify' requests. * @param ldb Current ldb_context * @param usr_obj ldb_message representing User object * @param user_account_control Value for userAccountControl flags @@ -5718,17 +5790,15 @@ int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_messa { int ret; uint32_t rid; - struct ldb_message_element *el; rid = ds_uf2prim_group_rid(user_account_control); - ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj, - "primaryGroupID", rid); + ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj, + "primaryGroupID", rid, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(usr_obj, "primaryGroupID"); - el->flags = LDB_FLAG_MOD_REPLACE; if (group_rid_p) { *group_rid_p = rid; diff --git a/source4/dsdb/samdb/ldb_modules/descriptor.c b/source4/dsdb/samdb/ldb_modules/descriptor.c index 8a4c2c3591f..10ed577328d 100644 --- a/source4/dsdb/samdb/ldb_modules/descriptor.c +++ b/source4/dsdb/samdb/ldb_modules/descriptor.c @@ -861,14 +861,8 @@ static int descriptor_modify(struct ldb_module *module, struct ldb_request *req) return ldb_module_done(req, NULL, NULL, LDB_SUCCESS); } - ret = ldb_msg_add_empty(msg, "nTSecurityDescriptor", - LDB_FLAG_MOD_REPLACE, - &sd_element); - if (ret != LDB_SUCCESS) { - return ldb_oom(ldb); - } - ret = ldb_msg_add_value(msg, "nTSecurityDescriptor", - sd, NULL); + ret = ldb_msg_append_value(msg, "nTSecurityDescriptor", + sd, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ldb_oom(ldb); } diff --git a/source4/dsdb/samdb/ldb_modules/objectguid.c b/source4/dsdb/samdb/ldb_modules/objectguid.c index 093d6ed74ca..cfc89184ff6 100644 --- a/source4/dsdb/samdb/ldb_modules/objectguid.c +++ b/source4/dsdb/samdb/ldb_modules/objectguid.c @@ -41,7 +41,6 @@ */ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) { - struct ldb_message_element *el; char *s; int ret; @@ -54,16 +53,13 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) return LDB_ERR_OPERATIONS_ERROR; } - ret = ldb_msg_add_string(msg, attr, s); + /* always set as replace. This works because on add ops, the flag + is ignored */ + ret = ldb_msg_append_string(msg, attr, s, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(msg, attr); - /* always set as replace. This works because on add ops, the flag - is ignored */ - el->flags = LDB_FLAG_MOD_REPLACE; - return LDB_SUCCESS; } @@ -73,23 +69,19 @@ static int add_time_element(struct ldb_message *msg, const char *attr, time_t t) static int add_uint64_element(struct ldb_context *ldb, struct ldb_message *msg, const char *attr, uint64_t v) { - struct ldb_message_element *el; int ret; if (ldb_msg_find_element(msg, attr) != NULL) { return LDB_SUCCESS; } - ret = samdb_msg_add_uint64(ldb, msg, msg, attr, v); + /* always set as replace. This works because on add ops, the flag + is ignored */ + ret = samdb_msg_append_uint64(ldb, msg, msg, attr, v, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(msg, attr); - /* always set as replace. This works because on add ops, the flag - is ignored */ - el->flags = LDB_FLAG_MOD_REPLACE; - return LDB_SUCCESS; } diff --git a/source4/dsdb/samdb/ldb_modules/partition_init.c b/source4/dsdb/samdb/ldb_modules/partition_init.c index 58c65ccedd0..484b5bffb27 100644 --- a/source4/dsdb/samdb/ldb_modules/partition_init.c +++ b/source4/dsdb/samdb/ldb_modules/partition_init.c @@ -742,10 +742,6 @@ int partition_create(struct ldb_module *module, struct ldb_request *req) } mod_msg->dn = ldb_dn_new(mod_msg, ldb, DSDB_PARTITION_DN); - ret = ldb_msg_add_empty(mod_msg, DSDB_PARTITION_ATTR, LDB_FLAG_MOD_ADD, NULL); - if (ret != LDB_SUCCESS) { - return ret; - } casefold_dn = ldb_dn_get_casefold(dn); @@ -785,18 +781,16 @@ int partition_create(struct ldb_module *module, struct ldb_request *req) } partition_record = talloc_asprintf(mod_msg, "%s:%s", casefold_dn, filename); - ret = ldb_msg_add_steal_string(mod_msg, DSDB_PARTITION_ATTR, partition_record); + ret = ldb_msg_append_steal_string(mod_msg, DSDB_PARTITION_ATTR, partition_record, + LDB_FLAG_MOD_ADD); if (ret != LDB_SUCCESS) { return ret; } if (ldb_request_get_control(req, DSDB_CONTROL_PARTIAL_REPLICA)) { /* this new partition is a partial replica */ - ret = ldb_msg_add_empty(mod_msg, "partialReplica", LDB_FLAG_MOD_ADD, NULL); - if (ret != LDB_SUCCESS) { - return ret; - } - ret = ldb_msg_add_fmt(mod_msg, "partialReplica", "%s", ldb_dn_get_linearized(dn)); + ret = ldb_msg_append_fmt(mod_msg, LDB_FLAG_MOD_ADD, + "partialReplica", "%s", ldb_dn_get_linearized(dn)); if (ret != LDB_SUCCESS) { return ret; } diff --git a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c index 85d1359db98..c35969708e3 100644 --- a/source4/dsdb/samdb/ldb_modules/repl_meta_data.c +++ b/source4/dsdb/samdb/ldb_modules/repl_meta_data.c @@ -3888,22 +3888,12 @@ static int replmd_rename_callback(struct ldb_request *req, struct ldb_reply *are ldb_operr(ldb)); } - if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) { + if (ldb_msg_append_value(msg, rdn_name, rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); } - if (ldb_msg_add_value(msg, rdn_name, rdn_val, NULL) != 0) { - talloc_free(ares); - return ldb_module_done(ac->req, NULL, NULL, - ldb_oom(ldb)); - } - if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) { - talloc_free(ares); - return ldb_module_done(ac->req, NULL, NULL, - ldb_oom(ldb)); - } - if (ldb_msg_add_value(msg, "name", rdn_val, NULL) != 0) { + if (ldb_msg_append_value(msg, "name", rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { talloc_free(ares); return ldb_module_done(ac->req, NULL, NULL, ldb_oom(ldb)); @@ -5161,16 +5151,10 @@ static int replmd_name_modify(struct replmd_replicated_request *ar, goto failed; } - if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) { - goto failed; - } - if (ldb_msg_add_value(msg, rdn_name, rdn_val, NULL) != 0) { - goto failed; - } - if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) { + if (ldb_msg_append_value(msg, rdn_name, rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { goto failed; } - if (ldb_msg_add_value(msg, "name", rdn_val, NULL) != 0) { + if (ldb_msg_append_value(msg, "name", rdn_val, LDB_FLAG_MOD_REPLACE) != 0) { goto failed; } diff --git a/source4/dsdb/samdb/ldb_modules/samldb.c b/source4/dsdb/samdb/ldb_modules/samldb.c index 24971d521aa..b89d93910fd 100644 --- a/source4/dsdb/samdb/ldb_modules/samldb.c +++ b/source4/dsdb/samdb/ldb_modules/samldb.c @@ -1103,14 +1103,11 @@ static int samldb_rodc_add(struct samldb_ctx *ac) return LDB_ERR_OTHER; found: - ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber", - LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL); - if (ret != LDB_SUCCESS) { - return ldb_operr(ldb); - } - ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, - "msDS-SecondaryKrbTgtNumber", krbtgt_number); + ldb_msg_remove_attr(ac->msg, "msDS-SecondaryKrbTgtNumber"); + ret = samdb_msg_append_uint(ldb, ac->msg, ac->msg, + "msDS-SecondaryKrbTgtNumber", krbtgt_number, + LDB_FLAG_INTERNAL_DISABLE_VALIDATION); if (ret != LDB_SUCCESS) { return ldb_operr(ldb); } @@ -1792,7 +1789,7 @@ static int samldb_objectclass_trigger(struct samldb_ctx *ac) struct ldb_context *ldb = ldb_module_get_ctx(ac->module); void *skip_allocate_sids = ldb_get_opaque(ldb, "skip_allocate_sids"); - struct ldb_message_element *el, *el2; + struct ldb_message_element *el; struct dom_sid *sid; int ret; @@ -1926,23 +1923,17 @@ static int samldb_objectclass_trigger(struct samldb_ctx *ac) /* "isCriticalSystemObject" might be set */ if (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) { - ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject", - "TRUE"); + ret = ldb_msg_add_string_flags(ac->msg, "isCriticalSystemObject", + "TRUE", LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el2 = ldb_msg_find_element(ac->msg, - "isCriticalSystemObject"); - el2->flags = LDB_FLAG_MOD_REPLACE; } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) { - ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject", - "FALSE"); + ret = ldb_msg_add_string_flags(ac->msg, "isCriticalSystemObject", + "FALSE", LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el2 = ldb_msg_find_element(ac->msg, - "isCriticalSystemObject"); - el2->flags = LDB_FLAG_MOD_REPLACE; } /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */ @@ -2018,14 +2009,13 @@ static int samldb_objectclass_trigger(struct samldb_ctx *ac) ldb_set_errstring(ldb, "samldb: Unrecognized account type!"); return LDB_ERR_UNWILLING_TO_PERFORM; } - ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, - "sAMAccountType", - account_type); + ret = samdb_msg_add_uint_flags(ldb, ac->msg, ac->msg, + "sAMAccountType", + account_type, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el2 = ldb_msg_find_element(ac->msg, "sAMAccountType"); - el2->flags = LDB_FLAG_MOD_REPLACE; } break; } @@ -2945,26 +2935,23 @@ static int samldb_user_account_control_change(struct samldb_ctx *ac) } if (old_atype != new_atype) { - ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, - "sAMAccountType", new_atype); + ret = samdb_msg_append_uint(ldb, ac->msg, ac->msg, + "sAMAccountType", new_atype, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, "sAMAccountType"); - el->flags = LDB_FLAG_MOD_REPLACE; } /* As per MS-SAMR 3.1.1.8.10 these flags have not to be set */ if ((clear_uac & UF_LOCKOUT) && (old_lockoutTime != 0)) { /* "lockoutTime" reset as per MS-SAMR 3.1.1.8.10 */ ldb_msg_remove_attr(ac->msg, "lockoutTime"); - ret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg, "lockoutTime", - (NTTIME)0); + ret = samdb_msg_append_uint64(ldb, ac->msg, ac->msg, "lockoutTime", + (NTTIME)0, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, "lockoutTime"); - el->flags = LDB_FLAG_MOD_REPLACE; } /* @@ -2975,14 +2962,12 @@ static int samldb_user_account_control_change(struct samldb_ctx *ac) * creating the attribute. */ if (old_is_critical != new_is_critical || old_atype != new_atype) { - ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject", - new_is_critical ? "TRUE": "FALSE"); + ret = ldb_msg_append_string(ac->msg, "isCriticalSystemObject", + new_is_critical ? "TRUE": "FALSE", + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, - "isCriticalSystemObject"); - el->flags = LDB_FLAG_MOD_REPLACE; } if (!ldb_msg_find_element(ac->msg, "primaryGroupID") && @@ -2995,14 +2980,12 @@ static int samldb_user_account_control_change(struct samldb_ctx *ac) } } - ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, - "primaryGroupID", new_pgrid); + ret = samdb_msg_append_uint(ldb, ac->msg, ac->msg, + "primaryGroupID", new_pgrid, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, - "primaryGroupID"); - el->flags = LDB_FLAG_MOD_REPLACE; } /* Propagate eventual "userAccountControl" attribute changes */ @@ -3205,13 +3188,12 @@ static int samldb_lockout_time(struct samldb_ctx *ac) /* lockoutTime == 0 resets badPwdCount */ ldb_msg_remove_attr(ac->msg, "badPwdCount"); - ret = samdb_msg_add_int(ldb, ac->msg, ac->msg, - "badPwdCount", 0); + ret = samdb_msg_append_int(ldb, ac->msg, ac->msg, + "badPwdCount", 0, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, "badPwdCount"); - el->flags = LDB_FLAG_MOD_REPLACE; return LDB_SUCCESS; } @@ -3309,13 +3291,11 @@ static int samldb_group_type_change(struct samldb_ctx *ac) ldb_set_errstring(ldb, "samldb: Unrecognized account type!"); return LDB_ERR_UNWILLING_TO_PERFORM; } - ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType", - account_type); + ret = samdb_msg_append_uint(ldb, ac->msg, ac->msg, "sAMAccountType", + account_type, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->msg, "sAMAccountType"); - el->flags = LDB_FLAG_MOD_REPLACE; return LDB_SUCCESS; } diff --git a/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c b/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c index 5f8911c66be..99c5955e9e7 100644 --- a/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c +++ b/source4/dsdb/samdb/ldb_modules/tombstone_reanimate.c @@ -294,14 +294,13 @@ static int tr_prepare_attributes(struct tr_context *ac) return ldb_error(ldb, LDB_ERR_UNWILLING_TO_PERFORM, "reanimate: Unrecognized account type!"); } - ret = samdb_msg_add_uint(ldb, ac->mod_msg, ac->mod_msg, - "sAMAccountType", account_type); + ret = samdb_msg_append_uint(ldb, ac->mod_msg, ac->mod_msg, + "sAMAccountType", account_type, + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "reanimate: Failed to add sAMAccountType to restored object."); } - el = ldb_msg_find_element(ac->mod_msg, "sAMAccountType"); - el->flags = LDB_FLAG_MOD_REPLACE; /* Default values set by Windows */ ret = samdb_find_or_add_attribute(ldb, ac->mod_msg, @@ -324,12 +323,11 @@ static int tr_prepare_attributes(struct tr_context *ac) return ret; } - ret = ldb_msg_add_string(ac->mod_msg, "objectCategory", value); + ret = ldb_msg_append_string(ac->mod_msg, "objectCategory", value, + LDB_FLAG_MOD_ADD); if (ret != LDB_SUCCESS) { return ret; } - el = ldb_msg_find_element(ac->mod_msg, "objectCategory"); - el->flags = LDB_FLAG_MOD_ADD; } return LDB_SUCCESS; diff --git a/source4/nbt_server/wins/winsdb.c b/source4/nbt_server/wins/winsdb.c index e4a7c2042ed..2a05e96bca4 100644 --- a/source4/nbt_server/wins/winsdb.c +++ b/source4/nbt_server/wins/winsdb.c @@ -102,13 +102,11 @@ uint64_t winsdb_set_maxVersion(struct winsdb_handle *h, uint64_t newMaxVersion) msg->dn = dn; - ret = ldb_msg_add_empty(msg, "objectClass", LDB_FLAG_MOD_REPLACE, NULL); + ret = ldb_msg_append_string(msg, "objectClass", "winsMaxVersion", + LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) goto failed; - ret = ldb_msg_add_string(msg, "objectClass", "winsMaxVersion"); - if (ret != LDB_SUCCESS) goto failed; - ret = ldb_msg_add_empty(msg, "maxVersion", LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) goto failed; - ret = ldb_msg_add_fmt(msg, "maxVersion", "%llu", (long long)newMaxVersion); + ret = ldb_msg_append_fmt(msg, LDB_FLAG_MOD_REPLACE, + "maxVersion", "%llu", (long long)newMaxVersion); if (ret != LDB_SUCCESS) goto failed; ret = ldb_modify(wins_db, msg); @@ -779,8 +777,7 @@ static struct ldb_message *winsdb_message(struct ldb_context *ldb, ret |= ldb_msg_add_winsdb_addr(msg, rec, "address", rec->addresses[i]); } if (rec->registered_by) { - ret |= ldb_msg_add_empty(msg, "registeredBy", 0, NULL); - ret |= ldb_msg_add_string(msg, "registeredBy", rec->registered_by); + ret |= ldb_msg_append_string(msg, "registeredBy", rec->registered_by, 0); } if (ret != LDB_SUCCESS) goto failed; return msg; diff --git a/source4/rpc_server/lsa/dcesrv_lsa.c b/source4/rpc_server/lsa/dcesrv_lsa.c index 4101d6ddd34..22d1a6a8252 100644 --- a/source4/rpc_server/lsa/dcesrv_lsa.c +++ b/source4/rpc_server/lsa/dcesrv_lsa.c @@ -1778,12 +1778,7 @@ static NTSTATUS update_uint32_t_value(TALLOC_CTX *mem_ctx, goto done; } - ret = ldb_msg_add_empty(dest, attribute, flags, NULL); - if (ret != LDB_SUCCESS) { - return NT_STATUS_NO_MEMORY; - } - - ret = samdb_msg_add_uint(sam_ldb, dest, dest, attribute, value); + ret = samdb_msg_append_uint(sam_ldb, dest, dest, attribute, value, flags); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } @@ -1874,13 +1869,7 @@ static NTSTATUS update_trust_user(TALLOC_CTX *mem_ctx, continue; } - ret = ldb_msg_add_empty(msg, attribute, - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - return NT_STATUS_NO_MEMORY; - } - - ret = ldb_msg_add_value(msg, attribute, &v, NULL); + ret = ldb_msg_append_value(msg, attribute, &v, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } @@ -2166,28 +2155,30 @@ static NTSTATUS setInfoTrustedDomain_base(struct dcesrv_call_state *dce_call, } if (add_incoming || del_incoming) { - ret = ldb_msg_add_empty(msg, "trustAuthIncoming", - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - return NT_STATUS_NO_MEMORY; - } if (add_incoming) { - ret = ldb_msg_add_value(msg, "trustAuthIncoming", - &trustAuthIncoming, NULL); + ret = ldb_msg_append_value(msg, "trustAuthIncoming", + &trustAuthIncoming, LDB_FLAG_MOD_REPLACE); + if (ret != LDB_SUCCESS) { + return NT_STATUS_NO_MEMORY; + } + } else { + ret = ldb_msg_add_empty(msg, "trustAuthIncoming", + LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } } } if (add_outgoing || del_outgoing) { - ret = ldb_msg_add_empty(msg, "trustAuthOutgoing", - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - return NT_STATUS_NO_MEMORY; - } if (add_outgoing) { - ret = ldb_msg_add_value(msg, "trustAuthOutgoing", - &trustAuthOutgoing, NULL); + ret = ldb_msg_append_value(msg, "trustAuthOutgoing", + &trustAuthOutgoing, LDB_FLAG_MOD_REPLACE); + if (ret != LDB_SUCCESS) { + return NT_STATUS_NO_MEMORY; + } + } else { + ret = ldb_msg_add_empty(msg, "trustAuthOutgoing", + LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { return NT_STATUS_NO_MEMORY; } @@ -4635,14 +4626,8 @@ static NTSTATUS dcesrv_lsa_lsaRSetForestTrustInformation(struct dcesrv_call_stat goto done; } - ret = ldb_msg_add_empty(msg, "msDS-TrustForestTrustInfo", - LDB_FLAG_MOD_REPLACE, NULL); - if (ret != LDB_SUCCESS) { - status = NT_STATUS_NO_MEMORY; - goto done; - } - ret = ldb_msg_add_value(msg, "msDS-TrustForestTrustInfo", - &ft_blob, NULL); + ret = ldb_msg_append_value(msg, "msDS-TrustForestTrustInfo", + &ft_blob, LDB_FLAG_MOD_REPLACE); if (ret != LDB_SUCCESS) { status = NT_STATUS_NO_MEMORY; goto done; diff --git a/source4/winbind/idmap.c b/source4/winbind/idmap.c index c4039be473a..c6375f8357a 100644 --- a/source4/winbind/idmap.c +++ b/source4/winbind/idmap.c @@ -672,14 +672,8 @@ static NTSTATUS idmap_sid_to_xid(struct idmap_context *idmap_ctx, vals[1].data = (uint8_t *)hwm_string; vals[1].length = strlen(hwm_string); } else { - ret = ldb_msg_add_empty(hwm_msg, "xidNumber", LDB_FLAG_MOD_ADD, - NULL); - if (ret != LDB_SUCCESS) { - status = NT_STATUS_NONE_MAPPED; - goto failed; - } - - ret = ldb_msg_add_string(hwm_msg, "xidNumber", hwm_string); + ret = ldb_msg_append_string(hwm_msg, "xidNumber", hwm_string, + LDB_FLAG_MOD_ADD); if (ret != LDB_SUCCESS) { status = NT_STATUS_NONE_MAPPED; -- 2.25.1 From 90ef792d904bc14c462a0232b985185a2159cf94 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Tue, 14 Jun 2022 15:43:26 +1200 Subject: [PATCH 14/68] CVE-2022-32746 ldb: Release LDB 2.5.2 * CVE-2022-32746 Use-after-free occurring in database audit logging module (bug 15009) BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Andrew Bartlett --- lib/ldb/ABI/ldb-2.5.2.sigs | 291 ++++++++++++++++++++++++++++++ lib/ldb/ABI/pyldb-util-2.5.2.sigs | 3 + lib/ldb/wscript | 2 +- 3 files changed, 295 insertions(+), 1 deletion(-) create mode 100644 lib/ldb/ABI/ldb-2.5.2.sigs create mode 100644 lib/ldb/ABI/pyldb-util-2.5.2.sigs diff --git a/lib/ldb/ABI/ldb-2.5.2.sigs b/lib/ldb/ABI/ldb-2.5.2.sigs new file mode 100644 index 00000000000..40388d9e330 --- /dev/null +++ b/lib/ldb/ABI/ldb-2.5.2.sigs @@ -0,0 +1,291 @@ +ldb_add: int (struct ldb_context *, const struct ldb_message *) +ldb_any_comparison: int (struct ldb_context *, void *, ldb_attr_handler_t, const struct ldb_val *, const struct ldb_val *) +ldb_asprintf_errstring: void (struct ldb_context *, const char *, ...) +ldb_attr_casefold: char *(TALLOC_CTX *, const char *) +ldb_attr_dn: int (const char *) +ldb_attr_in_list: int (const char * const *, const char *) +ldb_attr_list_copy: const char **(TALLOC_CTX *, const char * const *) +ldb_attr_list_copy_add: const char **(TALLOC_CTX *, const char * const *, const char *) +ldb_base64_decode: int (char *) +ldb_base64_encode: char *(TALLOC_CTX *, const char *, int) +ldb_binary_decode: struct ldb_val (TALLOC_CTX *, const char *) +ldb_binary_encode: char *(TALLOC_CTX *, struct ldb_val) +ldb_binary_encode_string: char *(TALLOC_CTX *, const char *) +ldb_build_add_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, const struct ldb_message *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_del_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, struct ldb_dn *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_extended_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, const char *, void *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_mod_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, const struct ldb_message *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_rename_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, struct ldb_dn *, struct ldb_dn *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_search_req: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, struct ldb_dn *, enum ldb_scope, const char *, const char * const *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_build_search_req_ex: int (struct ldb_request **, struct ldb_context *, TALLOC_CTX *, struct ldb_dn *, enum ldb_scope, struct ldb_parse_tree *, const char * const *, struct ldb_control **, void *, ldb_request_callback_t, struct ldb_request *) +ldb_casefold: char *(struct ldb_context *, TALLOC_CTX *, const char *, size_t) +ldb_casefold_default: char *(void *, TALLOC_CTX *, const char *, size_t) +ldb_check_critical_controls: int (struct ldb_control **) +ldb_comparison_binary: int (struct ldb_context *, void *, const struct ldb_val *, const struct ldb_val *) +ldb_comparison_fold: int (struct ldb_context *, void *, const struct ldb_val *, const struct ldb_val *) +ldb_connect: int (struct ldb_context *, const char *, unsigned int, const char **) +ldb_control_to_string: char *(TALLOC_CTX *, const struct ldb_control *) +ldb_controls_except_specified: struct ldb_control **(struct ldb_control **, TALLOC_CTX *, struct ldb_control *) +ldb_debug: void (struct ldb_context *, enum ldb_debug_level, const char *, ...) +ldb_debug_add: void (struct ldb_context *, const char *, ...) +ldb_debug_end: void (struct ldb_context *, enum ldb_debug_level) +ldb_debug_set: void (struct ldb_context *, enum ldb_debug_level, const char *, ...) +ldb_delete: int (struct ldb_context *, struct ldb_dn *) +ldb_dn_add_base: bool (struct ldb_dn *, struct ldb_dn *) +ldb_dn_add_base_fmt: bool (struct ldb_dn *, const char *, ...) +ldb_dn_add_child: bool (struct ldb_dn *, struct ldb_dn *) +ldb_dn_add_child_fmt: bool (struct ldb_dn *, const char *, ...) +ldb_dn_add_child_val: bool (struct ldb_dn *, const char *, struct ldb_val) +ldb_dn_alloc_casefold: char *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_alloc_linearized: char *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_canonical_ex_string: char *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_canonical_string: char *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_check_local: bool (struct ldb_module *, struct ldb_dn *) +ldb_dn_check_special: bool (struct ldb_dn *, const char *) +ldb_dn_compare: int (struct ldb_dn *, struct ldb_dn *) +ldb_dn_compare_base: int (struct ldb_dn *, struct ldb_dn *) +ldb_dn_copy: struct ldb_dn *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_escape_value: char *(TALLOC_CTX *, struct ldb_val) +ldb_dn_extended_add_syntax: int (struct ldb_context *, unsigned int, const struct ldb_dn_extended_syntax *) +ldb_dn_extended_filter: void (struct ldb_dn *, const char * const *) +ldb_dn_extended_syntax_by_name: const struct ldb_dn_extended_syntax *(struct ldb_context *, const char *) +ldb_dn_from_ldb_val: struct ldb_dn *(TALLOC_CTX *, struct ldb_context *, const struct ldb_val *) +ldb_dn_get_casefold: const char *(struct ldb_dn *) +ldb_dn_get_comp_num: int (struct ldb_dn *) +ldb_dn_get_component_name: const char *(struct ldb_dn *, unsigned int) +ldb_dn_get_component_val: const struct ldb_val *(struct ldb_dn *, unsigned int) +ldb_dn_get_extended_comp_num: int (struct ldb_dn *) +ldb_dn_get_extended_component: const struct ldb_val *(struct ldb_dn *, const char *) +ldb_dn_get_extended_linearized: char *(TALLOC_CTX *, struct ldb_dn *, int) +ldb_dn_get_ldb_context: struct ldb_context *(struct ldb_dn *) +ldb_dn_get_linearized: const char *(struct ldb_dn *) +ldb_dn_get_parent: struct ldb_dn *(TALLOC_CTX *, struct ldb_dn *) +ldb_dn_get_rdn_name: const char *(struct ldb_dn *) +ldb_dn_get_rdn_val: const struct ldb_val *(struct ldb_dn *) +ldb_dn_has_extended: bool (struct ldb_dn *) +ldb_dn_is_null: bool (struct ldb_dn *) +ldb_dn_is_special: bool (struct ldb_dn *) +ldb_dn_is_valid: bool (struct ldb_dn *) +ldb_dn_map_local: struct ldb_dn *(struct ldb_module *, void *, struct ldb_dn *) +ldb_dn_map_rebase_remote: struct ldb_dn *(struct ldb_module *, void *, struct ldb_dn *) +ldb_dn_map_remote: struct ldb_dn *(struct ldb_module *, void *, struct ldb_dn *) +ldb_dn_minimise: bool (struct ldb_dn *) +ldb_dn_new: struct ldb_dn *(TALLOC_CTX *, struct ldb_context *, const char *) +ldb_dn_new_fmt: struct ldb_dn *(TALLOC_CTX *, struct ldb_context *, const char *, ...) +ldb_dn_remove_base_components: bool (struct ldb_dn *, unsigned int) +ldb_dn_remove_child_components: bool (struct ldb_dn *, unsigned int) +ldb_dn_remove_extended_components: void (struct ldb_dn *) +ldb_dn_replace_components: bool (struct ldb_dn *, struct ldb_dn *) +ldb_dn_set_component: int (struct ldb_dn *, int, const char *, const struct ldb_val) +ldb_dn_set_extended_component: int (struct ldb_dn *, const char *, const struct ldb_val *) +ldb_dn_update_components: int (struct ldb_dn *, const struct ldb_dn *) +ldb_dn_validate: bool (struct ldb_dn *) +ldb_dump_results: void (struct ldb_context *, struct ldb_result *, FILE *) +ldb_error_at: int (struct ldb_context *, int, const char *, const char *, int) +ldb_errstring: const char *(struct ldb_context *) +ldb_extended: int (struct ldb_context *, const char *, void *, struct ldb_result **) +ldb_extended_default_callback: int (struct ldb_request *, struct ldb_reply *) +ldb_filter_attrs: int (struct ldb_context *, const struct ldb_message *, const char * const *, struct ldb_message *) +ldb_filter_from_tree: char *(TALLOC_CTX *, const struct ldb_parse_tree *) +ldb_get_config_basedn: struct ldb_dn *(struct ldb_context *) +ldb_get_create_perms: unsigned int (struct ldb_context *) +ldb_get_default_basedn: struct ldb_dn *(struct ldb_context *) +ldb_get_event_context: struct tevent_context *(struct ldb_context *) +ldb_get_flags: unsigned int (struct ldb_context *) +ldb_get_opaque: void *(struct ldb_context *, const char *) +ldb_get_root_basedn: struct ldb_dn *(struct ldb_context *) +ldb_get_schema_basedn: struct ldb_dn *(struct ldb_context *) +ldb_global_init: int (void) +ldb_handle_get_event_context: struct tevent_context *(struct ldb_handle *) +ldb_handle_new: struct ldb_handle *(TALLOC_CTX *, struct ldb_context *) +ldb_handle_use_global_event_context: void (struct ldb_handle *) +ldb_handler_copy: int (struct ldb_context *, void *, const struct ldb_val *, struct ldb_val *) +ldb_handler_fold: int (struct ldb_context *, void *, const struct ldb_val *, struct ldb_val *) +ldb_init: struct ldb_context *(TALLOC_CTX *, struct tevent_context *) +ldb_ldif_message_redacted_string: char *(struct ldb_context *, TALLOC_CTX *, enum ldb_changetype, const struct ldb_message *) +ldb_ldif_message_string: char *(struct ldb_context *, TALLOC_CTX *, enum ldb_changetype, const struct ldb_message *) +ldb_ldif_parse_modrdn: int (struct ldb_context *, const struct ldb_ldif *, TALLOC_CTX *, struct ldb_dn **, struct ldb_dn **, bool *, struct ldb_dn **, struct ldb_dn **) +ldb_ldif_read: struct ldb_ldif *(struct ldb_context *, int (*)(void *), void *) +ldb_ldif_read_file: struct ldb_ldif *(struct ldb_context *, FILE *) +ldb_ldif_read_file_state: struct ldb_ldif *(struct ldb_context *, struct ldif_read_file_state *) +ldb_ldif_read_free: void (struct ldb_context *, struct ldb_ldif *) +ldb_ldif_read_string: struct ldb_ldif *(struct ldb_context *, const char **) +ldb_ldif_write: int (struct ldb_context *, int (*)(void *, const char *, ...), void *, const struct ldb_ldif *) +ldb_ldif_write_file: int (struct ldb_context *, FILE *, const struct ldb_ldif *) +ldb_ldif_write_redacted_trace_string: char *(struct ldb_context *, TALLOC_CTX *, const struct ldb_ldif *) +ldb_ldif_write_string: char *(struct ldb_context *, TALLOC_CTX *, const struct ldb_ldif *) +ldb_load_modules: int (struct ldb_context *, const char **) +ldb_map_add: int (struct ldb_module *, struct ldb_request *) +ldb_map_delete: int (struct ldb_module *, struct ldb_request *) +ldb_map_init: int (struct ldb_module *, const struct ldb_map_attribute *, const struct ldb_map_objectclass *, const char * const *, const char *, const char *) +ldb_map_modify: int (struct ldb_module *, struct ldb_request *) +ldb_map_rename: int (struct ldb_module *, struct ldb_request *) +ldb_map_search: int (struct ldb_module *, struct ldb_request *) +ldb_match_message: int (struct ldb_context *, const struct ldb_message *, const struct ldb_parse_tree *, enum ldb_scope, bool *) +ldb_match_msg: int (struct ldb_context *, const struct ldb_message *, const struct ldb_parse_tree *, struct ldb_dn *, enum ldb_scope) +ldb_match_msg_error: int (struct ldb_context *, const struct ldb_message *, const struct ldb_parse_tree *, struct ldb_dn *, enum ldb_scope, bool *) +ldb_match_msg_objectclass: int (const struct ldb_message *, const char *) +ldb_mod_register_control: int (struct ldb_module *, const char *) +ldb_modify: int (struct ldb_context *, const struct ldb_message *) +ldb_modify_default_callback: int (struct ldb_request *, struct ldb_reply *) +ldb_module_call_chain: char *(struct ldb_request *, TALLOC_CTX *) +ldb_module_connect_backend: int (struct ldb_context *, const char *, const char **, struct ldb_module **) +ldb_module_done: int (struct ldb_request *, struct ldb_control **, struct ldb_extended *, int) +ldb_module_flags: uint32_t (struct ldb_context *) +ldb_module_get_ctx: struct ldb_context *(struct ldb_module *) +ldb_module_get_name: const char *(struct ldb_module *) +ldb_module_get_ops: const struct ldb_module_ops *(struct ldb_module *) +ldb_module_get_private: void *(struct ldb_module *) +ldb_module_init_chain: int (struct ldb_context *, struct ldb_module *) +ldb_module_load_list: int (struct ldb_context *, const char **, struct ldb_module *, struct ldb_module **) +ldb_module_new: struct ldb_module *(TALLOC_CTX *, struct ldb_context *, const char *, const struct ldb_module_ops *) +ldb_module_next: struct ldb_module *(struct ldb_module *) +ldb_module_popt_options: struct poptOption **(struct ldb_context *) +ldb_module_send_entry: int (struct ldb_request *, struct ldb_message *, struct ldb_control **) +ldb_module_send_referral: int (struct ldb_request *, char *) +ldb_module_set_next: void (struct ldb_module *, struct ldb_module *) +ldb_module_set_private: void (struct ldb_module *, void *) +ldb_modules_hook: int (struct ldb_context *, enum ldb_module_hook_type) +ldb_modules_list_from_string: const char **(struct ldb_context *, TALLOC_CTX *, const char *) +ldb_modules_load: int (const char *, const char *) +ldb_msg_add: int (struct ldb_message *, const struct ldb_message_element *, int) +ldb_msg_add_empty: int (struct ldb_message *, const char *, int, struct ldb_message_element **) +ldb_msg_add_fmt: int (struct ldb_message *, const char *, const char *, ...) +ldb_msg_add_linearized_dn: int (struct ldb_message *, const char *, struct ldb_dn *) +ldb_msg_add_steal_string: int (struct ldb_message *, const char *, char *) +ldb_msg_add_steal_value: int (struct ldb_message *, const char *, struct ldb_val *) +ldb_msg_add_string: int (struct ldb_message *, const char *, const char *) +ldb_msg_add_string_flags: int (struct ldb_message *, const char *, const char *, int) +ldb_msg_add_value: int (struct ldb_message *, const char *, const struct ldb_val *, struct ldb_message_element **) +ldb_msg_append_fmt: int (struct ldb_message *, int, const char *, const char *, ...) +ldb_msg_append_linearized_dn: int (struct ldb_message *, const char *, struct ldb_dn *, int) +ldb_msg_append_steal_string: int (struct ldb_message *, const char *, char *, int) +ldb_msg_append_steal_value: int (struct ldb_message *, const char *, struct ldb_val *, int) +ldb_msg_append_string: int (struct ldb_message *, const char *, const char *, int) +ldb_msg_append_value: int (struct ldb_message *, const char *, const struct ldb_val *, int) +ldb_msg_canonicalize: struct ldb_message *(struct ldb_context *, const struct ldb_message *) +ldb_msg_check_string_attribute: int (const struct ldb_message *, const char *, const char *) +ldb_msg_copy: struct ldb_message *(TALLOC_CTX *, const struct ldb_message *) +ldb_msg_copy_attr: int (struct ldb_message *, const char *, const char *) +ldb_msg_copy_shallow: struct ldb_message *(TALLOC_CTX *, const struct ldb_message *) +ldb_msg_diff: struct ldb_message *(struct ldb_context *, struct ldb_message *, struct ldb_message *) +ldb_msg_difference: int (struct ldb_context *, TALLOC_CTX *, struct ldb_message *, struct ldb_message *, struct ldb_message **) +ldb_msg_element_add_value: int (TALLOC_CTX *, struct ldb_message_element *, const struct ldb_val *) +ldb_msg_element_compare: int (struct ldb_message_element *, struct ldb_message_element *) +ldb_msg_element_compare_name: int (struct ldb_message_element *, struct ldb_message_element *) +ldb_msg_element_equal_ordered: bool (const struct ldb_message_element *, const struct ldb_message_element *) +ldb_msg_find_attr_as_bool: int (const struct ldb_message *, const char *, int) +ldb_msg_find_attr_as_dn: struct ldb_dn *(struct ldb_context *, TALLOC_CTX *, const struct ldb_message *, const char *) +ldb_msg_find_attr_as_double: double (const struct ldb_message *, const char *, double) +ldb_msg_find_attr_as_int: int (const struct ldb_message *, const char *, int) +ldb_msg_find_attr_as_int64: int64_t (const struct ldb_message *, const char *, int64_t) +ldb_msg_find_attr_as_string: const char *(const struct ldb_message *, const char *, const char *) +ldb_msg_find_attr_as_uint: unsigned int (const struct ldb_message *, const char *, unsigned int) +ldb_msg_find_attr_as_uint64: uint64_t (const struct ldb_message *, const char *, uint64_t) +ldb_msg_find_common_values: int (struct ldb_context *, TALLOC_CTX *, struct ldb_message_element *, struct ldb_message_element *, uint32_t) +ldb_msg_find_duplicate_val: int (struct ldb_context *, TALLOC_CTX *, const struct ldb_message_element *, struct ldb_val **, uint32_t) +ldb_msg_find_element: struct ldb_message_element *(const struct ldb_message *, const char *) +ldb_msg_find_ldb_val: const struct ldb_val *(const struct ldb_message *, const char *) +ldb_msg_find_val: struct ldb_val *(const struct ldb_message_element *, struct ldb_val *) +ldb_msg_new: struct ldb_message *(TALLOC_CTX *) +ldb_msg_normalize: int (struct ldb_context *, TALLOC_CTX *, const struct ldb_message *, struct ldb_message **) +ldb_msg_remove_attr: void (struct ldb_message *, const char *) +ldb_msg_remove_element: void (struct ldb_message *, struct ldb_message_element *) +ldb_msg_rename_attr: int (struct ldb_message *, const char *, const char *) +ldb_msg_sanity_check: int (struct ldb_context *, const struct ldb_message *) +ldb_msg_sort_elements: void (struct ldb_message *) +ldb_next_del_trans: int (struct ldb_module *) +ldb_next_end_trans: int (struct ldb_module *) +ldb_next_init: int (struct ldb_module *) +ldb_next_prepare_commit: int (struct ldb_module *) +ldb_next_read_lock: int (struct ldb_module *) +ldb_next_read_unlock: int (struct ldb_module *) +ldb_next_remote_request: int (struct ldb_module *, struct ldb_request *) +ldb_next_request: int (struct ldb_module *, struct ldb_request *) +ldb_next_start_trans: int (struct ldb_module *) +ldb_op_default_callback: int (struct ldb_request *, struct ldb_reply *) +ldb_options_copy: const char **(TALLOC_CTX *, const char **) +ldb_options_find: const char *(struct ldb_context *, const char **, const char *) +ldb_options_get: const char **(struct ldb_context *) +ldb_pack_data: int (struct ldb_context *, const struct ldb_message *, struct ldb_val *, uint32_t) +ldb_parse_control_from_string: struct ldb_control *(struct ldb_context *, TALLOC_CTX *, const char *) +ldb_parse_control_strings: struct ldb_control **(struct ldb_context *, TALLOC_CTX *, const char **) +ldb_parse_tree: struct ldb_parse_tree *(TALLOC_CTX *, const char *) +ldb_parse_tree_attr_replace: void (struct ldb_parse_tree *, const char *, const char *) +ldb_parse_tree_copy_shallow: struct ldb_parse_tree *(TALLOC_CTX *, const struct ldb_parse_tree *) +ldb_parse_tree_walk: int (struct ldb_parse_tree *, int (*)(struct ldb_parse_tree *, void *), void *) +ldb_qsort: void (void * const, size_t, size_t, void *, ldb_qsort_cmp_fn_t) +ldb_register_backend: int (const char *, ldb_connect_fn, bool) +ldb_register_extended_match_rule: int (struct ldb_context *, const struct ldb_extended_match_rule *) +ldb_register_hook: int (ldb_hook_fn) +ldb_register_module: int (const struct ldb_module_ops *) +ldb_rename: int (struct ldb_context *, struct ldb_dn *, struct ldb_dn *) +ldb_reply_add_control: int (struct ldb_reply *, const char *, bool, void *) +ldb_reply_get_control: struct ldb_control *(struct ldb_reply *, const char *) +ldb_req_get_custom_flags: uint32_t (struct ldb_request *) +ldb_req_is_untrusted: bool (struct ldb_request *) +ldb_req_location: const char *(struct ldb_request *) +ldb_req_mark_trusted: void (struct ldb_request *) +ldb_req_mark_untrusted: void (struct ldb_request *) +ldb_req_set_custom_flags: void (struct ldb_request *, uint32_t) +ldb_req_set_location: void (struct ldb_request *, const char *) +ldb_request: int (struct ldb_context *, struct ldb_request *) +ldb_request_add_control: int (struct ldb_request *, const char *, bool, void *) +ldb_request_done: int (struct ldb_request *, int) +ldb_request_get_control: struct ldb_control *(struct ldb_request *, const char *) +ldb_request_get_status: int (struct ldb_request *) +ldb_request_replace_control: int (struct ldb_request *, const char *, bool, void *) +ldb_request_set_state: void (struct ldb_request *, int) +ldb_reset_err_string: void (struct ldb_context *) +ldb_save_controls: int (struct ldb_control *, struct ldb_request *, struct ldb_control ***) +ldb_schema_attribute_add: int (struct ldb_context *, const char *, unsigned int, const char *) +ldb_schema_attribute_add_with_syntax: int (struct ldb_context *, const char *, unsigned int, const struct ldb_schema_syntax *) +ldb_schema_attribute_by_name: const struct ldb_schema_attribute *(struct ldb_context *, const char *) +ldb_schema_attribute_fill_with_syntax: int (struct ldb_context *, TALLOC_CTX *, const char *, unsigned int, const struct ldb_schema_syntax *, struct ldb_schema_attribute *) +ldb_schema_attribute_remove: void (struct ldb_context *, const char *) +ldb_schema_attribute_remove_flagged: void (struct ldb_context *, unsigned int) +ldb_schema_attribute_set_override_handler: void (struct ldb_context *, ldb_attribute_handler_override_fn_t, void *) +ldb_schema_set_override_GUID_index: void (struct ldb_context *, const char *, const char *) +ldb_schema_set_override_indexlist: void (struct ldb_context *, bool) +ldb_search: int (struct ldb_context *, TALLOC_CTX *, struct ldb_result **, struct ldb_dn *, enum ldb_scope, const char * const *, const char *, ...) +ldb_search_default_callback: int (struct ldb_request *, struct ldb_reply *) +ldb_sequence_number: int (struct ldb_context *, enum ldb_sequence_type, uint64_t *) +ldb_set_create_perms: void (struct ldb_context *, unsigned int) +ldb_set_debug: int (struct ldb_context *, void (*)(void *, enum ldb_debug_level, const char *, va_list), void *) +ldb_set_debug_stderr: int (struct ldb_context *) +ldb_set_default_dns: void (struct ldb_context *) +ldb_set_errstring: void (struct ldb_context *, const char *) +ldb_set_event_context: void (struct ldb_context *, struct tevent_context *) +ldb_set_flags: void (struct ldb_context *, unsigned int) +ldb_set_modules_dir: void (struct ldb_context *, const char *) +ldb_set_opaque: int (struct ldb_context *, const char *, void *) +ldb_set_require_private_event_context: void (struct ldb_context *) +ldb_set_timeout: int (struct ldb_context *, struct ldb_request *, int) +ldb_set_timeout_from_prev_req: int (struct ldb_context *, struct ldb_request *, struct ldb_request *) +ldb_set_utf8_default: void (struct ldb_context *) +ldb_set_utf8_fns: void (struct ldb_context *, void *, char *(*)(void *, void *, const char *, size_t)) +ldb_setup_wellknown_attributes: int (struct ldb_context *) +ldb_should_b64_encode: int (struct ldb_context *, const struct ldb_val *) +ldb_standard_syntax_by_name: const struct ldb_schema_syntax *(struct ldb_context *, const char *) +ldb_strerror: const char *(int) +ldb_string_to_time: time_t (const char *) +ldb_string_utc_to_time: time_t (const char *) +ldb_timestring: char *(TALLOC_CTX *, time_t) +ldb_timestring_utc: char *(TALLOC_CTX *, time_t) +ldb_transaction_cancel: int (struct ldb_context *) +ldb_transaction_cancel_noerr: int (struct ldb_context *) +ldb_transaction_commit: int (struct ldb_context *) +ldb_transaction_prepare_commit: int (struct ldb_context *) +ldb_transaction_start: int (struct ldb_context *) +ldb_unpack_data: int (struct ldb_context *, const struct ldb_val *, struct ldb_message *) +ldb_unpack_data_flags: int (struct ldb_context *, const struct ldb_val *, struct ldb_message *, unsigned int) +ldb_unpack_get_format: int (const struct ldb_val *, uint32_t *) +ldb_val_dup: struct ldb_val (TALLOC_CTX *, const struct ldb_val *) +ldb_val_equal_exact: int (const struct ldb_val *, const struct ldb_val *) +ldb_val_map_local: struct ldb_val (struct ldb_module *, void *, const struct ldb_map_attribute *, const struct ldb_val *) +ldb_val_map_remote: struct ldb_val (struct ldb_module *, void *, const struct ldb_map_attribute *, const struct ldb_val *) +ldb_val_string_cmp: int (const struct ldb_val *, const char *) +ldb_val_to_time: int (const struct ldb_val *, time_t *) +ldb_valid_attr_name: int (const char *) +ldb_vdebug: void (struct ldb_context *, enum ldb_debug_level, const char *, va_list) +ldb_wait: int (struct ldb_handle *, enum ldb_wait_type) diff --git a/lib/ldb/ABI/pyldb-util-2.5.2.sigs b/lib/ldb/ABI/pyldb-util-2.5.2.sigs new file mode 100644 index 00000000000..164a806b2ff --- /dev/null +++ b/lib/ldb/ABI/pyldb-util-2.5.2.sigs @@ -0,0 +1,3 @@ +pyldb_Dn_FromDn: PyObject *(struct ldb_dn *) +pyldb_Object_AsDn: bool (TALLOC_CTX *, PyObject *, struct ldb_context *, struct ldb_dn **) +pyldb_check_type: bool (PyObject *, const char *) diff --git a/lib/ldb/wscript b/lib/ldb/wscript index f483dd54748..16e5682148a 100644 --- a/lib/ldb/wscript +++ b/lib/ldb/wscript @@ -2,7 +2,7 @@ APPNAME = 'ldb' # For Samba 4.16.x -VERSION = '2.5.1' +VERSION = '2.5.2' import sys, os -- 2.25.1 From 1d7690b000f115ea39fb498d63de46ab6705f927 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 16 Feb 2022 17:03:10 +1300 Subject: [PATCH 15/68] CVE-2022-32745 s4/dsdb/samldb: Check for empty values array This avoids potentially trying to access the first element of an empty array. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15008 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/samldb.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/samldb.c b/source4/dsdb/samdb/ldb_modules/samldb.c index b89d93910fd..3ecbd00e68e 100644 --- a/source4/dsdb/samdb/ldb_modules/samldb.c +++ b/source4/dsdb/samdb/ldb_modules/samldb.c @@ -751,7 +751,7 @@ static int samldb_schema_add_handle_linkid(struct samldb_ctx *ac) return ret; } - if (el == NULL) { + if (el == NULL || el->num_values == 0) { return LDB_SUCCESS; } @@ -919,7 +919,7 @@ static int samldb_schema_add_handle_mapiid(struct samldb_ctx *ac) return ret; } - if (el == NULL) { + if (el == NULL || el->num_values == 0) { return LDB_SUCCESS; } -- 2.25.1 From f2ded77168dbc54b1d0c8ead08701c48af3f3a74 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 17 Feb 2022 11:11:53 +1300 Subject: [PATCH 16/68] CVE-2022-32745 s4/dsdb/util: Use correct value for loop count limit Currently, we can crash the server by sending a large number of values of a specific attribute (such as sAMAccountName) spread across a few message elements. If val_count is larger than the total number of elements, we get an access beyond the elements array. Similarly, we can include unrelated message elements prior to the message elements of the attribute in question, so that not all of the attribute's values are copied into the returned elements values array. This can cause the server to access uninitialised data, likely resulting in a crash or unexpected behaviour. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15008 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/dsdb/samdb/ldb_modules/util.c b/source4/dsdb/samdb/ldb_modules/util.c index 405febf0b3d..14947746837 100644 --- a/source4/dsdb/samdb/ldb_modules/util.c +++ b/source4/dsdb/samdb/ldb_modules/util.c @@ -1546,7 +1546,7 @@ int dsdb_get_expected_new_values(TALLOC_CTX *mem_ctx, v = _el->values; - for (i = 0; i < val_count; i++) { + for (i = 0; i < msg->num_elements; i++) { if (ldb_attr_cmp(msg->elements[i].name, attr_name) == 0) { if ((operation == LDB_MODIFY) && (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) -- 2.25.1 From 701aef133fd6efb03f8b32dfd5a4d93acf8b9fce Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 17 Feb 2022 11:13:38 +1300 Subject: [PATCH 17/68] CVE-2022-32745 s4/dsdb/util: Don't call memcpy() with a NULL pointer Doing so is undefined behaviour. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15008 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/util.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/source4/dsdb/samdb/ldb_modules/util.c b/source4/dsdb/samdb/ldb_modules/util.c index 14947746837..35ae110b5ef 100644 --- a/source4/dsdb/samdb/ldb_modules/util.c +++ b/source4/dsdb/samdb/ldb_modules/util.c @@ -1548,15 +1548,19 @@ int dsdb_get_expected_new_values(TALLOC_CTX *mem_ctx, for (i = 0; i < msg->num_elements; i++) { if (ldb_attr_cmp(msg->elements[i].name, attr_name) == 0) { + const struct ldb_message_element *tmp_el = &msg->elements[i]; if ((operation == LDB_MODIFY) && - (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) + (LDB_FLAG_MOD_TYPE(tmp_el->flags) == LDB_FLAG_MOD_DELETE)) { continue; } + if (tmp_el->values == NULL || tmp_el->num_values == 0) { + continue; + } memcpy(v, - msg->elements[i].values, - msg->elements[i].num_values); - v += msg->elements[i].num_values; + tmp_el->values, + tmp_el->num_values); + v += tmp_el->num_values; } } -- 2.25.1 From e0d25e172c48c1cd083466dc304257698aadf4af Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 3 Jun 2022 16:16:31 +1200 Subject: [PATCH 18/68] CVE-2022-32745 s4/dsdb/util: Correctly copy values into message element To use memcpy(), we need to specify the number of bytes to copy, rather than the number of ldb_val structures. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15008 Signed-off-by: Joseph Sutton --- source4/dsdb/samdb/ldb_modules/util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/dsdb/samdb/ldb_modules/util.c b/source4/dsdb/samdb/ldb_modules/util.c index 35ae110b5ef..e7fe8f855df 100644 --- a/source4/dsdb/samdb/ldb_modules/util.c +++ b/source4/dsdb/samdb/ldb_modules/util.c @@ -1559,7 +1559,7 @@ int dsdb_get_expected_new_values(TALLOC_CTX *mem_ctx, } memcpy(v, tmp_el->values, - tmp_el->num_values); + tmp_el->num_values * sizeof(*v)); v += tmp_el->num_values; } } -- 2.25.1 From 23f770ed910b837b20f5252283f849cebff66745 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 21 Dec 2021 12:17:11 +0100 Subject: [PATCH 19/68] s4:kdc: Also cannoicalize krbtgt principals when enforcing canonicalization Signed-off-by: Andreas Schneider Reviewed-by: Stefan Metzmacher (cherry picked from commit f1ec950aeb47283a504018bafa21f54c3282e70c) --- source4/kdc/db-glue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 3e1f7a6b4dc..4094ad42727 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -985,7 +985,7 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) { p->is_krbtgt = true; - if (flags & (SDB_F_CANON)) { + if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) { /* * When requested to do so, ensure that the * both realm values in the principal are set -- 2.25.1 From 191adf2cf3880a56a8289b5da7dd1bdf41f24ce6 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 8 Feb 2022 12:15:36 +1300 Subject: [PATCH 20/68] tests/krb5: Add helper function to modify ticket flags Signed-off-by: Joseph Sutton Reviewed-by: Stefan Metzmacher (cherry picked from commit ded5115f73dff5b8b2f3212988e03f9dbe0c2aa3) --- python/samba/tests/krb5/kdc_base_test.py | 14 ++++++++++++++ python/samba/tests/krb5/kdc_tgs_tests.py | 18 ++---------------- python/samba/tests/krb5/s4u_tests.py | 17 +++-------------- 3 files changed, 19 insertions(+), 30 deletions(-) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index 9c79411d487..a1c40d9ffde 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -1630,6 +1630,20 @@ class KDCBaseTest(RawKerberosTest): enc_part, asn1Spec=krb5_asn1.EncTicketPart()) return enc_ticket_part + def modify_ticket_flag(self, enc_part, flag, value): + self.assertIsInstance(value, bool) + + flag = krb5_asn1.TicketFlags(flag) + pos = len(tuple(flag)) - 1 + + flags = enc_part['flags'] + self.assertLessEqual(pos, len(flags)) + + new_flags = flags[:pos] + str(int(value)) + flags[pos + 1:] + enc_part['flags'] = new_flags + + return enc_part + def get_objectSid(self, samdb, dn): ''' Get the objectSID for a DN Note: performs an Ldb query. diff --git a/python/samba/tests/krb5/kdc_tgs_tests.py b/python/samba/tests/krb5/kdc_tgs_tests.py index df95523144f..21044f6d094 100755 --- a/python/samba/tests/krb5/kdc_tgs_tests.py +++ b/python/samba/tests/krb5/kdc_tgs_tests.py @@ -2419,14 +2419,7 @@ class KdcTgsTests(KDCBaseTest): def _modify_renewable(self, enc_part): # Set the renewable flag. - renewable_flag = krb5_asn1.TicketFlags('renewable') - pos = len(tuple(renewable_flag)) - 1 - - flags = enc_part['flags'] - self.assertLessEqual(pos, len(flags)) - - new_flags = flags[:pos] + '1' + flags[pos + 1:] - enc_part['flags'] = new_flags + enc_part = self.modify_ticket_flag(enc_part, 'renewable', value=True) # Set the renew-till time to be in the future. renew_till = self.get_KerberosTime(offset=100 * 60 * 60) @@ -2436,14 +2429,7 @@ class KdcTgsTests(KDCBaseTest): def _modify_invalid(self, enc_part): # Set the invalid flag. - invalid_flag = krb5_asn1.TicketFlags('invalid') - pos = len(tuple(invalid_flag)) - 1 - - flags = enc_part['flags'] - self.assertLessEqual(pos, len(flags)) - - new_flags = flags[:pos] + '1' + flags[pos + 1:] - enc_part['flags'] = new_flags + enc_part = self.modify_ticket_flag(enc_part, 'invalid', value=True) # Set the ticket start time to be in the past. past_time = self.get_KerberosTime(offset=-100 * 60 * 60) diff --git a/python/samba/tests/krb5/s4u_tests.py b/python/samba/tests/krb5/s4u_tests.py index 6ec9af11423..49dd89cd764 100755 --- a/python/samba/tests/krb5/s4u_tests.py +++ b/python/samba/tests/krb5/s4u_tests.py @@ -1336,20 +1336,9 @@ class S4UKerberosTests(KDCBaseTest): modify_pac_fn=modify_pac_fn) def set_ticket_forwardable(self, ticket, flag, update_pac_checksums=True): - flag = '1' if flag else '0' - - def modify_fn(enc_part): - # Reset the forwardable flag - forwardable_pos = (len(tuple(krb5_asn1.TicketFlags('forwardable'))) - - 1) - - flags = enc_part['flags'] - self.assertLessEqual(forwardable_pos, len(flags)) - enc_part['flags'] = (flags[:forwardable_pos] + - flag + - flags[forwardable_pos+1:]) - - return enc_part + modify_fn = functools.partial(self.modify_ticket_flag, + flag='forwardable', + value=flag) if update_pac_checksums: checksum_keys = self.get_krbtgt_checksum_key() -- 2.25.1 From 06444c0d4ea7e4f26bcf7ea285061e97c294444e Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 4 Mar 2022 16:57:27 +1300 Subject: [PATCH 21/68] selftest: Simplify krb5 test environments It's not necessary to repeat the required environment variables for every test. Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider (cherry picked from commit e729606631b5bfaf7c4ad8c1e70697adf8274777) --- source4/selftest/tests.py | 239 ++++++-------------------------------- 1 file changed, 38 insertions(+), 201 deletions(-) diff --git a/source4/selftest/tests.py b/source4/selftest/tests.py index 53978966f7c..e6847d384e8 100755 --- a/source4/selftest/tests.py +++ b/source4/selftest/tests.py @@ -961,126 +961,63 @@ for env in ['fileserver_smb1', 'nt4_member', 'clusteredmember', 'ktest', 'nt4_dc planoldpythontestsuite(env, "samba.tests.imports") have_fast_support = 1 +claims_support = 0 +compound_id_support = 0 tkt_sig_support = int('SAMBA4_USES_HEIMDAL' in config_hash) expect_pac = int('SAMBA4_USES_HEIMDAL' in config_hash) extra_pac_buffers = int('SAMBA4_USES_HEIMDAL' in config_hash) check_cname = int('SAMBA4_USES_HEIMDAL' in config_hash) check_padata = int('SAMBA4_USES_HEIMDAL' in config_hash) +krb5_environ = { + 'SERVICE_USERNAME': '$SERVER', + 'ADMIN_USERNAME': '$DC_USERNAME', + 'ADMIN_PASSWORD': '$DC_PASSWORD', + 'FOR_USER': '$DC_USERNAME', + 'STRICT_CHECKING':'0', + 'FAST_SUPPORT': have_fast_support, + 'CLAIMS_SUPPORT': claims_support, + 'COMPOUND_ID_SUPPORT': compound_id_support, + 'TKT_SIG_SUPPORT': tkt_sig_support, + 'EXPECT_PAC': expect_pac, + 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, + 'CHECK_CNAME': check_cname, + 'CHECK_PADATA': check_padata, +} planoldpythontestsuite("none", "samba.tests.krb5.kcrypto") planoldpythontestsuite("ad_dc_default", "samba.tests.krb5.simple_tests", - environ={'SERVICE_USERNAME':'$SERVER', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata}) + environ=krb5_environ) planoldpythontestsuite("ad_dc_default:local", "samba.tests.krb5.s4u_tests", - environ={'ADMIN_USERNAME':'$USERNAME', - 'ADMIN_PASSWORD':'$PASSWORD', - 'FOR_USER':'$USERNAME', - 'STRICT_CHECKING':'0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata}) + environ=krb5_environ) planoldpythontestsuite("rodc:local", "samba.tests.krb5.rodc_tests", - environ={'ADMIN_USERNAME':'$USERNAME', - 'ADMIN_PASSWORD':'$PASSWORD', - 'STRICT_CHECKING':'0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata}) + environ=krb5_environ) planoldpythontestsuite("ad_dc_default", "samba.tests.dsdb_dns") planoldpythontestsuite("fl2008r2dc:local", "samba.tests.krb5.xrealm_tests", - environ={'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata}) + environ=krb5_environ) planoldpythontestsuite("ad_dc_default", "samba.tests.krb5.test_ccache", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planoldpythontestsuite("ad_dc_default", "samba.tests.krb5.test_ldap", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) for env in ['ad_dc_default', 'ad_member']: planoldpythontestsuite(env, "samba.tests.krb5.test_rpc", - environ={ - 'ADMIN_USERNAME': '$DC_USERNAME', - 'ADMIN_PASSWORD': '$DC_PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planoldpythontestsuite("ad_dc_smb1", "samba.tests.krb5.test_smb", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planoldpythontestsuite("ad_member_idmap_nss:local", "samba.tests.krb5.test_min_domain_uid", - environ={ - 'ADMIN_USERNAME': '$DC_USERNAME', - 'ADMIN_PASSWORD': '$DC_PASSWORD', - 'STRICT_CHECKING': '0' - }) + environ=krb5_environ) planoldpythontestsuite("ad_member_idmap_nss:local", "samba.tests.krb5.test_idmap_nss", environ={ - 'ADMIN_USERNAME': '$DC_USERNAME', - 'ADMIN_PASSWORD': '$DC_PASSWORD', + **krb5_environ, 'MAPPED_USERNAME': 'bob', 'MAPPED_PASSWORD': 'Secret007', 'UNMAPPED_USERNAME': 'jane', 'UNMAPPED_PASSWORD': 'Secret007', 'INVALID_USERNAME': 'joe', 'INVALID_PASSWORD': 'Secret007', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata }) for env in ["ad_dc", smbv1_disabled_testenv]: @@ -1673,29 +1610,12 @@ for env in ["fl2008r2dc", "fl2003dc"]: fast_support = 0 planoldpythontestsuite(env, "samba.tests.krb5.as_req_tests", environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', + **krb5_environ, 'FAST_SUPPORT': fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata }) planoldpythontestsuite('fl2008r2dc', 'samba.tests.krb5.salt_tests', - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) for env in ["rodc", "promoted_dc", "fl2000dc", "fl2008r2dc"]: if env == "rodc": @@ -1712,118 +1632,35 @@ for env in ["rodc", "promoted_dc", "fl2000dc", "fl2008r2dc"]: "samba4.krb5.kdc with machine account") planpythontestsuite("ad_dc", "samba.tests.krb5.as_canonicalization_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite("ad_dc", "samba.tests.krb5.compatability_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite("ad_dc", "samba.tests.krb5.kdc_tests", - environ={'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata}) + environ=krb5_environ) planpythontestsuite( "ad_dc", "samba.tests.krb5.kdc_tgs_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite( "ad_dc", "samba.tests.krb5.fast_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite( "ad_dc", "samba.tests.krb5.ms_kile_client_principal_lookup_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite( "ad_dc", "samba.tests.krb5.spn_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planpythontestsuite( "ad_dc", "samba.tests.krb5.alias_tests", - environ={ - 'ADMIN_USERNAME': '$USERNAME', - 'ADMIN_PASSWORD': '$PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname, - 'CHECK_PADATA': check_padata - }) + environ=krb5_environ) planoldpythontestsuite( 'ad_dc', 'samba.tests.krb5.pac_align_tests', - environ={ - 'ADMIN_USERNAME': '$DC_USERNAME', - 'ADMIN_PASSWORD': '$DC_PASSWORD', - 'STRICT_CHECKING': '0', - 'FAST_SUPPORT': have_fast_support, - 'TKT_SIG_SUPPORT': tkt_sig_support, - 'EXPECT_PAC': expect_pac, - 'EXPECT_EXTRA_PAC_BUFFERS': extra_pac_buffers, - 'CHECK_CNAME': check_cname - }) + environ=krb5_environ) for env in [ 'vampire_dc', -- 2.25.1 From 628534b4dcf080a1ab9349d43973c97de818d69c Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 15 Jun 2022 19:37:39 +1200 Subject: [PATCH 22/68] CVE-2022-2031 s4:kdc: Add MIT support for ATTRIBUTES_INFO and REQUESTER_SID PAC buffers So that we do not confuse TGTs and kpasswd tickets, it is critical to check that the REQUESTER_SID buffer exists in TGTs, and to ensure that it is not propagated to service tickets. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton --- selftest/knownfail_mit_kdc | 5 --- source4/kdc/mit_samba.c | 79 +++++++++++++++++++++++++++++++++++++- 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index ab4976ea690..a0e7579e140 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -461,7 +461,6 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_authdata_no_pac ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_no_pac ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rename -^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_req_no_requester_sid ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_allowed_denied ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_denied ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_no_krbtgt_link @@ -520,7 +519,6 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_pac_attrs_rodc_renew_true ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_pac_attrs_true ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_pac_attrs_false -^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_pac_attrs_none ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_pac_attrs_true ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_req_from_rodc_no_pac_attrs # @@ -536,11 +534,8 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # PAC requester SID tests # ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_req_from_rodc_no_requester_sid -^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid\( -^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_missing_renew ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_missing_rodc_renew ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_missing_rodc_validate -^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_missing_validate ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_rodc_renew ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_requester_sid_rodc_validate ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_logon_info_only_sid_mismatch_existing diff --git a/source4/kdc/mit_samba.c b/source4/kdc/mit_samba.c index 27b15828468..cb72b5de294 100644 --- a/source4/kdc/mit_samba.c +++ b/source4/kdc/mit_samba.c @@ -530,6 +530,7 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, DATA_BLOB *pac_blob = NULL; DATA_BLOB *upn_blob = NULL; DATA_BLOB *deleg_blob = NULL; + DATA_BLOB *requester_sid_blob = NULL; struct samba_kdc_entry *client_skdc_entry = NULL; struct samba_kdc_entry *krbtgt_skdc_entry = NULL; struct samba_kdc_entry *server_skdc_entry = NULL; @@ -545,8 +546,12 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, ssize_t upn_dns_info_idx = -1; ssize_t srv_checksum_idx = -1; ssize_t kdc_checksum_idx = -1; + ssize_t tkt_checksum_idx = -1; + ssize_t attrs_info_idx = -1; + ssize_t requester_sid_idx = -1; krb5_pac new_pac = NULL; bool ok; + bool is_krbtgt; /* Create a memory context early so code can use talloc_stackframe() */ tmp_ctx = talloc_named(ctx, 0, "mit_samba_reget_pac context"); @@ -554,6 +559,8 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, return ENOMEM; } + is_krbtgt = ks_is_tgs_principal(ctx, server->princ); + if (client != NULL) { client_skdc_entry = talloc_get_type_abort(client->e_data, @@ -613,7 +620,7 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, &upn_blob, NULL, 0, - NULL, + &requester_sid_blob, NULL); if (!NT_STATUS_IS_OK(nt_status)) { code = EINVAL; @@ -772,6 +779,45 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, } kdc_checksum_idx = i; break; + case PAC_TYPE_TICKET_CHECKSUM: + if (tkt_checksum_idx != -1) { + DBG_WARNING("ticket checksum type[%u] twice " + "[%zd] and [%zu]: \n", + types[i], + tkt_checksum_idx, + i); + SAFE_FREE(types); + code = EINVAL; + goto done; + } + tkt_checksum_idx = i; + break; + case PAC_TYPE_ATTRIBUTES_INFO: + if (attrs_info_idx != -1) { + DBG_WARNING("attributes info type[%u] twice " + "[%zd] and [%zu]: \n", + types[i], + attrs_info_idx, + i); + SAFE_FREE(types); + code = EINVAL; + goto done; + } + attrs_info_idx = i; + break; + case PAC_TYPE_REQUESTER_SID: + if (requester_sid_idx != -1) { + DBG_WARNING("requester sid type[%u] twice" + "[%zd] and [%zu]: \n", + types[i], + requester_sid_idx, + i); + SAFE_FREE(types); + code = EINVAL; + goto done; + } + requester_sid_idx = i; + break; default: continue; } @@ -801,6 +847,13 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, code = EINVAL; goto done; } + if (!(flags & KRB5_KDB_FLAG_CONSTRAINED_DELEGATION) && + requester_sid_idx == -1) { + DEBUG(1, ("PAC_TYPE_REQUESTER_SID missing\n")); + SAFE_FREE(types); + code = KRB5KDC_ERR_TGT_REVOKED; + goto done; + } /* Build an updated PAC */ code = krb5_pac_init(context, &new_pac); @@ -866,6 +919,10 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, } break; case PAC_TYPE_SRV_CHECKSUM: + if (requester_sid_idx == -1 && requester_sid_blob != NULL) { + /* inject REQUESTER_SID */ + forced_next_type = PAC_TYPE_REQUESTER_SID; + } /* * This is generated in the main KDC code */ @@ -875,6 +932,26 @@ krb5_error_code mit_samba_reget_pac(struct mit_samba_context *ctx, * This is generated in the main KDC code */ continue; + case PAC_TYPE_ATTRIBUTES_INFO: + if (!is_untrusted && is_krbtgt) { + /* just copy... */ + break; + } + + continue; + case PAC_TYPE_REQUESTER_SID: + if (!is_krbtgt) { + continue; + } + + /* + * Replace in the RODC case, otherwise + * requester_sid_blob is NULL and we just copy. + */ + if (requester_sid_blob != NULL) { + type_blob = *requester_sid_blob; + } + break; default: /* just copy... */ break; -- 2.25.1 From 52b953bfc1891a83099b0829b00f6710f17454fb Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 16 Jun 2022 15:32:49 +1200 Subject: [PATCH 23/68] CVE-2022-2031 third_party/heimdal: Check generate_pac() return code If the function fails, we should not issue a ticket missing the PAC. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton --- third_party/heimdal/kdc/kerberos5.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/third_party/heimdal/kdc/kerberos5.c b/third_party/heimdal/kdc/kerberos5.c index e95bdad0a64..0a7934310cc 100644 --- a/third_party/heimdal/kdc/kerberos5.c +++ b/third_party/heimdal/kdc/kerberos5.c @@ -2668,7 +2668,9 @@ _kdc_as_rep(astgs_request_t r) /* Add the PAC */ if (!r->et.flags.anonymous) { - generate_pac(r, skey, krbtgt_key, is_tgs); + ret = generate_pac(r, skey, krbtgt_key, is_tgs); + if (ret) + goto out; } if (r->client->flags.synthetic) { -- 2.25.1 From f706dcd5ddc13f7e615a7d503420693d1ee45eb2 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 27 May 2022 19:17:02 +1200 Subject: [PATCH 24/68] CVE-2022-2031 s4:kpasswd: Account for missing target principal This field is supposed to be optional. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/kdc/kpasswd-service-mit.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/source4/kdc/kpasswd-service-mit.c b/source4/kdc/kpasswd-service-mit.c index 2117c1c1696..b53c1a4618a 100644 --- a/source4/kdc/kpasswd-service-mit.c +++ b/source4/kdc/kpasswd-service-mit.c @@ -143,16 +143,18 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, return KRB5_KPASSWD_HARDERROR; } - target_realm = smb_krb5_principal_get_realm( - mem_ctx, context, target_principal); - code = krb5_unparse_name_flags(context, - target_principal, - KRB5_PRINCIPAL_UNPARSE_NO_REALM, - &target_name); - if (code != 0) { - DBG_WARNING("Failed to parse principal\n"); - *error_string = "String conversion failed"; - return KRB5_KPASSWD_HARDERROR; + if (target_principal != NULL) { + target_realm = smb_krb5_principal_get_realm( + mem_ctx, context, target_principal); + code = krb5_unparse_name_flags(context, + target_principal, + KRB5_PRINCIPAL_UNPARSE_NO_REALM, + &target_name); + if (code != 0) { + DBG_WARNING("Failed to parse principal\n"); + *error_string = "String conversion failed"; + return KRB5_KPASSWD_HARDERROR; + } } if ((target_name != NULL && target_realm == NULL) || -- 2.25.1 From 3bd5df466cb567be8c673eb20cfe903f1950a700 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Mon, 30 May 2022 19:17:41 +1200 Subject: [PATCH 25/68] CVE-2022-2031 s4:kpasswd: Add MIT fallback for decoding setpw structure The target principal and realm fields of the setpw structure are supposed to be optional, but in MIT Kerberos they are mandatory. For better compatibility and ease of testing, fall back to parsing the simpler (containing only the new password) structure if the MIT function fails to decode it. Although the target principal and realm fields should be optional, one is not supposed to specified without the other, so we don't have to deal with the case where only one is specified. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/kdc/kpasswd-service-mit.c | 94 ++++++++++++++++++++++++++----- 1 file changed, 79 insertions(+), 15 deletions(-) diff --git a/source4/kdc/kpasswd-service-mit.c b/source4/kdc/kpasswd-service-mit.c index b53c1a4618a..9c4d2801669 100644 --- a/source4/kdc/kpasswd-service-mit.c +++ b/source4/kdc/kpasswd-service-mit.c @@ -28,6 +28,7 @@ #include "kdc/kpasswd_glue.h" #include "kdc/kpasswd-service.h" #include "kdc/kpasswd-helper.h" +#include "../lib/util/asn1.h" #define RFC3244_VERSION 0xff80 @@ -35,6 +36,52 @@ krb5_error_code decode_krb5_setpw_req(const krb5_data *code, krb5_data **password_out, krb5_principal *target_out); +/* + * A fallback for when MIT refuses to parse a setpw structure without the + * (optional) target principal and realm + */ +static bool decode_krb5_setpw_req_simple(TALLOC_CTX *mem_ctx, + const DATA_BLOB *decoded_data, + DATA_BLOB *clear_data) +{ + struct asn1_data *asn1 = NULL; + bool ret; + + asn1 = asn1_init(mem_ctx, 3); + if (asn1 == NULL) { + return false; + } + + ret = asn1_load(asn1, *decoded_data); + if (!ret) { + goto out; + } + + ret = asn1_start_tag(asn1, ASN1_SEQUENCE(0)); + if (!ret) { + goto out; + } + ret = asn1_start_tag(asn1, ASN1_CONTEXT(0)); + if (!ret) { + goto out; + } + ret = asn1_read_OctetString(asn1, mem_ctx, clear_data); + if (!ret) { + goto out; + } + + ret = asn1_end_tag(asn1); + if (!ret) { + goto out; + } + ret = asn1_end_tag(asn1); + +out: + asn1_free(asn1); + + return ret; +} + static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, struct auth_session_info *session_info, @@ -93,9 +140,10 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, const char **error_string) { krb5_context context = kdc->smb_krb5_context->krb5_context; + DATA_BLOB clear_data; krb5_data k_dec_data; - krb5_data *k_clear_data; - krb5_principal target_principal; + krb5_data *k_clear_data = NULL; + krb5_principal target_principal = NULL; krb5_error_code code; DATA_BLOB password; char *target_realm = NULL; @@ -114,29 +162,45 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, code = decode_krb5_setpw_req(&k_dec_data, &k_clear_data, &target_principal); - if (code != 0) { - DBG_WARNING("decode_krb5_setpw_req failed: %s\n", - error_message(code)); - ok = kpasswd_make_error_reply(mem_ctx, - KRB5_KPASSWD_MALFORMED, - "Failed to decode packet", - kpasswd_reply); + if (code == 0) { + clear_data.data = (uint8_t *)k_clear_data->data; + clear_data.length = k_clear_data->length; + } else { + target_principal = NULL; + + /* + * The MIT decode failed, so fall back to trying the simple + * case, without target_principal. + */ + ok = decode_krb5_setpw_req_simple(mem_ctx, + decoded_data, + &clear_data); if (!ok) { - *error_string = "Failed to create reply"; - return KRB5_KPASSWD_HARDERROR; + DBG_WARNING("decode_krb5_setpw_req failed: %s\n", + error_message(code)); + ok = kpasswd_make_error_reply(mem_ctx, + KRB5_KPASSWD_MALFORMED, + "Failed to decode packet", + kpasswd_reply); + if (!ok) { + *error_string = "Failed to create reply"; + return KRB5_KPASSWD_HARDERROR; + } + return 0; } - return 0; } ok = convert_string_talloc_handle(mem_ctx, lpcfg_iconv_handle(kdc->task->lp_ctx), CH_UTF8, CH_UTF16, - (const char *)k_clear_data->data, - k_clear_data->length, + clear_data.data, + clear_data.length, (void **)&password.data, &password.length); - krb5_free_data(context, k_clear_data); + if (k_clear_data != NULL) { + krb5_free_data(context, k_clear_data); + } if (!ok) { DBG_WARNING("String conversion failed\n"); *error_string = "String conversion failed"; -- 2.25.1 From af53dbec65ca65030d4712acdabbb7505b811611 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 26 May 2022 16:34:01 +1200 Subject: [PATCH 26/68] CVE-2022-32744 tests/krb5: Correctly handle specifying account kvno The environment variable is a string, but we expect an integer. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/raw_testcase.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 584a3fe5567..edebba6ae91 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -755,7 +755,7 @@ class RawKerberosTest(TestCaseInTempDir): fallback_default=False, allow_missing=kvno_allow_missing) if kvno is not None: - c.set_kvno(kvno) + c.set_kvno(int(kvno)) aes256_key = self.env_get_var('AES256_KEY_HEX', prefix, fallback_default=False, allow_missing=aes256_allow_missing) -- 2.25.1 From 3034c1933c22c76d112693117ac6bf0f95a49f70 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 26 May 2022 20:52:04 +1200 Subject: [PATCH 27/68] CVE-2022-2031 tests/krb5: Split out _make_tgs_request() This allows us to make use of it in other tests. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/kdc_base_test.py | 85 ++++++++++++++++++++++++ python/samba/tests/krb5/kdc_tgs_tests.py | 84 ----------------------- 2 files changed, 85 insertions(+), 84 deletions(-) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index a1c40d9ffde..097b7813711 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -67,6 +67,7 @@ from samba.tests.krb5.rfc4120_constants import ( AES256_CTS_HMAC_SHA1_96, ARCFOUR_HMAC_MD5, KDC_ERR_PREAUTH_REQUIRED, + KDC_ERR_TGT_REVOKED, KRB_AS_REP, KRB_TGS_REP, KRB_ERROR, @@ -1566,6 +1567,90 @@ class KDCBaseTest(RawKerberosTest): return ticket_creds + def _make_tgs_request(self, client_creds, service_creds, tgt, + client_account=None, + client_name_type=NT_PRINCIPAL, + kdc_options=None, + pac_request=None, expect_pac=True, + expect_error=False, + expected_cname=None, + expected_account_name=None, + expected_upn_name=None, + expected_sid=None): + if client_account is None: + client_account = client_creds.get_username() + cname = self.PrincipalName_create(name_type=client_name_type, + names=client_account.split('/')) + + service_account = service_creds.get_username() + sname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=[service_account]) + + realm = service_creds.get_realm() + + expected_crealm = realm + if expected_cname is None: + expected_cname = cname + expected_srealm = realm + expected_sname = sname + + expected_supported_etypes = service_creds.tgs_supported_enctypes + + etypes = (AES256_CTS_HMAC_SHA1_96, ARCFOUR_HMAC_MD5) + + if kdc_options is None: + kdc_options = 'canonicalize' + kdc_options = str(krb5_asn1.KDCOptions(kdc_options)) + + target_decryption_key = self.TicketDecryptionKey_from_creds( + service_creds) + + authenticator_subkey = self.RandomKey(kcrypto.Enctype.AES256) + + if expect_error: + expected_error_mode = KDC_ERR_TGT_REVOKED + check_error_fn = self.generic_check_kdc_error + check_rep_fn = None + else: + expected_error_mode = 0 + check_error_fn = None + check_rep_fn = self.generic_check_kdc_rep + + kdc_exchange_dict = self.tgs_exchange_dict( + expected_crealm=expected_crealm, + expected_cname=expected_cname, + expected_srealm=expected_srealm, + expected_sname=expected_sname, + expected_account_name=expected_account_name, + expected_upn_name=expected_upn_name, + expected_sid=expected_sid, + expected_supported_etypes=expected_supported_etypes, + ticket_decryption_key=target_decryption_key, + check_error_fn=check_error_fn, + check_rep_fn=check_rep_fn, + check_kdc_private_fn=self.generic_check_kdc_private, + expected_error_mode=expected_error_mode, + tgt=tgt, + authenticator_subkey=authenticator_subkey, + kdc_options=kdc_options, + pac_request=pac_request, + expect_pac=expect_pac, + expect_edata=False) + + rep = self._generic_kdc_exchange(kdc_exchange_dict, + cname=cname, + realm=realm, + sname=sname, + etypes=etypes) + if expect_error: + self.check_error_rep(rep, expected_error_mode) + + return None + else: + self.check_reply(rep, KRB_TGS_REP) + + return kdc_exchange_dict['rep_ticket_creds'] + # Named tuple to contain values of interest when the PAC is decoded. PacData = namedtuple( "PacData", diff --git a/python/samba/tests/krb5/kdc_tgs_tests.py b/python/samba/tests/krb5/kdc_tgs_tests.py index 21044f6d094..07370dff3df 100755 --- a/python/samba/tests/krb5/kdc_tgs_tests.py +++ b/python/samba/tests/krb5/kdc_tgs_tests.py @@ -231,90 +231,6 @@ class KdcTgsTests(KDCBaseTest): pac_data.account_sid, "rep = {%s},%s" % (rep, pac_data)) - def _make_tgs_request(self, client_creds, service_creds, tgt, - client_account=None, - client_name_type=NT_PRINCIPAL, - kdc_options=None, - pac_request=None, expect_pac=True, - expect_error=False, - expected_cname=None, - expected_account_name=None, - expected_upn_name=None, - expected_sid=None): - if client_account is None: - client_account = client_creds.get_username() - cname = self.PrincipalName_create(name_type=client_name_type, - names=client_account.split('/')) - - service_account = service_creds.get_username() - sname = self.PrincipalName_create(name_type=NT_PRINCIPAL, - names=[service_account]) - - realm = service_creds.get_realm() - - expected_crealm = realm - if expected_cname is None: - expected_cname = cname - expected_srealm = realm - expected_sname = sname - - expected_supported_etypes = service_creds.tgs_supported_enctypes - - etypes = (AES256_CTS_HMAC_SHA1_96, ARCFOUR_HMAC_MD5) - - if kdc_options is None: - kdc_options = 'canonicalize' - kdc_options = str(krb5_asn1.KDCOptions(kdc_options)) - - target_decryption_key = self.TicketDecryptionKey_from_creds( - service_creds) - - authenticator_subkey = self.RandomKey(kcrypto.Enctype.AES256) - - if expect_error: - expected_error_mode = KDC_ERR_TGT_REVOKED - check_error_fn = self.generic_check_kdc_error - check_rep_fn = None - else: - expected_error_mode = 0 - check_error_fn = None - check_rep_fn = self.generic_check_kdc_rep - - kdc_exchange_dict = self.tgs_exchange_dict( - expected_crealm=expected_crealm, - expected_cname=expected_cname, - expected_srealm=expected_srealm, - expected_sname=expected_sname, - expected_account_name=expected_account_name, - expected_upn_name=expected_upn_name, - expected_sid=expected_sid, - expected_supported_etypes=expected_supported_etypes, - ticket_decryption_key=target_decryption_key, - check_error_fn=check_error_fn, - check_rep_fn=check_rep_fn, - check_kdc_private_fn=self.generic_check_kdc_private, - expected_error_mode=expected_error_mode, - tgt=tgt, - authenticator_subkey=authenticator_subkey, - kdc_options=kdc_options, - pac_request=pac_request, - expect_pac=expect_pac, - expect_edata=False) - - rep = self._generic_kdc_exchange(kdc_exchange_dict, - cname=cname, - realm=realm, - sname=sname, - etypes=etypes) - if expect_error: - self.check_error_rep(rep, expected_error_mode) - - return None - else: - self.check_reply(rep, KRB_TGS_REP) - - return kdc_exchange_dict['rep_ticket_creds'] - def test_request(self): client_creds = self.get_client_creds() service_creds = self.get_service_creds() -- 2.25.1 From 7c9faf1aacc3c22c0c1a44a7259ddd995bc26c4a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:06:53 +1200 Subject: [PATCH 28/68] CVE-2022-32744 tests/krb5: Correctly calculate salt for pre-existing accounts BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/kdc_base_test.py | 1 + python/samba/tests/krb5/raw_testcase.py | 1 + 2 files changed, 2 insertions(+) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index 097b7813711..dd83b64a9a2 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -1065,6 +1065,7 @@ class KDCBaseTest(RawKerberosTest): kvno = int(res[0]['msDS-KeyVersionNumber'][0]) creds.set_kvno(kvno) + creds.set_workstation(username[:-1]) creds.set_dn(dn) keys = self.get_keys(samdb, dn) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index edebba6ae91..3c3004392bc 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -865,6 +865,7 @@ class RawKerberosTest(TestCaseInTempDir): allow_missing_password=allow_missing_password, allow_missing_keys=allow_missing_keys) c.set_gensec_features(c.get_gensec_features() | FEATURE_SEAL) + c.set_workstation('') return c def get_rodc_krbtgt_creds(self, -- 2.25.1 From a0efc5bc0aeff42563660cd68ba4dcb85d609bc6 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:13:54 +1200 Subject: [PATCH 29/68] CVE-2022-2031 tests/krb5: Add new definitions for kpasswd BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/rfc4120.asn1 | 6 ++++++ python/samba/tests/krb5/rfc4120_constants.py | 13 +++++++++++++ python/samba/tests/krb5/rfc4120_pyasn1.py | 13 ++++++++++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/python/samba/tests/krb5/rfc4120.asn1 b/python/samba/tests/krb5/rfc4120.asn1 index 7b146015548..e2f96829370 100644 --- a/python/samba/tests/krb5/rfc4120.asn1 +++ b/python/samba/tests/krb5/rfc4120.asn1 @@ -568,6 +568,12 @@ PA-FX-FAST-REPLY ::= CHOICE { ... } +ChangePasswdDataMS ::= SEQUENCE { + newpasswd [0] OCTET STRING, + targname [1] PrincipalName OPTIONAL, + targrealm [2] Realm OPTIONAL +} + -- MS-KILE End -- -- diff --git a/python/samba/tests/krb5/rfc4120_constants.py b/python/samba/tests/krb5/rfc4120_constants.py index 1bf7ebf499e..8d8340e4711 100644 --- a/python/samba/tests/krb5/rfc4120_constants.py +++ b/python/samba/tests/krb5/rfc4120_constants.py @@ -27,11 +27,13 @@ ARCFOUR_HMAC_MD5 = int( # Message types KRB_ERROR = int(krb5_asn1.MessageTypeValues('krb-error')) +KRB_AP_REP = int(krb5_asn1.MessageTypeValues('krb-ap-rep')) KRB_AP_REQ = int(krb5_asn1.MessageTypeValues('krb-ap-req')) KRB_AS_REP = int(krb5_asn1.MessageTypeValues('krb-as-rep')) KRB_AS_REQ = int(krb5_asn1.MessageTypeValues('krb-as-req')) KRB_TGS_REP = int(krb5_asn1.MessageTypeValues('krb-tgs-rep')) KRB_TGS_REQ = int(krb5_asn1.MessageTypeValues('krb-tgs-req')) +KRB_PRIV = int(krb5_asn1.MessageTypeValues('krb-priv')) # PAData types PADATA_ENC_TIMESTAMP = int( @@ -82,6 +84,7 @@ KDC_ERR_TGT_REVOKED = 20 KDC_ERR_PREAUTH_FAILED = 24 KDC_ERR_PREAUTH_REQUIRED = 25 KDC_ERR_BAD_INTEGRITY = 31 +KDC_ERR_TKT_EXPIRED = 32 KRB_ERR_TKT_NYV = 33 KDC_ERR_NOT_US = 35 KDC_ERR_BADMATCH = 36 @@ -93,6 +96,16 @@ KDC_ERR_WRONG_REALM = 68 KDC_ERR_CLIENT_NAME_MISMATCH = 75 KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS = 93 +# Kpasswd error codes +KPASSWD_SUCCESS = 0 +KPASSWD_MALFORMED = 1 +KPASSWD_HARDERROR = 2 +KPASSWD_AUTHERROR = 3 +KPASSWD_SOFTERROR = 4 +KPASSWD_ACCESSDENIED = 5 +KPASSWD_BAD_VERSION = 6 +KPASSWD_INITIAL_FLAG_NEEDED = 7 + # Extended error types KERB_AP_ERR_TYPE_SKEW_RECOVERY = int( krb5_asn1.KerbErrorDataTypeValues('kERB-AP-ERR-TYPE-SKEW-RECOVERY')) diff --git a/python/samba/tests/krb5/rfc4120_pyasn1.py b/python/samba/tests/krb5/rfc4120_pyasn1.py index d789ab96b43..ef77ac19ce3 100644 --- a/python/samba/tests/krb5/rfc4120_pyasn1.py +++ b/python/samba/tests/krb5/rfc4120_pyasn1.py @@ -1,5 +1,5 @@ # Auto-generated by asn1ate v.0.6.1.dev0 from rfc4120.asn1 -# (last modified on 2021-06-25 12:10:34.484667) +# (last modified on 2022-05-13 20:03:06.039817) # KerberosV5Spec2 from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful @@ -364,6 +364,17 @@ Authenticator.componentType = namedtype.NamedTypes( ) +class ChangePasswdDataMS(univ.Sequence): + pass + + +ChangePasswdDataMS.componentType = namedtype.NamedTypes( + namedtype.NamedType('newpasswd', univ.OctetString().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), + namedtype.OptionalNamedType('targname', PrincipalName().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), + namedtype.OptionalNamedType('targrealm', Realm().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))) +) + + class ChecksumTypeValues(univ.Integer): pass -- 2.25.1 From 7cc2b1ac55390cefca0644534939329b49a9535a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:17:45 +1200 Subject: [PATCH 30/68] CVE-2022-2031 tests/krb5: Add methods to create ASN1 kpasswd structures BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/raw_testcase.py | 95 +++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 3c3004392bc..6a217e62c3f 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -56,6 +56,7 @@ from samba.tests.krb5.rfc4120_constants import ( KRB_AS_REP, KRB_AS_REQ, KRB_ERROR, + KRB_PRIV, KRB_TGS_REP, KRB_TGS_REQ, KU_AP_REQ_AUTH, @@ -66,6 +67,7 @@ from samba.tests.krb5.rfc4120_constants import ( KU_FAST_FINISHED, KU_FAST_REP, KU_FAST_REQ_CHKSUM, + KU_KRB_PRIV, KU_NON_KERB_CKSUM_SALT, KU_TGS_REP_ENC_PART_SESSION, KU_TGS_REP_ENC_PART_SUB_KEY, @@ -1811,6 +1813,99 @@ class RawKerberosTest(TestCaseInTempDir): PA_S4U2Self_obj, asn1Spec=krb5_asn1.PA_S4U2Self()) return self.PA_DATA_create(PADATA_FOR_USER, pa_s4u2self) + def ChangePasswdDataMS_create(self, + new_password, + target_princ=None, + target_realm=None): + ChangePasswdDataMS_obj = { + 'newpasswd': new_password, + } + if target_princ is not None: + ChangePasswdDataMS_obj['targname'] = target_princ + if target_realm is not None: + ChangePasswdDataMS_obj['targrealm'] = target_realm + + change_password_data = self.der_encode( + ChangePasswdDataMS_obj, asn1Spec=krb5_asn1.ChangePasswdDataMS()) + + return change_password_data + + def KRB_PRIV_create(self, + subkey, + user_data, + s_address, + timestamp=None, + usec=None, + seq_number=None, + r_address=None): + EncKrbPrivPart_obj = { + 'user-data': user_data, + 's-address': s_address, + } + if timestamp is not None: + EncKrbPrivPart_obj['timestamp'] = timestamp + if usec is not None: + EncKrbPrivPart_obj['usec'] = usec + if seq_number is not None: + EncKrbPrivPart_obj['seq-number'] = seq_number + if r_address is not None: + EncKrbPrivPart_obj['r-address'] = r_address + + enc_krb_priv_part = self.der_encode( + EncKrbPrivPart_obj, asn1Spec=krb5_asn1.EncKrbPrivPart()) + + enc_data = self.EncryptedData_create(subkey, + KU_KRB_PRIV, + enc_krb_priv_part) + + KRB_PRIV_obj = { + 'pvno': 5, + 'msg-type': KRB_PRIV, + 'enc-part': enc_data, + } + + krb_priv = self.der_encode( + KRB_PRIV_obj, asn1Spec=krb5_asn1.KRB_PRIV()) + + return krb_priv + + def kpasswd_create(self, + subkey, + user_data, + version, + seq_number, + ap_req, + local_address, + remote_address): + self.assertIsNotNone(self.s, 'call self.connect() first') + + timestamp, usec = self.get_KerberosTimeWithUsec() + + krb_priv = self.KRB_PRIV_create(subkey, + user_data, + s_address=local_address, + timestamp=timestamp, + usec=usec, + seq_number=seq_number, + r_address=remote_address) + + size = 6 + len(ap_req) + len(krb_priv) + self.assertLess(size, 0x10000) + + msg = bytearray() + msg.append(size >> 8) + msg.append(size & 0xff) + msg.append(version >> 8) + msg.append(version & 0xff) + msg.append(len(ap_req) >> 8) + msg.append(len(ap_req) & 0xff) + # Note: for sets, there could be a little-endian four-byte length here. + + msg.extend(ap_req) + msg.extend(krb_priv) + + return msg + def _generic_kdc_exchange(self, kdc_exchange_dict, # required cname=None, # optional -- 2.25.1 From 82bfffcdc3cd2ae5f71f5cc18bf862ac88ee038a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:21:37 +1200 Subject: [PATCH 31/68] CVE-2022-2031 tests/krb5: Add 'port' parameter to connect() This allows us to use the kpasswd port, 464. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/raw_testcase.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 6a217e62c3f..63793a461fb 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -669,10 +669,11 @@ class RawKerberosTest(TestCaseInTempDir): if self.do_hexdump: sys.stderr.write("disconnect[%s]\n" % reason) - def _connect_tcp(self, host): - tcp_port = 88 + def _connect_tcp(self, host, port=None): + if port is None: + port = 88 try: - self.a = socket.getaddrinfo(host, tcp_port, socket.AF_UNSPEC, + self.a = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, 0) self.s = socket.socket(self.a[0][0], self.a[0][1], self.a[0][2]) @@ -685,9 +686,9 @@ class RawKerberosTest(TestCaseInTempDir): self.s.close() raise - def connect(self, host): + def connect(self, host, port=None): self.assertNotConnected() - self._connect_tcp(host) + self._connect_tcp(host, port) if self.do_hexdump: sys.stderr.write("connected[%s]\n" % host) -- 2.25.1 From 5f32710d6787bbf821a37f786a3e82360b7b7660 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:20:28 +1200 Subject: [PATCH 32/68] CVE-2022-2031 tests/krb5: Add methods to send and receive generic messages This allows us to send and receive kpasswd messages, while avoiding the existing logic for encoding and decoding other Kerberos message types. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/raw_testcase.py | 44 +++++++++++++++---------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 63793a461fb..5c4601bf0fa 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -951,24 +951,28 @@ class RawKerberosTest(TestCaseInTempDir): return blob def send_pdu(self, req, asn1_print=None, hexdump=None): + k5_pdu = self.der_encode( + req, native_decode=False, asn1_print=asn1_print, hexdump=False) + self.send_msg(k5_pdu, hexdump=hexdump) + + def send_msg(self, msg, hexdump=None): + header = struct.pack('>I', len(msg)) + req_pdu = header + req_pdu += msg + self.hex_dump("send_msg", header, hexdump=hexdump) + self.hex_dump("send_msg", msg, hexdump=hexdump) + try: - k5_pdu = self.der_encode( - req, native_decode=False, asn1_print=asn1_print, hexdump=False) - header = struct.pack('>I', len(k5_pdu)) - req_pdu = header - req_pdu += k5_pdu - self.hex_dump("send_pdu", header, hexdump=hexdump) - self.hex_dump("send_pdu", k5_pdu, hexdump=hexdump) while True: sent = self.s.send(req_pdu, 0) if sent == len(req_pdu): - break + return req_pdu = req_pdu[sent:] except socket.error as e: - self._disconnect("send_pdu: %s" % e) + self._disconnect("send_msg: %s" % e) raise except IOError as e: - self._disconnect("send_pdu: %s" % e) + self._disconnect("send_msg: %s" % e) raise def recv_raw(self, num_recv=0xffff, hexdump=None, timeout=None): @@ -994,16 +998,14 @@ class RawKerberosTest(TestCaseInTempDir): return rep_pdu def recv_pdu_raw(self, asn1_print=None, hexdump=None, timeout=None): - rep_pdu = None - rep = None raw_pdu = self.recv_raw( num_recv=4, hexdump=hexdump, timeout=timeout) if raw_pdu is None: - return (None, None) + return None header = struct.unpack(">I", raw_pdu[0:4]) k5_len = header[0] if k5_len == 0: - return (None, "") + return "" missing = k5_len rep_pdu = b'' while missing > 0: @@ -1012,6 +1014,14 @@ class RawKerberosTest(TestCaseInTempDir): self.assertGreaterEqual(len(raw_pdu), 1) rep_pdu += raw_pdu missing = k5_len - len(rep_pdu) + return rep_pdu + + def recv_reply(self, asn1_print=None, hexdump=None, timeout=None): + rep_pdu = self.recv_pdu_raw(asn1_print=asn1_print, + hexdump=hexdump, + timeout=timeout) + if not rep_pdu: + return None, rep_pdu k5_raw = self.der_decode( rep_pdu, asn1Spec=None, @@ -1033,9 +1043,9 @@ class RawKerberosTest(TestCaseInTempDir): return (rep, rep_pdu) def recv_pdu(self, asn1_print=None, hexdump=None, timeout=None): - (rep, rep_pdu) = self.recv_pdu_raw(asn1_print=asn1_print, - hexdump=hexdump, - timeout=timeout) + (rep, rep_pdu) = self.recv_reply(asn1_print=asn1_print, + hexdump=hexdump, + timeout=timeout) return rep def assertIsConnected(self): -- 2.25.1 From a907564b698b5a2647ccf011db6ee45d5049ed04 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:26:56 +1200 Subject: [PATCH 33/68] tests/krb5: Fix enum typo Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/kdc_base_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index dd83b64a9a2..22360cb9383 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -248,9 +248,9 @@ class KDCBaseTest(RawKerberosTest): which is used by tearDownClass to clean up the created accounts. ''' if ou is None: - if account_type is account_type.COMPUTER: + if account_type is self.AccountType.COMPUTER: guid = DS_GUID_COMPUTERS_CONTAINER - elif account_type is account_type.SERVER: + elif account_type is self.AccountType.SERVER: guid = DS_GUID_DOMAIN_CONTROLLERS_CONTAINER else: guid = DS_GUID_USERS_CONTAINER -- 2.25.1 From 3e52255fd1623883449ab0ef8e759e0463662597 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:30:12 +1200 Subject: [PATCH 34/68] tests/krb5: Add option for creating accounts with expired passwords Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/kdc_base_test.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index 22360cb9383..5316f94511c 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -242,7 +242,8 @@ class KDCBaseTest(RawKerberosTest): def create_account(self, samdb, name, account_type=AccountType.USER, spn=None, upn=None, additional_details=None, - ou=None, account_control=0, add_dollar=True): + ou=None, account_control=0, add_dollar=True, + expired_password=False): '''Create an account for testing. The dn of the created account is added to self.accounts, which is used by tearDownClass to clean up the created accounts. @@ -296,6 +297,8 @@ class KDCBaseTest(RawKerberosTest): details["servicePrincipalName"] = spn if upn is not None: details["userPrincipalName"] = upn + if expired_password: + details["pwdLastSet"] = "0" if additional_details is not None: details.update(additional_details) samdb.add(details) @@ -663,6 +666,7 @@ class KDCBaseTest(RawKerberosTest): 'revealed_to_rodc': False, 'revealed_to_mock_rodc': False, 'no_auth_data_required': False, + 'expired_password': False, 'supported_enctypes': None, 'not_delegated': False, 'delegation_to_spn': None, @@ -705,6 +709,7 @@ class KDCBaseTest(RawKerberosTest): revealed_to_rodc, revealed_to_mock_rodc, no_auth_data_required, + expired_password, supported_enctypes, not_delegated, delegation_to_spn, @@ -764,7 +769,8 @@ class KDCBaseTest(RawKerberosTest): spn=spn, additional_details=details, account_control=user_account_control, - add_dollar=add_dollar) + add_dollar=add_dollar, + expired_password=expired_password) keys = self.get_keys(samdb, dn) self.creds_set_keys(creds, keys) -- 2.25.1 From 06c7f3d3f672646b2e0e556693df83761e8dc4e1 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:34:59 +1200 Subject: [PATCH 35/68] CVE-2022-2031 tests/krb5: Allow requesting a TGT to a different sname and realm BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Fixed conflict due to lacking rc4_support parameter] --- python/samba/tests/krb5/kdc_base_test.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index 5316f94511c..a4f0d8541d0 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -1361,10 +1361,12 @@ class KDCBaseTest(RawKerberosTest): expected_flags=None, unexpected_flags=None, pac_request=True, expect_pac=True, fresh=False): user_name = tgt.cname['name-string'][0] + ticket_sname = tgt.sname if target_name is None: target_name = target_creds.get_username()[:-1] cache_key = (user_name, target_name, service, to_rodc, kdc_options, pac_request, str(expected_flags), str(unexpected_flags), + str(ticket_sname), expect_pac) if not fresh: @@ -1433,6 +1435,7 @@ class KDCBaseTest(RawKerberosTest): expected_account_name=None, expected_upn_name=None, expected_cname=None, expected_sid=None, + sname=None, realm=None, pac_request=True, expect_pac=True, expect_pac_attrs=None, expect_pac_attrs_pac_request=None, expect_requester_sid=None, @@ -1446,6 +1449,7 @@ class KDCBaseTest(RawKerberosTest): client_name_type, str(expected_flags), str(unexpected_flags), expected_account_name, expected_upn_name, expected_sid, + str(sname), str(realm), str(expected_cname), expect_pac, expect_pac_attrs, expect_pac_attrs_pac_request, expect_requester_sid) @@ -1456,15 +1460,21 @@ class KDCBaseTest(RawKerberosTest): if tgt is not None: return tgt - realm = creds.get_realm() + if realm is None: + realm = creds.get_realm() salt = creds.get_salt() etype = (AES256_CTS_HMAC_SHA1_96, ARCFOUR_HMAC_MD5) cname = self.PrincipalName_create(name_type=client_name_type, names=user_name.split('/')) - sname = self.PrincipalName_create(name_type=NT_SRV_INST, - names=['krbtgt', realm]) + if sname is None: + sname = self.PrincipalName_create(name_type=NT_SRV_INST, + names=['krbtgt', realm]) + expected_sname = self.PrincipalName_create( + name_type=NT_SRV_INST, names=['krbtgt', realm.upper()]) + else: + expected_sname = sname if expected_cname is None: expected_cname = cname @@ -1533,9 +1543,6 @@ class KDCBaseTest(RawKerberosTest): expected_realm = realm.upper() - expected_sname = self.PrincipalName_create( - name_type=NT_SRV_INST, names=['krbtgt', realm.upper()]) - rep, kdc_exchange_dict = self._test_as_exchange( cname=cname, realm=realm, -- 2.25.1 From c84eb0e673640aeb391766bda50ec7649a75e4d9 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:57:57 +1200 Subject: [PATCH 36/68] CVE-2022-2031 tests/krb5: Add kpasswd_exchange() method Now we can test the kpasswd service from Python. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/raw_testcase.py | 264 ++++++++++++++++++++++-- 1 file changed, 251 insertions(+), 13 deletions(-) diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 5c4601bf0fa..6cacc3f8fca 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -26,6 +26,8 @@ import binascii import itertools import collections +from enum import Enum + from pyasn1.codec.der.decoder import decode as pyasn1_der_decode from pyasn1.codec.der.encoder import encode as pyasn1_der_encode from pyasn1.codec.native.decoder import decode as pyasn1_native_decode @@ -33,6 +35,8 @@ from pyasn1.codec.native.encoder import encode as pyasn1_native_encode from pyasn1.codec.ber.encoder import BitStringEncoder +from pyasn1.error import PyAsn1Error + from samba.credentials import Credentials from samba.dcerpc import krb5pac, security from samba.gensec import FEATURE_SEAL @@ -52,6 +56,7 @@ from samba.tests.krb5.rfc4120_constants import ( KDC_ERR_SKEW, KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTIONS, KERB_ERR_TYPE_EXTENDED, + KRB_AP_REP, KRB_AP_REQ, KRB_AS_REP, KRB_AS_REQ, @@ -61,6 +66,7 @@ from samba.tests.krb5.rfc4120_constants import ( KRB_TGS_REQ, KU_AP_REQ_AUTH, KU_AS_REP_ENC_PART, + KU_AP_REQ_ENC_PART, KU_AS_REQ, KU_ENC_CHALLENGE_KDC, KU_FAST_ENC, @@ -76,6 +82,7 @@ from samba.tests.krb5.rfc4120_constants import ( KU_TGS_REQ_AUTH_DAT_SESSION, KU_TGS_REQ_AUTH_DAT_SUBKEY, KU_TICKET, + NT_PRINCIPAL, NT_SRV_INST, NT_WELLKNOWN, PADATA_ENCRYPTED_CHALLENGE, @@ -521,6 +528,10 @@ class KerberosTicketCreds: class RawKerberosTest(TestCaseInTempDir): """A raw Kerberos Test case.""" + class KpasswdMode(Enum): + SET = object() + CHANGE = object() + pac_checksum_types = {krb5pac.PAC_TYPE_SRV_CHECKSUM, krb5pac.PAC_TYPE_KDC_CHECKSUM, krb5pac.PAC_TYPE_TICKET_CHECKSUM} @@ -1917,6 +1928,224 @@ class RawKerberosTest(TestCaseInTempDir): return msg + def get_enc_part(self, obj, key, usage): + self.assertElementEqual(obj, 'pvno', 5) + + enc_part = obj['enc-part'] + self.assertElementEqual(enc_part, 'etype', key.etype) + self.assertElementKVNO(enc_part, 'kvno', key.kvno) + + enc_part = key.decrypt(usage, enc_part['cipher']) + + return enc_part + + def kpasswd_exchange(self, + ticket, + new_password, + expected_code, + expected_msg, + mode, + target_princ=None, + target_realm=None, + ap_options=None, + send_seq_number=True): + if mode is self.KpasswdMode.SET: + version = 0xff80 + user_data = self.ChangePasswdDataMS_create(new_password, + target_princ, + target_realm) + elif mode is self.KpasswdMode.CHANGE: + self.assertIsNone(target_princ, + 'target_princ only valid for pw set') + self.assertIsNone(target_realm, + 'target_realm only valid for pw set') + + version = 1 + user_data = new_password.encode('utf-8') + else: + self.fail(f'invalid mode {mode}') + + subkey = self.RandomKey(kcrypto.Enctype.AES256) + + if ap_options is None: + ap_options = '0' + ap_options = str(krb5_asn1.APOptions(ap_options)) + + kdc_exchange_dict = { + 'tgt': ticket, + 'authenticator_subkey': subkey, + 'auth_data': None, + 'ap_options': ap_options, + } + + if send_seq_number: + seq_number = random.randint(0, 0xfffffffe) + else: + seq_number = None + + ap_req = self.generate_ap_req(kdc_exchange_dict, + None, + req_body=None, + armor=False, + usage=KU_AP_REQ_AUTH, + seq_number=seq_number) + + self.connect(self.host, port=464) + self.assertIsNotNone(self.s) + + family = self.s.family + + if family == socket.AF_INET: + addr_type = 2 # IPv4 + elif family == socket.AF_INET6: + addr_type = 24 # IPv6 + else: + self.fail(f'unknown family {family}') + + def create_address(ip): + return { + 'addr-type': addr_type, + 'address': socket.inet_pton(family, ip), + } + + local_ip = self.s.getsockname()[0] + local_address = create_address(local_ip) + + # remote_ip = self.s.getpeername()[0] + # remote_address = create_address(remote_ip) + + # TODO: due to a bug (?), MIT Kerberos will not accept the request + # unless r-address is set to our _local_ address. Heimdal, on the other + # hand, requires the r-address is set to the remote address (as + # expected). To avoid problems, avoid sending r-address for now. + remote_address = None + + msg = self.kpasswd_create(subkey, + user_data, + version, + seq_number, + ap_req, + local_address, + remote_address) + + self.send_msg(msg) + rep_pdu = self.recv_pdu_raw() + + self._disconnect('transaction done') + + self.assertIsNotNone(rep_pdu) + + header = rep_pdu[:6] + reply = rep_pdu[6:] + + reply_len = (header[0] << 8) | header[1] + reply_version = (header[2] << 8) | header[3] + ap_rep_len = (header[4] << 8) | header[5] + + self.assertEqual(reply_len, len(rep_pdu)) + self.assertEqual(1, reply_version) # KRB5_KPASSWD_VERS_CHANGEPW + self.assertLess(ap_rep_len, reply_len) + + self.assertNotEqual(0x7e, rep_pdu[1]) + self.assertNotEqual(0x5e, rep_pdu[1]) + + if ap_rep_len: + # We received an AP-REQ and KRB-PRIV as a response. This may or may + # not indicate an error, depending on the status code. + ap_rep = reply[:ap_rep_len] + krb_priv = reply[ap_rep_len:] + + key = ticket.session_key + + ap_rep = self.der_decode(ap_rep, asn1Spec=krb5_asn1.AP_REP()) + self.assertElementEqual(ap_rep, 'msg-type', KRB_AP_REP) + enc_part = self.get_enc_part(ap_rep, key, KU_AP_REQ_ENC_PART) + enc_part = self.der_decode( + enc_part, asn1Spec=krb5_asn1.EncAPRepPart()) + + self.assertElementPresent(enc_part, 'ctime') + self.assertElementPresent(enc_part, 'cusec') + # self.assertElementMissing(enc_part, 'subkey') # TODO + # self.assertElementPresent(enc_part, 'seq-number') # TODO + + try: + krb_priv = self.der_decode(krb_priv, asn1Spec=krb5_asn1.KRB_PRIV()) + except PyAsn1Error: + self.fail() + + self.assertElementEqual(krb_priv, 'msg-type', KRB_PRIV) + priv_enc_part = self.get_enc_part(krb_priv, subkey, KU_KRB_PRIV) + priv_enc_part = self.der_decode( + priv_enc_part, asn1Spec=krb5_asn1.EncKrbPrivPart()) + + self.assertElementMissing(priv_enc_part, 'timestamp') + self.assertElementMissing(priv_enc_part, 'usec') + # self.assertElementPresent(priv_enc_part, 'seq-number') # TODO + # self.assertElementEqual(priv_enc_part, 's-address', remote_address) # TODO + # self.assertElementMissing(priv_enc_part, 'r-address') # TODO + + result_data = priv_enc_part['user-data'] + else: + # We received a KRB-ERROR as a response, indicating an error. + krb_error = self.der_decode(reply, asn1Spec=krb5_asn1.KRB_ERROR()) + + sname = self.PrincipalName_create( + name_type=NT_PRINCIPAL, + names=['kadmin', 'changepw']) + realm = self.get_krbtgt_creds().get_realm().upper() + + self.assertElementEqual(krb_error, 'pvno', 5) + self.assertElementEqual(krb_error, 'msg-type', KRB_ERROR) + self.assertElementMissing(krb_error, 'ctime') + self.assertElementMissing(krb_error, 'usec') + self.assertElementPresent(krb_error, 'stime') + self.assertElementPresent(krb_error, 'susec') + + error_code = krb_error['error-code'] + if isinstance(expected_code, int): + self.assertEqual(error_code, expected_code) + else: + self.assertIn(error_code, expected_code) + + self.assertElementMissing(krb_error, 'crealm') + self.assertElementMissing(krb_error, 'cname') + self.assertElementEqual(krb_error, 'realm', realm.encode('utf-8')) + self.assertElementEqualPrincipal(krb_error, 'sname', sname) + self.assertElementMissing(krb_error, 'e-text') + + result_data = krb_error['e-data'] + + status = result_data[:2] + message = result_data[2:] + + status_code = (status[0] << 8) | status[1] + if isinstance(expected_code, int): + self.assertEqual(status_code, expected_code) + else: + self.assertIn(status_code, expected_code) + + if not message: + self.assertEqual(0, status_code, + 'got an error result, but no message') + return + + # Check the first character of the message. + if message[0]: + if isinstance(expected_msg, bytes): + self.assertEqual(message, expected_msg) + else: + self.assertIn(message, expected_msg) + else: + # We got AD password policy information. + self.assertEqual(30, len(message)) + + (empty_bytes, + min_length, + history_length, + properties, + expire_time, + min_age) = struct.unpack('>HIIIQQ', message) + def _generic_kdc_exchange(self, kdc_exchange_dict, # required cname=None, # optional @@ -2027,7 +2256,7 @@ class RawKerberosTest(TestCaseInTempDir): self.assertIsNotNone(generate_fast_fn) fast_ap_req = generate_fast_armor_fn(kdc_exchange_dict, callback_dict, - req_body, + None, armor=True) fast_armor_type = kdc_exchange_dict['fast_armor_type'] @@ -3377,31 +3606,39 @@ class RawKerberosTest(TestCaseInTempDir): kdc_exchange_dict, _callback_dict, req_body, - armor): + armor, + usage=None, + seq_number=None): + req_body_checksum = None + if armor: + self.assertIsNone(req_body) + tgt = kdc_exchange_dict['armor_tgt'] authenticator_subkey = kdc_exchange_dict['armor_subkey'] - - req_body_checksum = None else: tgt = kdc_exchange_dict['tgt'] authenticator_subkey = kdc_exchange_dict['authenticator_subkey'] - body_checksum_type = kdc_exchange_dict['body_checksum_type'] - req_body_blob = self.der_encode(req_body, - asn1Spec=krb5_asn1.KDC_REQ_BODY()) + if req_body is not None: + body_checksum_type = kdc_exchange_dict['body_checksum_type'] + + req_body_blob = self.der_encode( + req_body, asn1Spec=krb5_asn1.KDC_REQ_BODY()) - req_body_checksum = self.Checksum_create(tgt.session_key, - KU_TGS_REQ_AUTH_CKSUM, - req_body_blob, - ctype=body_checksum_type) + req_body_checksum = self.Checksum_create( + tgt.session_key, + KU_TGS_REQ_AUTH_CKSUM, + req_body_blob, + ctype=body_checksum_type) auth_data = kdc_exchange_dict['auth_data'] subkey_obj = None if authenticator_subkey is not None: subkey_obj = authenticator_subkey.export_obj() - seq_number = random.randint(0, 0xfffffffe) + if seq_number is None: + seq_number = random.randint(0, 0xfffffffe) (ctime, cusec) = self.get_KerberosTimeWithUsec() authenticator_obj = self.Authenticator_create( crealm=tgt.crealm, @@ -3416,7 +3653,8 @@ class RawKerberosTest(TestCaseInTempDir): authenticator_obj, asn1Spec=krb5_asn1.Authenticator()) - usage = KU_AP_REQ_AUTH if armor else KU_TGS_REQ_AUTH + if usage is None: + usage = KU_AP_REQ_AUTH if armor else KU_TGS_REQ_AUTH authenticator = self.EncryptedData_create(tgt.session_key, usage, authenticator_blob) -- 2.25.1 From 4af9286727415485ae82fb68478753e70c0bbe6d Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 26 May 2022 16:35:03 +1200 Subject: [PATCH 37/68] CVE-2022-32744 selftest: Specify Administrator kvno for Python krb5 tests BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/selftest/tests.py | 1 + 1 file changed, 1 insertion(+) diff --git a/source4/selftest/tests.py b/source4/selftest/tests.py index e6847d384e8..9dceb3416ca 100755 --- a/source4/selftest/tests.py +++ b/source4/selftest/tests.py @@ -972,6 +972,7 @@ krb5_environ = { 'SERVICE_USERNAME': '$SERVER', 'ADMIN_USERNAME': '$DC_USERNAME', 'ADMIN_PASSWORD': '$DC_PASSWORD', + 'ADMIN_KVNO': '1', 'FOR_USER': '$DC_USERNAME', 'STRICT_CHECKING':'0', 'FAST_SUPPORT': have_fast_support, -- 2.25.1 From 8a4f07c2ca2dc153a3c5fc635ac261d372c62fde Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 19:59:16 +1200 Subject: [PATCH 38/68] CVE-2022-2031 tests/krb5: Add tests for kpasswd service BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Fixed conflicts in usage.py and knownfails; removed MIT KDC 1.20-specific knownfails as it's not supported] --- python/samba/tests/krb5/kdc_base_test.py | 4 +- python/samba/tests/krb5/kpasswd_tests.py | 1021 ++++++++++++++++++++++ python/samba/tests/krb5/raw_testcase.py | 8 + python/samba/tests/usage.py | 1 + selftest/knownfail_heimdal_kdc | 26 + selftest/knownfail_mit_kdc | 26 + source4/selftest/tests.py | 4 + 7 files changed, 1089 insertions(+), 1 deletion(-) create mode 100755 python/samba/tests/krb5/kpasswd_tests.py diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py index a4f0d8541d0..c0764a887b8 100644 --- a/python/samba/tests/krb5/kdc_base_test.py +++ b/python/samba/tests/krb5/kdc_base_test.py @@ -1622,7 +1622,9 @@ class KDCBaseTest(RawKerberosTest): authenticator_subkey = self.RandomKey(kcrypto.Enctype.AES256) if expect_error: - expected_error_mode = KDC_ERR_TGT_REVOKED + expected_error_mode = expect_error + if expected_error_mode is True: + expected_error_mode = KDC_ERR_TGT_REVOKED check_error_fn = self.generic_check_kdc_error check_rep_fn = None else: diff --git a/python/samba/tests/krb5/kpasswd_tests.py b/python/samba/tests/krb5/kpasswd_tests.py new file mode 100755 index 00000000000..3a6c7d818dc --- /dev/null +++ b/python/samba/tests/krb5/kpasswd_tests.py @@ -0,0 +1,1021 @@ +#!/usr/bin/env python3 +# Unix SMB/CIFS implementation. +# Copyright (C) Stefan Metzmacher 2020 +# Copyright (C) Catalyst.Net Ltd +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import os +import sys + +from functools import partial + +from samba import generate_random_password, unix2nttime +from samba.dcerpc import krb5pac, security +from samba.sd_utils import SDUtils + +from samba.tests.krb5.kdc_base_test import KDCBaseTest +from samba.tests.krb5.rfc4120_constants import ( + KDC_ERR_TGT_REVOKED, + KDC_ERR_TKT_EXPIRED, + KPASSWD_ACCESSDENIED, + KPASSWD_HARDERROR, + KPASSWD_INITIAL_FLAG_NEEDED, + KPASSWD_MALFORMED, + KPASSWD_SOFTERROR, + KPASSWD_SUCCESS, + NT_PRINCIPAL, + NT_SRV_INST, +) + +sys.path.insert(0, 'bin/python') +os.environ['PYTHONUNBUFFERED'] = '1' + +global_asn1_print = False +global_hexdump = False + + +# Note: these tests do not pass on Windows, which returns different error codes +# to the ones we have chosen, and does not always return additional error data. +class KpasswdTests(KDCBaseTest): + + def setUp(self): + super().setUp() + self.do_asn1_print = global_asn1_print + self.do_hexdump = global_hexdump + + samdb = self.get_samdb() + + # Get the old 'dSHeuristics' if it was set + dsheuristics = samdb.get_dsheuristics() + + # Reset the 'dSHeuristics' as they were before + self.addCleanup(samdb.set_dsheuristics, dsheuristics) + + # Set the 'dSHeuristics' to activate the correct 'userPassword' + # behaviour + samdb.set_dsheuristics('000000001') + + # Get the old 'minPwdAge' + minPwdAge = samdb.get_minPwdAge() + + # Reset the 'minPwdAge' as it was before + self.addCleanup(samdb.set_minPwdAge, minPwdAge) + + # Set it temporarily to '0' + samdb.set_minPwdAge('0') + + def _get_creds(self, expired=False): + opts = { + 'expired_password': expired + } + + # Create the account. + creds = self.get_cached_creds(account_type=self.AccountType.USER, + opts=opts, + use_cache=False) + + return creds + + def issued_by_rodc(self, ticket): + krbtgt_creds = self.get_mock_rodc_krbtgt_creds() + + krbtgt_key = self.TicketDecryptionKey_from_creds(krbtgt_creds) + checksum_keys = { + krb5pac.PAC_TYPE_KDC_CHECKSUM: krbtgt_key, + } + + return self.modified_ticket( + ticket, + new_ticket_key=krbtgt_key, + checksum_keys=checksum_keys) + + def get_kpasswd_sname(self): + return self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=['kadmin', 'changepw']) + + def get_ticket_lifetime(self, ticket): + enc_part = ticket.ticket_private + + authtime = enc_part['authtime'] + starttime = enc_part.get('starttime', authtime) + endtime = enc_part['endtime'] + + starttime = self.get_EpochFromKerberosTime(starttime) + endtime = self.get_EpochFromKerberosTime(endtime) + + return endtime - starttime + + def add_requester_sid(self, pac, sid): + pac_buffers = pac.buffers + + buffer_types = [pac_buffer.type for pac_buffer in pac_buffers] + self.assertNotIn(krb5pac.PAC_TYPE_REQUESTER_SID, buffer_types) + + requester_sid = krb5pac.PAC_REQUESTER_SID() + requester_sid.sid = security.dom_sid(sid) + + requester_sid_buffer = krb5pac.PAC_BUFFER() + requester_sid_buffer.type = krb5pac.PAC_TYPE_REQUESTER_SID + requester_sid_buffer.info = requester_sid + + pac_buffers.append(requester_sid_buffer) + + pac.buffers = pac_buffers + pac.num_buffers += 1 + + return pac + + # Test setting a password with kpasswd. + def test_kpasswd_set(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Test the newly set password. + creds.update_password(new_password) + self.get_tgt(creds, fresh=True) + + # Test changing a password with kpasswd. + def test_kpasswd_change(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test the newly set password. + creds.update_password(new_password) + self.get_tgt(creds, fresh=True) + + # Test kpasswd without setting the canonicalize option. + def test_kpasswd_no_canonicalize(self): + # Create an account for testing. + creds = self._get_creds() + + sname = self.get_kpasswd_sname() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + creds.update_password(new_password) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + kdc_options='0') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd with the canonicalize option reset and a non-canonical + # (by conversion to title case) realm. + def test_kpasswd_no_canonicalize_realm_case(self): + # Create an account for testing. + creds = self._get_creds() + + sname = self.get_kpasswd_sname() + realm = creds.get_realm().capitalize() # We use a title-cased realm. + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + realm=realm, + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + creds.update_password(new_password) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + realm=realm, + kdc_options='0') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd with the canonicalize option set. + def test_kpasswd_canonicalize(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. We set the canonicalize flag here. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='canonicalize') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + creds.update_password(new_password) + + # Get an initial ticket to kpasswd. We set the canonicalize flag here. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='canonicalize') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd with the canonicalize option set and a non-canonical (by + # conversion to title case) realm. + def test_kpasswd_canonicalize_realm_case(self): + # Create an account for testing. + creds = self._get_creds() + + sname = self.get_kpasswd_sname() + realm = creds.get_realm().capitalize() # We use a title-cased realm. + + # Get an initial ticket to kpasswd. We set the canonicalize flag here. + ticket = self.get_tgt(creds, sname=sname, + realm=realm, + kdc_options='canonicalize') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + creds.update_password(new_password) + + # Get an initial ticket to kpasswd. We set the canonicalize flag here. + ticket = self.get_tgt(creds, sname=sname, + realm=realm, + kdc_options='canonicalize') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd rejects a password that does not meet complexity + # requirements. + def test_kpasswd_too_weak(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SOFTERROR + expected_msg = b'Password does not meet complexity requirements' + + # Set the password. + new_password = 'password' + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd rejects an empty new password. + def test_kpasswd_empty(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SOFTERROR, KPASSWD_HARDERROR + expected_msg = (b'Password too short, password must be at least 7 ' + b'characters long.', + b'String conversion failed!') + + # Set the password. + new_password = '' + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + expected_code = KPASSWD_HARDERROR + expected_msg = b'String conversion failed!' + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test kpasswd rejects a request that does not include a random sequence + # number. + def test_kpasswd_no_seq_number(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_HARDERROR + expected_msg = b'gensec_unwrap failed - NT_STATUS_ACCESS_DENIED\n' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET, + send_seq_number=False) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE, + send_seq_number=False) + + # Test kpasswd rejects a ticket issued by an RODC. + def test_kpasswd_from_rodc(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + # Have the ticket be issued by the RODC. + ticket = self.issued_by_rodc(ticket) + + expected_code = KPASSWD_HARDERROR + expected_msg = b'gensec_update failed - NT_STATUS_LOGON_FAILURE\n' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test setting a password, specifying the principal of the target user. + def test_kpasswd_set_target_princ_only(self): + # Create an account for testing. + creds = self._get_creds() + username = creds.get_username() + + cname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=username.split('/')) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_MALFORMED + expected_msg = (b'Realm and principal must be both present, or ' + b'neither present', + b'Failed to decode packet') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET, + target_princ=cname) + + # Test that kpasswd rejects a password set specifying only the realm of the + # target user. + def test_kpasswd_set_target_realm_only(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_MALFORMED, KPASSWD_ACCESSDENIED + expected_msg = (b'Realm and principal must be both present, or ' + b'neither present', + b'Failed to decode packet', + b'No such user when changing password') + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET, + target_realm=creds.get_realm()) + + # Show that a user cannot set a password, specifying both principal and + # realm of the target user, without having control access. + def test_kpasswd_set_target_princ_and_realm_no_access(self): + # Create an account for testing. + creds = self._get_creds() + username = creds.get_username() + + cname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=username.split('/')) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_ACCESSDENIED + expected_msg = b'Not permitted to change password' + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET, + target_princ=cname, + target_realm=creds.get_realm()) + + # Test setting a password, specifying both principal and realm of the + # target user, whem the user has control access on their account. + def test_kpasswd_set_target_princ_and_realm_access(self): + # Create an account for testing. + creds = self._get_creds() + username = creds.get_username() + tgt = self.get_tgt(creds) + + cname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=username.split('/')) + + samdb = self.get_samdb() + sd_utils = SDUtils(samdb) + + user_dn = creds.get_dn() + user_sid = self.get_objectSid(samdb, user_dn) + + # Give the user control access on their account. + ace = f'(A;;CR;;;{user_sid})' + sd_utils.dacl_add_ace(user_dn, ace) + + # Get a non-initial ticket to kpasswd. Since we have the right to + # change the account's password, we don't need an initial ticket. + krbtgt_creds = self.get_krbtgt_creds() + ticket = self.get_service_ticket(tgt, + krbtgt_creds, + service='kadmin', + target_name='changepw', + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET, + target_princ=cname, + target_realm=creds.get_realm()) + + # Test setting a password when the existing password has expired. + def test_kpasswd_set_expired_password(self): + # Create an account for testing, with an expired password. + creds = self._get_creds(expired=True) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Test changing a password when the existing password has expired. + def test_kpasswd_change_expired_password(self): + # Create an account for testing, with an expired password. + creds = self._get_creds(expired=True) + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Check the lifetime of a kpasswd ticket is not more than two minutes. + def test_kpasswd_ticket_lifetime(self): + # Create an account for testing. + creds = self._get_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + # Check the lifetime of the ticket is equal to two minutes. + lifetime = self.get_ticket_lifetime(ticket) + self.assertEqual(2 * 60, lifetime) + + # Ensure we cannot perform a TGS-REQ with a kpasswd ticket. + def test_kpasswd_ticket_tgs(self): + creds = self.get_client_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + # Change the sname of the ticket to match that of a TGT. + realm = creds.get_realm() + krbtgt_sname = self.PrincipalName_create(name_type=NT_SRV_INST, + names=['krbtgt', realm]) + ticket.set_sname(krbtgt_sname) + + # Try to use that ticket to get a service ticket. + service_creds = self.get_service_creds() + + # This fails due to missing REQUESTER_SID buffer. + self._make_tgs_request(creds, service_creds, ticket, + expect_error=(KDC_ERR_TGT_REVOKED, + KDC_ERR_TKT_EXPIRED)) + + def modify_requester_sid_time(self, ticket, sid, lifetime): + # Get the krbtgt key. + krbtgt_creds = self.get_krbtgt_creds() + + krbtgt_key = self.TicketDecryptionKey_from_creds(krbtgt_creds) + checksum_keys = { + krb5pac.PAC_TYPE_KDC_CHECKSUM: krbtgt_key, + } + + # Set authtime and starttime to an hour in the past, to show that they + # do not affect ticket rejection. + start_time = self.get_KerberosTime(offset=-60 * 60) + + # Set the endtime of the ticket relative to our current time, so that + # the ticket has 'lifetime' seconds remaining to live. + end_time = self.get_KerberosTime(offset=lifetime) + + # Modify the times in the ticket. + def modify_ticket_times(enc_part): + enc_part['authtime'] = start_time + if 'starttime' in enc_part: + enc_part['starttime'] = start_time + + enc_part['endtime'] = end_time + + return enc_part + + # We have to set the times in both the ticket and the PAC, otherwise + # Heimdal will complain. + def modify_pac_time(pac): + pac_buffers = pac.buffers + + for pac_buffer in pac_buffers: + if pac_buffer.type == krb5pac.PAC_TYPE_LOGON_NAME: + logon_time = self.get_EpochFromKerberosTime(start_time) + pac_buffer.info.logon_time = unix2nttime(logon_time) + break + else: + self.fail('failed to find LOGON_NAME PAC buffer') + + pac.buffers = pac_buffers + + return pac + + # Add a requester SID to show that the KDC will then accept this + # kpasswd ticket as if it were a TGT. + def modify_pac_fn(pac): + pac = self.add_requester_sid(pac, sid=sid) + pac = modify_pac_time(pac) + return pac + + # Do the actual modification. + return self.modified_ticket(ticket, + new_ticket_key=krbtgt_key, + modify_fn=modify_ticket_times, + modify_pac_fn=modify_pac_fn, + checksum_keys=checksum_keys) + + # Ensure we cannot perform a TGS-REQ with a kpasswd ticket containing a + # requester SID and having a remaining lifetime of two minutes. + def test_kpasswd_ticket_requester_sid_tgs(self): + creds = self.get_client_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + # Change the sname of the ticket to match that of a TGT. + realm = creds.get_realm() + krbtgt_sname = self.PrincipalName_create(name_type=NT_SRV_INST, + names=['krbtgt', realm]) + ticket.set_sname(krbtgt_sname) + + # Get the user's SID. + samdb = self.get_samdb() + + user_dn = creds.get_dn() + user_sid = self.get_objectSid(samdb, user_dn) + + # Modify the ticket to add a requester SID and give it two minutes to + # live. + ticket = self.modify_requester_sid_time(ticket, + sid=user_sid, + lifetime=2 * 60) + + # Try to use that ticket to get a service ticket. + service_creds = self.get_service_creds() + + # This fails due to the lifetime being too short. + self._make_tgs_request(creds, service_creds, ticket, + expect_error=KDC_ERR_TKT_EXPIRED) + + # Show we can perform a TGS-REQ with a kpasswd ticket containing a + # requester SID if the remaining lifetime exceeds two minutes. + def test_kpasswd_ticket_requester_sid_lifetime_tgs(self): + creds = self.get_client_creds() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=self.get_kpasswd_sname(), + kdc_options='0') + + # Change the sname of the ticket to match that of a TGT. + realm = creds.get_realm() + krbtgt_sname = self.PrincipalName_create(name_type=NT_SRV_INST, + names=['krbtgt', realm]) + ticket.set_sname(krbtgt_sname) + + # Get the user's SID. + samdb = self.get_samdb() + + user_dn = creds.get_dn() + user_sid = self.get_objectSid(samdb, user_dn) + + # Modify the ticket to add a requester SID and give it two minutes and + # ten seconds to live. + ticket = self.modify_requester_sid_time(ticket, + sid=user_sid, + lifetime=2 * 60 + 10) + + # Try to use that ticket to get a service ticket. + service_creds = self.get_service_creds() + + # This succeeds. + self._make_tgs_request(creds, service_creds, ticket, + expect_error=False) + + # Test that kpasswd rejects requests with a service ticket. + def test_kpasswd_non_initial(self): + # Create an account for testing, and get a TGT. + creds = self._get_creds() + tgt = self.get_tgt(creds) + + # Get a non-initial ticket to kpasswd. + krbtgt_creds = self.get_krbtgt_creds() + ticket = self.get_service_ticket(tgt, + krbtgt_creds, + service='kadmin', + target_name='changepw', + kdc_options='0') + + expected_code = KPASSWD_INITIAL_FLAG_NEEDED + expected_msg = b'Expected an initial ticket' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Show that kpasswd accepts requests with a service ticket modified to set + # the 'initial' flag. + def test_kpasswd_initial(self): + # Create an account for testing, and get a TGT. + creds = self._get_creds() + + krbtgt_creds = self.get_krbtgt_creds() + + # Get a service ticket, and modify it to set the 'initial' flag. + def get_ticket(): + tgt = self.get_tgt(creds, fresh=True) + + # Get a non-initial ticket to kpasswd. + ticket = self.get_service_ticket(tgt, + krbtgt_creds, + service='kadmin', + target_name='changepw', + kdc_options='0', + fresh=True) + + set_initial_flag = partial(self.modify_ticket_flag, flag='initial', + value=True) + + checksum_keys = self.get_krbtgt_checksum_key() + return self.modified_ticket(ticket, + modify_fn=set_initial_flag, + checksum_keys=checksum_keys) + + expected_code = KPASSWD_SUCCESS + expected_msg = b'Password changed' + + ticket = get_ticket() + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + creds.update_password(new_password) + ticket = get_ticket() + + # Change the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test that kpasswd rejects requests where the ticket is encrypted with a + # key other than the krbtgt's. + def test_kpasswd_wrong_key(self): + # Create an account for testing. + creds = self._get_creds() + + sname = self.get_kpasswd_sname() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + kdc_options='0') + + # Get a key belonging to the Administrator account. + admin_creds = self.get_admin_creds() + admin_key = self.TicketDecryptionKey_from_creds(admin_creds) + self.assertIsNotNone(admin_key.kvno, + 'a kvno is required to tell the DB ' + 'which key to look up.') + checksum_keys = { + krb5pac.PAC_TYPE_KDC_CHECKSUM: admin_key, + } + + # Re-encrypt the ticket using the Administrator's key. + ticket = self.modified_ticket(ticket, + new_ticket_key=admin_key, + checksum_keys=checksum_keys) + + # Set the sname of the ticket to that of the Administrator account. + admin_sname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=['Administrator']) + ticket.set_sname(admin_sname) + + expected_code = KPASSWD_HARDERROR + expected_msg = b'gensec_update failed - NT_STATUS_LOGON_FAILURE\n' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + def test_kpasswd_wrong_key_service(self): + # Create an account for testing. + creds = self.get_cached_creds(account_type=self.AccountType.COMPUTER, + use_cache=False) + + sname = self.get_kpasswd_sname() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + kdc_options='0') + + # Get a key belonging to our account. + our_key = self.TicketDecryptionKey_from_creds(creds) + self.assertIsNotNone(our_key.kvno, + 'a kvno is required to tell the DB ' + 'which key to look up.') + checksum_keys = { + krb5pac.PAC_TYPE_KDC_CHECKSUM: our_key, + } + + # Re-encrypt the ticket using our key. + ticket = self.modified_ticket(ticket, + new_ticket_key=our_key, + checksum_keys=checksum_keys) + + # Set the sname of the ticket to that of our account. + username = creds.get_username() + sname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=username.split('/')) + ticket.set_sname(sname) + + expected_code = KPASSWD_HARDERROR + expected_msg = b'gensec_update failed - NT_STATUS_LOGON_FAILURE\n' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + # Test that kpasswd rejects requests where the ticket is encrypted with a + # key belonging to a server account other than the krbtgt. + def test_kpasswd_wrong_key_server(self): + # Create an account for testing. + creds = self._get_creds() + + sname = self.get_kpasswd_sname() + + # Get an initial ticket to kpasswd. + ticket = self.get_tgt(creds, sname=sname, + kdc_options='0') + + # Get a key belonging to the DC's account. + dc_creds = self.get_dc_creds() + dc_key = self.TicketDecryptionKey_from_creds(dc_creds) + self.assertIsNotNone(dc_key.kvno, + 'a kvno is required to tell the DB ' + 'which key to look up.') + checksum_keys = { + krb5pac.PAC_TYPE_KDC_CHECKSUM: dc_key, + } + + # Re-encrypt the ticket using the DC's key. + ticket = self.modified_ticket(ticket, + new_ticket_key=dc_key, + checksum_keys=checksum_keys) + + # Set the sname of the ticket to that of the DC's account. + dc_username = dc_creds.get_username() + dc_sname = self.PrincipalName_create(name_type=NT_PRINCIPAL, + names=dc_username.split('/')) + ticket.set_sname(dc_sname) + + expected_code = KPASSWD_HARDERROR + expected_msg = b'gensec_update failed - NT_STATUS_LOGON_FAILURE\n' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(ticket, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + + +if __name__ == '__main__': + global_asn1_print = False + global_hexdump = False + import unittest + unittest.main() diff --git a/python/samba/tests/krb5/raw_testcase.py b/python/samba/tests/krb5/raw_testcase.py index 6cacc3f8fca..00c590a34c0 100644 --- a/python/samba/tests/krb5/raw_testcase.py +++ b/python/samba/tests/krb5/raw_testcase.py @@ -506,6 +506,10 @@ class KerberosCredentials(Credentials): def get_upn(self): return self.upn + def update_password(self, password): + self.set_password(password) + self.set_kvno(self.get_kvno() + 1) + class KerberosTicketCreds: def __init__(self, ticket, session_key, @@ -524,6 +528,10 @@ class KerberosTicketCreds: self.ticket_private = ticket_private self.encpart_private = encpart_private + def set_sname(self, sname): + self.ticket['sname'] = sname + self.sname = sname + class RawKerberosTest(TestCaseInTempDir): """A raw Kerberos Test case.""" diff --git a/python/samba/tests/usage.py b/python/samba/tests/usage.py index 4b12bc29652..037c4ab9faf 100644 --- a/python/samba/tests/usage.py +++ b/python/samba/tests/usage.py @@ -110,6 +110,7 @@ EXCLUDE_USAGE = { 'python/samba/tests/krb5/test_min_domain_uid.py', 'python/samba/tests/krb5/test_idmap_nss.py', 'python/samba/tests/krb5/pac_align_tests.py', + 'python/samba/tests/krb5/kpasswd_tests.py', } EXCLUDE_HELP = { diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index a5a995d92f0..f5885e811b7 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -47,3 +47,29 @@ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_user2user_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_validate_rodc_not_revealed +# +# Kpasswd tests +# +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change_expired_password.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_initial.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_expired_password.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_access.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_no_access.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_only.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_realm_only.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_too_weak.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index a0e7579e140..f2f17dc8577 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -544,3 +544,29 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_logon_info_sid_mismatch_nonexisting ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_requester_sid_mismatch_existing ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_requester_sid_mismatch_nonexisting +# +# Kpasswd tests +# +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change_expired_password.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_initial.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_expired_password.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_access.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_no_access.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_only.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_realm_only.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_too_weak.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/selftest/tests.py b/source4/selftest/tests.py index 9dceb3416ca..3af8e92d7f2 100755 --- a/source4/selftest/tests.py +++ b/source4/selftest/tests.py @@ -1662,6 +1662,10 @@ planoldpythontestsuite( 'ad_dc', 'samba.tests.krb5.pac_align_tests', environ=krb5_environ) +planoldpythontestsuite( + 'ad_dc', + 'samba.tests.krb5.kpasswd_tests', + environ=krb5_environ) for env in [ 'vampire_dc', -- 2.25.1 From 705e7ff46d61338e0529c2ac6ce2245d399d27d5 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 27 May 2022 19:21:06 +1200 Subject: [PATCH 39/68] CVE-2022-2031 s4:kpasswd: Correctly generate error strings The error_data we create already has an explicit length, and should not be zero-terminated, so we omit the trailing null byte. Previously, Heimdal builds would leave a superfluous trailing null byte on error strings, while MIT builds would omit the final character. The two bytes added to the string's length are for the prepended error code. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Removed MIT KDC 1.20-specific knownfails] --- selftest/knownfail_heimdal_kdc | 12 ------------ selftest/knownfail_mit_kdc | 15 --------------- source4/kdc/kpasswd-helper.c | 13 ++++++------- 3 files changed, 6 insertions(+), 34 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index f5885e811b7..5bc37a71125 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -52,24 +52,12 @@ # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change_expired_password.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_initial.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_expired_password.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_access.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_no_access.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_only.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_realm_only.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_too_weak.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index f2f17dc8577..2ddd027c8ea 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -547,26 +547,11 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # # Kpasswd tests # -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_change_expired_password.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_initial.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_expired_password.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_access.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_and_realm_no_access.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_princ_only.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_set_target_realm_only.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_too_weak.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/kpasswd-helper.c b/source4/kdc/kpasswd-helper.c index 995f54825b5..55a2f5b3bf6 100644 --- a/source4/kdc/kpasswd-helper.c +++ b/source4/kdc/kpasswd-helper.c @@ -48,17 +48,16 @@ bool kpasswd_make_error_reply(TALLOC_CTX *mem_ctx, } /* - * The string 's' has two terminating nul-bytes which are also - * reflected by 'slen'. Normally Kerberos doesn't expect that strings - * are nul-terminated, but Heimdal does! + * The string 's' has one terminating nul-byte which is also + * reflected by 'slen'. We subtract it from the length. */ -#ifndef SAMBA4_USES_HEIMDAL - if (slen < 2) { + if (slen < 1) { talloc_free(s); return false; } - slen -= 2; -#endif + slen--; + + /* Two bytes are added to the length to account for the error code. */ if (2 + slen < slen) { talloc_free(s); return false; -- 2.25.1 From 63d6af6ed70a0e9581f851c46c921f1024c7515d Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:48:59 +1200 Subject: [PATCH 40/68] CVE-2022-2031 s4:kpasswd: Don't return AP-REP on failure BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Removed MIT KDC 1.20-specific knownfails] --- selftest/knownfail_mit_kdc | 1 - source4/kdc/kpasswd-service.c | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index 2ddd027c8ea..e37a048105f 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -548,7 +548,6 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # Kpasswd tests # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc diff --git a/source4/kdc/kpasswd-service.c b/source4/kdc/kpasswd-service.c index 061aedc80e5..22e1295c11e 100644 --- a/source4/kdc/kpasswd-service.c +++ b/source4/kdc/kpasswd-service.c @@ -256,6 +256,7 @@ kdc_code kpasswd_process(struct kdc_server *kdc, &kpasswd_dec_reply, &error_string); if (code != 0) { + ap_rep_blob = data_blob_null; error_code = code; goto reply; } @@ -265,6 +266,7 @@ kdc_code kpasswd_process(struct kdc_server *kdc, &kpasswd_dec_reply, &enc_data_blob); if (!NT_STATUS_IS_OK(status)) { + ap_rep_blob = data_blob_null; error_code = KRB5_KPASSWD_HARDERROR; error_string = talloc_asprintf(tmp_ctx, "gensec_wrap failed - %s\n", -- 2.25.1 From 99bbd95a1d6d96b33e9af310e8c0788440e51845 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 27 May 2022 19:29:34 +1200 Subject: [PATCH 41/68] CVE-2022-2031 lib:krb5_wrap: Generate valid error codes in smb_krb5_mk_error() The error code passed in will be an offset from ERROR_TABLE_BASE_krb5, so we need to subtract that before creating the error. Heimdal does this internally, so it isn't needed there. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- lib/krb5_wrap/krb5_samba.c | 2 +- selftest/knownfail_mit_kdc | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/krb5_wrap/krb5_samba.c b/lib/krb5_wrap/krb5_samba.c index 99809ffea27..4321f07ca09 100644 --- a/lib/krb5_wrap/krb5_samba.c +++ b/lib/krb5_wrap/krb5_samba.c @@ -237,7 +237,7 @@ krb5_error_code smb_krb5_mk_error(krb5_context context, return code; } - errpkt.error = error_code; + errpkt.error = error_code - ERROR_TABLE_BASE_krb5; errpkt.text.length = 0; if (e_text != NULL) { diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index e37a048105f..c66608544b6 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -548,9 +548,13 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # Kpasswd tests # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc -- 2.25.1 From 393c18b53ec88e18239b9fa2c1e6ef2009a75ad5 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:49:43 +1200 Subject: [PATCH 42/68] CVE-2022-2031 s4:kpasswd: Return a kpasswd error code in KRB-ERROR If we attempt to return an error code outside of Heimdal's allowed range [KRB5KDC_ERR_NONE, KRB5_ERR_RCSID), it will be replaced with a GENERIC error, and the error text will be set to the meaningless result of krb5_get_error_message(). Avoid this by ensuring the error code is in the correct range. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- selftest/knownfail_heimdal_kdc | 2 -- selftest/knownfail_mit_kdc | 4 ---- source4/kdc/kpasswd-service.c | 2 +- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 5bc37a71125..1063c3dc5b5 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -52,9 +52,7 @@ # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index c66608544b6..e37a048105f 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -548,13 +548,9 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # Kpasswd tests # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_empty.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_seq_number.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/kpasswd-service.c b/source4/kdc/kpasswd-service.c index 22e1295c11e..379ddebf3ad 100644 --- a/source4/kdc/kpasswd-service.c +++ b/source4/kdc/kpasswd-service.c @@ -315,7 +315,7 @@ reply: } code = smb_krb5_mk_error(kdc->smb_krb5_context->krb5_context, - error_code, + KRB5KDC_ERR_NONE + error_code, NULL, /* e_text */ &k_dec_data, NULL, /* client */ -- 2.25.1 From eade23880ec8484530ca19a929bae7c437eafc7e Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:06:31 +1200 Subject: [PATCH 43/68] CVE-2022-2031 gensec_krb5: Add helper function to check if client sent an initial ticket This will be used in the kpasswd service to ensure that the client has an initial ticket to kadmin/changepw, and not a service ticket. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/auth/gensec/gensec_krb5.c | 20 +----- source4/auth/gensec/gensec_krb5_helpers.c | 72 ++++++++++++++++++++++ source4/auth/gensec/gensec_krb5_helpers.h | 32 ++++++++++ source4/auth/gensec/gensec_krb5_internal.h | 47 ++++++++++++++ source4/auth/gensec/wscript_build | 4 ++ 5 files changed, 157 insertions(+), 18 deletions(-) create mode 100644 source4/auth/gensec/gensec_krb5_helpers.c create mode 100644 source4/auth/gensec/gensec_krb5_helpers.h create mode 100644 source4/auth/gensec/gensec_krb5_internal.h diff --git a/source4/auth/gensec/gensec_krb5.c b/source4/auth/gensec/gensec_krb5.c index 7d87b3ac6b9..104e4639c44 100644 --- a/source4/auth/gensec/gensec_krb5.c +++ b/source4/auth/gensec/gensec_krb5.c @@ -44,27 +44,11 @@ #include "../lib/util/asn1.h" #include "auth/kerberos/pac_utils.h" #include "gensec_krb5.h" +#include "gensec_krb5_internal.h" +#include "gensec_krb5_helpers.h" _PUBLIC_ NTSTATUS gensec_krb5_init(TALLOC_CTX *); -enum GENSEC_KRB5_STATE { - GENSEC_KRB5_SERVER_START, - GENSEC_KRB5_CLIENT_START, - GENSEC_KRB5_CLIENT_MUTUAL_AUTH, - GENSEC_KRB5_DONE -}; - -struct gensec_krb5_state { - enum GENSEC_KRB5_STATE state_position; - struct smb_krb5_context *smb_krb5_context; - krb5_auth_context auth_context; - krb5_data enc_ticket; - krb5_keyblock *keyblock; - krb5_ticket *ticket; - bool gssapi; - krb5_flags ap_req_options; -}; - static int gensec_krb5_destroy(struct gensec_krb5_state *gensec_krb5_state) { if (!gensec_krb5_state->smb_krb5_context) { diff --git a/source4/auth/gensec/gensec_krb5_helpers.c b/source4/auth/gensec/gensec_krb5_helpers.c new file mode 100644 index 00000000000..21f2f1e884e --- /dev/null +++ b/source4/auth/gensec/gensec_krb5_helpers.c @@ -0,0 +1,72 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett 2004 + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_internal.h" +#include "gensec_krb5_internal.h" +#include "gensec_krb5_helpers.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" + +static struct gensec_krb5_state *get_private_state(const struct gensec_security *gensec_security) +{ + struct gensec_krb5_state *gensec_krb5_state = NULL; + + if (strcmp(gensec_security->ops->name, "krb5") != 0) { + /* We require that the krb5 mechanism is being used. */ + return NULL; + } + + gensec_krb5_state = talloc_get_type(gensec_security->private_data, + struct gensec_krb5_state); + return gensec_krb5_state; +} + +/* + * Returns 1 if our ticket has the initial flag set, 0 if not, and -1 in case of + * error. + */ +int gensec_krb5_initial_ticket(const struct gensec_security *gensec_security) +{ + struct gensec_krb5_state *gensec_krb5_state = NULL; + + gensec_krb5_state = get_private_state(gensec_security); + if (gensec_krb5_state == NULL) { + return -1; + } + + if (gensec_krb5_state->ticket == NULL) { + /* We don't have a ticket */ + return -1; + } + +#ifdef SAMBA4_USES_HEIMDAL + return gensec_krb5_state->ticket->ticket.flags.initial; +#else /* MIT KERBEROS */ + return (gensec_krb5_state->ticket->enc_part2->flags & TKT_FLG_INITIAL) ? 1 : 0; +#endif /* SAMBA4_USES_HEIMDAL */ +} diff --git a/source4/auth/gensec/gensec_krb5_helpers.h b/source4/auth/gensec/gensec_krb5_helpers.h new file mode 100644 index 00000000000..d7b694dad0c --- /dev/null +++ b/source4/auth/gensec/gensec_krb5_helpers.h @@ -0,0 +1,32 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett 2004 + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +struct gensec_security; + +/* + * Returns 1 if our ticket has the initial flag set, 0 if not, and -1 in case of + * error. + */ +int gensec_krb5_initial_ticket(const struct gensec_security *gensec_security); diff --git a/source4/auth/gensec/gensec_krb5_internal.h b/source4/auth/gensec/gensec_krb5_internal.h new file mode 100644 index 00000000000..0bb796f1b2a --- /dev/null +++ b/source4/auth/gensec/gensec_krb5_internal.h @@ -0,0 +1,47 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett 2004 + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "includes.h" +#include "auth/gensec/gensec.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" + +enum GENSEC_KRB5_STATE { + GENSEC_KRB5_SERVER_START, + GENSEC_KRB5_CLIENT_START, + GENSEC_KRB5_CLIENT_MUTUAL_AUTH, + GENSEC_KRB5_DONE +}; + +struct gensec_krb5_state { + enum GENSEC_KRB5_STATE state_position; + struct smb_krb5_context *smb_krb5_context; + krb5_auth_context auth_context; + krb5_data enc_ticket; + krb5_keyblock *keyblock; + krb5_ticket *ticket; + bool gssapi; + krb5_flags ap_req_options; +}; diff --git a/source4/auth/gensec/wscript_build b/source4/auth/gensec/wscript_build index d14a50ff273..20271f1665b 100644 --- a/source4/auth/gensec/wscript_build +++ b/source4/auth/gensec/wscript_build @@ -18,6 +18,10 @@ bld.SAMBA_MODULE('gensec_krb5', enabled=bld.AD_DC_BUILD_IS_ENABLED() ) +bld.SAMBA_SUBSYSTEM('gensec_krb5_helpers', + source='gensec_krb5_helpers.c', + deps='gensec_krb5', + enabled=bld.AD_DC_BUILD_IS_ENABLED()) bld.SAMBA_MODULE('gensec_gssapi', source='gensec_gssapi.c', -- 2.25.1 From b8d97f5bd5566996a5fb9def4d0ee3fb8b21974b Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:52:41 +1200 Subject: [PATCH 44/68] CVE-2022-2031 s4:kpasswd: Require an initial ticket Ensure that for password changes the client uses an AS-REQ to get the ticket to kpasswd, and not a TGS-REQ. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Removed MIT KDC 1.20-specific knownfails] --- selftest/knownfail_heimdal_kdc | 1 - selftest/knownfail_mit_kdc | 1 - source4/kdc/kpasswd-service-heimdal.c | 17 +++++++++++++++++ source4/kdc/kpasswd-service-mit.c | 17 +++++++++++++++++ source4/kdc/wscript_build | 1 + 5 files changed, 35 insertions(+), 2 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 1063c3dc5b5..7dc915a6099 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -53,7 +53,6 @@ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index e37a048105f..eafa08bfc07 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -549,7 +549,6 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_non_initial.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc diff --git a/source4/kdc/kpasswd-service-heimdal.c b/source4/kdc/kpasswd-service-heimdal.c index c804852c3a7..1a6c2b60d03 100644 --- a/source4/kdc/kpasswd-service-heimdal.c +++ b/source4/kdc/kpasswd-service-heimdal.c @@ -24,6 +24,7 @@ #include "param/param.h" #include "auth/auth.h" #include "auth/gensec/gensec.h" +#include "gensec_krb5_helpers.h" #include "kdc/kdc-server.h" #include "kdc/kpasswd_glue.h" #include "kdc/kpasswd-service.h" @@ -31,6 +32,7 @@ static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, + const struct gensec_security *gensec_security, struct auth_session_info *session_info, DATA_BLOB *password, DATA_BLOB *kpasswd_reply, @@ -42,6 +44,17 @@ static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, const char *reject_string = NULL; struct samr_DomInfo1 *dominfo; bool ok; + int ret; + + /* + * We're doing a password change (rather than a password set), so check + * that we were given an initial ticket. + */ + ret = gensec_krb5_initial_ticket(gensec_security); + if (ret != 1) { + *error_string = "Expected an initial ticket"; + return KRB5_KPASSWD_INITIAL_FLAG_NEEDED; + } status = samdb_kpasswd_change_password(mem_ctx, kdc->task->lp_ctx, @@ -81,6 +94,7 @@ static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, + const struct gensec_security *gensec_security, struct auth_session_info *session_info, DATA_BLOB *decoded_data, DATA_BLOB *kpasswd_reply, @@ -173,6 +187,7 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, free_ChangePasswdDataMS(&chpw); return kpasswd_change_password(kdc, mem_ctx, + gensec_security, session_info, &password, kpasswd_reply, @@ -272,6 +287,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, return kpasswd_change_password(kdc, mem_ctx, + gensec_security, session_info, &password, kpasswd_reply, @@ -280,6 +296,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, case KRB5_KPASSWD_VERS_SETPW: { return kpasswd_set_password(kdc, mem_ctx, + gensec_security, session_info, decoded_data, kpasswd_reply, diff --git a/source4/kdc/kpasswd-service-mit.c b/source4/kdc/kpasswd-service-mit.c index 9c4d2801669..de4c6f3f622 100644 --- a/source4/kdc/kpasswd-service-mit.c +++ b/source4/kdc/kpasswd-service-mit.c @@ -24,6 +24,7 @@ #include "param/param.h" #include "auth/auth.h" #include "auth/gensec/gensec.h" +#include "gensec_krb5_helpers.h" #include "kdc/kdc-server.h" #include "kdc/kpasswd_glue.h" #include "kdc/kpasswd-service.h" @@ -84,6 +85,7 @@ out: static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, + const struct gensec_security *gensec_security, struct auth_session_info *session_info, DATA_BLOB *password, DATA_BLOB *kpasswd_reply, @@ -95,6 +97,17 @@ static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, const char *reject_string = NULL; struct samr_DomInfo1 *dominfo; bool ok; + int ret; + + /* + * We're doing a password change (rather than a password set), so check + * that we were given an initial ticket. + */ + ret = gensec_krb5_initial_ticket(gensec_security); + if (ret != 1) { + *error_string = "Expected an initial ticket"; + return KRB5_KPASSWD_INITIAL_FLAG_NEEDED; + } status = samdb_kpasswd_change_password(mem_ctx, kdc->task->lp_ctx, @@ -134,6 +147,7 @@ static krb5_error_code kpasswd_change_password(struct kdc_server *kdc, static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, + const struct gensec_security *gensec_security, struct auth_session_info *session_info, DATA_BLOB *decoded_data, DATA_BLOB *kpasswd_reply, @@ -250,6 +264,7 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, return kpasswd_change_password(kdc, mem_ctx, + gensec_security, session_info, &password, kpasswd_reply, @@ -350,6 +365,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, return kpasswd_change_password(kdc, mem_ctx, + gensec_security, session_info, &password, kpasswd_reply, @@ -358,6 +374,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, case RFC3244_VERSION: { return kpasswd_set_password(kdc, mem_ctx, + gensec_security, session_info, decoded_data, kpasswd_reply, diff --git a/source4/kdc/wscript_build b/source4/kdc/wscript_build index 26a68e9c37c..c5a80468afe 100644 --- a/source4/kdc/wscript_build +++ b/source4/kdc/wscript_build @@ -85,6 +85,7 @@ bld.SAMBA_SUBSYSTEM('KPASSWD-SERVICE', krb5samba samba_server_gensec KPASSWD_GLUE + gensec_krb5_helpers ''') bld.SAMBA_SUBSYSTEM('KDC-GLUE', -- 2.25.1 From 59d656406f58af649fb20a74c295f840327135b0 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 17:11:49 +1200 Subject: [PATCH 45/68] s4:kpasswd: Restructure code for clarity View with 'git show -b'. Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/kdc/kpasswd-service-heimdal.c | 46 +++++++++++++-------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/source4/kdc/kpasswd-service-heimdal.c b/source4/kdc/kpasswd-service-heimdal.c index 1a6c2b60d03..a0352d1ad35 100644 --- a/source4/kdc/kpasswd-service-heimdal.c +++ b/source4/kdc/kpasswd-service-heimdal.c @@ -160,30 +160,7 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, return 0; } - if (chpw.targname != NULL && chpw.targrealm != NULL) { - code = krb5_build_principal_ext(context, - &target_principal, - strlen(*chpw.targrealm), - *chpw.targrealm, - 0); - if (code != 0) { - free_ChangePasswdDataMS(&chpw); - return kpasswd_make_error_reply(mem_ctx, - KRB5_KPASSWD_MALFORMED, - "Failed to parse principal", - kpasswd_reply); - } - code = copy_PrincipalName(chpw.targname, - &target_principal->name); - if (code != 0) { - free_ChangePasswdDataMS(&chpw); - krb5_free_principal(context, target_principal); - return kpasswd_make_error_reply(mem_ctx, - KRB5_KPASSWD_MALFORMED, - "Failed to parse principal", - kpasswd_reply); - } - } else { + if (chpw.targname == NULL || chpw.targrealm == NULL) { free_ChangePasswdDataMS(&chpw); return kpasswd_change_password(kdc, mem_ctx, @@ -193,7 +170,28 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc, kpasswd_reply, error_string); } + code = krb5_build_principal_ext(context, + &target_principal, + strlen(*chpw.targrealm), + *chpw.targrealm, + 0); + if (code != 0) { + free_ChangePasswdDataMS(&chpw); + return kpasswd_make_error_reply(mem_ctx, + KRB5_KPASSWD_MALFORMED, + "Failed to parse principal", + kpasswd_reply); + } + code = copy_PrincipalName(chpw.targname, + &target_principal->name); free_ChangePasswdDataMS(&chpw); + if (code != 0) { + krb5_free_principal(context, target_principal); + return kpasswd_make_error_reply(mem_ctx, + KRB5_KPASSWD_MALFORMED, + "Failed to parse principal", + kpasswd_reply); + } if (target_principal->name.name_string.len >= 2) { is_service_principal = true; -- 2.25.1 From 3761a6e87131a27b6687eb387b35069cba0119d3 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 24 May 2022 10:17:00 +0200 Subject: [PATCH 46/68] CVE-2022-2031 testprogs: Fix auth with smbclient and krb5 ccache BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Andreas Schneider Reviewed-by: Joseph Sutton --- testprogs/blackbox/test_kpasswd_heimdal.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testprogs/blackbox/test_kpasswd_heimdal.sh b/testprogs/blackbox/test_kpasswd_heimdal.sh index 43f38b09de2..a73c6665a18 100755 --- a/testprogs/blackbox/test_kpasswd_heimdal.sh +++ b/testprogs/blackbox/test_kpasswd_heimdal.sh @@ -71,7 +71,7 @@ testit "kinit with user password" \ do_kinit $TEST_PRINCIPAL $TEST_PASSWORD || failed=`expr $failed + 1` test_smbclient "Test login with user kerberos ccache" \ - "ls" "$SMB_UNC" --use-kerberos=required || failed=`expr $failed + 1` + "ls" "$SMB_UNC" --use-krb5-ccache=${KRB5CCNAME} || failed=`expr $failed + 1` testit "change user password with 'samba-tool user password' (unforced)" \ $VALGRIND $PYTHON $samba_tool user password -W$DOMAIN -U$TEST_USERNAME%$TEST_PASSWORD --use-kerberos=off --newpassword=$TEST_PASSWORD_NEW || failed=`expr $failed + 1` @@ -84,7 +84,7 @@ testit "kinit with user password" \ do_kinit $TEST_PRINCIPAL $TEST_PASSWORD || failed=`expr $failed + 1` test_smbclient "Test login with user kerberos ccache" \ - "ls" "$SMB_UNC" --use-kerberos=required || failed=`expr $failed + 1` + "ls" "$SMB_UNC" --use-krb5-ccache=${KRB5CCNAME} || failed=`expr $failed + 1` ########################################################### ### check that a short password is rejected -- 2.25.1 From 4aafa72991cb59426669725733251d45f912cccb Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Thu, 19 May 2022 16:35:28 +0200 Subject: [PATCH 47/68] CVE-2022-2031 testprogs: Add kadmin/changepw canonicalization test with MIT kpasswd BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Andreas Schneider Reviewed-by: Joseph Sutton --- selftest/knownfail.d/kadmin_changepw | 1 + testprogs/blackbox/test_kpasswd_heimdal.sh | 35 +++++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 selftest/knownfail.d/kadmin_changepw diff --git a/selftest/knownfail.d/kadmin_changepw b/selftest/knownfail.d/kadmin_changepw new file mode 100644 index 00000000000..97c14793ea5 --- /dev/null +++ b/selftest/knownfail.d/kadmin_changepw @@ -0,0 +1 @@ +^samba4.blackbox.kpasswd.MIT kpasswd.change.user.password diff --git a/testprogs/blackbox/test_kpasswd_heimdal.sh b/testprogs/blackbox/test_kpasswd_heimdal.sh index a73c6665a18..698044a3fd3 100755 --- a/testprogs/blackbox/test_kpasswd_heimdal.sh +++ b/testprogs/blackbox/test_kpasswd_heimdal.sh @@ -7,7 +7,7 @@ if [ $# -lt 6 ]; then cat < "${PREFIX}/tmpkpasswdscript" < "${KRB5_CONFIG}" + testit "MIT kpasswd change user password" \ + "${texpect}" "${PREFIX}/tmpkpasswdscript" "${mit_kpasswd}" \ + "${TEST_PRINCIPAL}" || + failed=$((failed + 1)) + KRB5_CONFIG="${SAVE_KRB5_CONFIG}" + export KRB5_CONFIG +fi + +TEST_PASSWORD="${TEST_PASSWORD_NEW}" +TEST_PASSWORD_NEW="testPaSS@03force%" + ########################################################### ### Force password change at login ########################################################### -- 2.25.1 From ada799129ebc19c51a014dcf05cd17ea86b73f5b Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 24 May 2022 09:54:18 +0200 Subject: [PATCH 48/68] CVE-2022-2031 s4:kdc: Implement is_kadmin_changepw() helper function BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Andreas Schneider Reviewed-by: Joseph Sutton [jsutton@samba.org Adapted entry to entry_ex->entry] --- source4/kdc/db-glue.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 4094ad42727..9cdc73393fa 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -880,6 +880,14 @@ static int principal_comp_strcmp(krb5_context context, component, string, false); } +static bool is_kadmin_changepw(krb5_context context, + krb5_const_principal principal) +{ + return krb5_princ_size(context, principal) == 2 && + (principal_comp_strcmp(context, principal, 0, "kadmin") == 0) && + (principal_comp_strcmp(context, principal, 1, "changepw") == 0); +} + /* * Construct an hdb_entry from a directory entry. */ @@ -1182,11 +1190,9 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, * 'change password', as otherwise we could get into * trouble, and not enforce the password expirty. * Instead, only do it when request is for the kpasswd service */ - if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER - && krb5_princ_size(context, principal) == 2 - && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0) - && (principal_comp_strcmp(context, principal, 1, "changepw") == 0) - && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) { + if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && + is_kadmin_changepw(context, principal) && + lpcfg_is_my_domain_or_realm(lp_ctx, realm)) { entry_ex->entry.flags.change_pw = 1; } -- 2.25.1 From 9022a69aebfca3af5a5ef432ff392df69490d961 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:56:01 +1200 Subject: [PATCH 49/68] CVE-2022-2031 s4:kdc: Split out a samba_kdc_get_entry_principal() function BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Adapted entry to entry_ex->entry] --- source4/kdc/db-glue.c | 192 +++++++++++++++++++++++------------------- 1 file changed, 107 insertions(+), 85 deletions(-) diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 9cdc73393fa..91b9699fa01 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -888,6 +888,101 @@ static bool is_kadmin_changepw(krb5_context context, (principal_comp_strcmp(context, principal, 1, "changepw") == 0); } +static krb5_error_code samba_kdc_get_entry_principal( + krb5_context context, + struct samba_kdc_db_context *kdc_db_ctx, + const char *samAccountName, + enum samba_kdc_ent_type ent_type, + unsigned flags, + krb5_const_principal in_princ, + krb5_principal *out_princ) +{ + struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx; + krb5_error_code ret = 0; + + /* + * If we are set to canonicalize, we get back the fixed UPPER + * case realm, and the real username (ie matching LDAP + * samAccountName) + * + * Otherwise, if we are set to enterprise, we + * get back the whole principal as-sent + * + * Finally, if we are not set to canonicalize, we get back the + * fixed UPPER case realm, but the as-sent username + */ + + if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) { + if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) { + /* + * When requested to do so, ensure that the + * both realm values in the principal are set + * to the upper case, canonical realm + */ + ret = smb_krb5_make_principal(context, out_princ, + lpcfg_realm(lp_ctx), "krbtgt", + lpcfg_realm(lp_ctx), NULL); + if (ret) { + return ret; + } + smb_krb5_principal_set_type(context, *out_princ, KRB5_NT_SRV_INST); + } else { + ret = krb5_copy_principal(context, in_princ, out_princ); + if (ret) { + return ret; + } + /* + * this appears to be required regardless of + * the canonicalize flag from the client + */ + ret = smb_krb5_principal_set_realm(context, *out_princ, lpcfg_realm(lp_ctx)); + if (ret) { + return ret; + } + } + + } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL) { + ret = smb_krb5_make_principal(context, out_princ, lpcfg_realm(lp_ctx), samAccountName, NULL); + if (ret) { + return ret; + } + } else if ((flags & SDB_F_FORCE_CANON) || + ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ))) { + /* + * SDB_F_CANON maps from the canonicalize flag in the + * packet, and has a different meaning between AS-REQ + * and TGS-REQ. We only change the principal in the AS-REQ case + * + * The SDB_F_FORCE_CANON if for new MIT KDC code that wants + * the canonical name in all lookups, and takes care to + * canonicalize only when appropriate. + */ + ret = smb_krb5_make_principal(context, out_princ, lpcfg_realm(lp_ctx), samAccountName, NULL); + if (ret) { + return ret; + } + } else { + ret = krb5_copy_principal(context, in_princ, out_princ); + if (ret) { + return ret; + } + + /* While we have copied the client principal, tests + * show that Win2k3 returns the 'corrected' realm, not + * the client-specified realm. This code attempts to + * replace the client principal's realm with the one + * we determine from our records */ + + /* this has to be with malloc() */ + ret = smb_krb5_principal_set_realm(context, *out_princ, lpcfg_realm(lp_ctx)); + if (ret) { + return ret; + } + } + + return 0; +} + /* * Construct an hdb_entry from a directory entry. */ @@ -978,93 +1073,8 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, userAccountControl |= msDS_User_Account_Control_Computed; } - /* - * If we are set to canonicalize, we get back the fixed UPPER - * case realm, and the real username (ie matching LDAP - * samAccountName) - * - * Otherwise, if we are set to enterprise, we - * get back the whole principal as-sent - * - * Finally, if we are not set to canonicalize, we get back the - * fixed UPPER case realm, but the as-sent username - */ - if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) { p->is_krbtgt = true; - - if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) { - /* - * When requested to do so, ensure that the - * both realm values in the principal are set - * to the upper case, canonical realm - */ - ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, - lpcfg_realm(lp_ctx), "krbtgt", - lpcfg_realm(lp_ctx), NULL); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST); - } else { - ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - /* - * this appears to be required regardless of - * the canonicalize flag from the client - */ - ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx)); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - } - - } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) { - ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - } else if ((flags & SDB_F_FORCE_CANON) || - ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ))) { - /* - * SDB_F_CANON maps from the canonicalize flag in the - * packet, and has a different meaning between AS-REQ - * and TGS-REQ. We only change the principal in the AS-REQ case - * - * The SDB_F_FORCE_CANON if for new MIT KDC code that wants - * the canonical name in all lookups, and takes care to - * canonicalize only when appropriate. - */ - ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - } else { - ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal); - if (ret) { - krb5_clear_error_message(context); - goto out; - } - - /* While we have copied the client principal, tests - * show that Win2k3 returns the 'corrected' realm, not - * the client-specified realm. This code attempts to - * replace the client principal's realm with the one - * we determine from our records */ - - /* this has to be with malloc() */ - ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx)); - if (ret) { - krb5_clear_error_message(context); - goto out; - } } /* First try and figure out the flags based on the userAccountControl */ @@ -1257,6 +1267,18 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, } } + ret = samba_kdc_get_entry_principal(context, + kdc_db_ctx, + samAccountName, + ent_type, + flags, + principal, + &entry_ex->entry.principal); + if (ret != 0) { + krb5_clear_error_message(context); + goto out; + } + entry_ex->entry.valid_start = NULL; entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life)); -- 2.25.1 From 2b63f021e5970386fc4e4923f32b14008e6aac0e Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 25 May 2022 17:19:58 +1200 Subject: [PATCH 50/68] CVE-2022-2031 s4:kdc: Refactor samba_kdc_get_entry_principal() This eliminates some duplicate branches. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Pair-Programmed-With: Andreas Schneider Reviewed-by: Andreas Schneider --- source4/kdc/db-glue.c | 116 ++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 61 deletions(-) diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 91b9699fa01..10f7d850b11 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -898,7 +898,8 @@ static krb5_error_code samba_kdc_get_entry_principal( krb5_principal *out_princ) { struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx; - krb5_error_code ret = 0; + krb5_error_code code = 0; + bool canon = flags & (SDB_F_CANON|SDB_F_FORCE_CANON); /* * If we are set to canonicalize, we get back the fixed UPPER @@ -912,75 +913,68 @@ static krb5_error_code samba_kdc_get_entry_principal( * fixed UPPER case realm, but the as-sent username */ - if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) { - if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) { - /* - * When requested to do so, ensure that the - * both realm values in the principal are set - * to the upper case, canonical realm - */ - ret = smb_krb5_make_principal(context, out_princ, - lpcfg_realm(lp_ctx), "krbtgt", - lpcfg_realm(lp_ctx), NULL); - if (ret) { - return ret; - } - smb_krb5_principal_set_type(context, *out_princ, KRB5_NT_SRV_INST); - } else { - ret = krb5_copy_principal(context, in_princ, out_princ); - if (ret) { - return ret; - } - /* - * this appears to be required regardless of - * the canonicalize flag from the client - */ - ret = smb_krb5_principal_set_realm(context, *out_princ, lpcfg_realm(lp_ctx)); - if (ret) { - return ret; - } - } + if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) { + /* + * When requested to do so, ensure that the + * both realm values in the principal are set + * to the upper case, canonical realm + */ + code = smb_krb5_make_principal(context, + out_princ, + lpcfg_realm(lp_ctx), + "krbtgt", + lpcfg_realm(lp_ctx), + NULL); + if (code != 0) { + return code; + } + smb_krb5_principal_set_type(context, + *out_princ, + KRB5_NT_SRV_INST); - } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL) { - ret = smb_krb5_make_principal(context, out_princ, lpcfg_realm(lp_ctx), samAccountName, NULL); - if (ret) { - return ret; - } - } else if ((flags & SDB_F_FORCE_CANON) || - ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ))) { + return 0; + } + + if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) || + (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) { /* * SDB_F_CANON maps from the canonicalize flag in the * packet, and has a different meaning between AS-REQ - * and TGS-REQ. We only change the principal in the AS-REQ case + * and TGS-REQ. We only change the principal in the + * AS-REQ case. * - * The SDB_F_FORCE_CANON if for new MIT KDC code that wants - * the canonical name in all lookups, and takes care to - * canonicalize only when appropriate. + * The SDB_F_FORCE_CANON if for new MIT KDC code that + * wants the canonical name in all lookups, and takes + * care to canonicalize only when appropriate. */ - ret = smb_krb5_make_principal(context, out_princ, lpcfg_realm(lp_ctx), samAccountName, NULL); - if (ret) { - return ret; - } - } else { - ret = krb5_copy_principal(context, in_princ, out_princ); - if (ret) { - return ret; - } - - /* While we have copied the client principal, tests - * show that Win2k3 returns the 'corrected' realm, not - * the client-specified realm. This code attempts to - * replace the client principal's realm with the one - * we determine from our records */ + code = smb_krb5_make_principal(context, + out_princ, + lpcfg_realm(lp_ctx), + samAccountName, + NULL); + return code; + } - /* this has to be with malloc() */ - ret = smb_krb5_principal_set_realm(context, *out_princ, lpcfg_realm(lp_ctx)); - if (ret) { - return ret; - } + /* + * For a krbtgt entry, this appears to be required regardless of the + * canonicalize flag from the client. + */ + code = krb5_copy_principal(context, in_princ, out_princ); + if (code != 0) { + return code; } - return 0; + /* + * While we have copied the client principal, tests show that Win2k3 + * returns the 'corrected' realm, not the client-specified realm. This + * code attempts to replace the client principal's realm with the one + * we determine from our records + */ + code = smb_krb5_principal_set_realm(context, + *out_princ, + lpcfg_realm(lp_ctx)); + + return code; } /* -- 2.25.1 From fb7391ca60e4c86bcf79d25547476edf81278c1c Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 18 May 2022 16:56:01 +1200 Subject: [PATCH 51/68] CVE-2022-2031 s4:kdc: Fix canonicalisation of kadmin/changepw principal Since this principal goes through the samba_kdc_fetch_server() path, setting the canonicalisation flag would cause the principal to be replaced with the sAMAccountName; this meant requests to kadmin/changepw@REALM would result in a ticket to krbtgt@REALM. Now we properly handle canonicalisation for the kadmin/changepw principal. View with 'git show -b'. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Pair-Programmed-With: Andreas Schneider Signed-off-by: Andreas Schneider Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Adapted entry to entry_ex->entry; removed MIT KDC 1.20-specific knownfails] --- selftest/knownfail.d/kadmin_changepw | 1 - selftest/knownfail_heimdal_kdc | 2 - source4/kdc/db-glue.c | 84 +++++++++++++++------------- 3 files changed, 46 insertions(+), 41 deletions(-) delete mode 100644 selftest/knownfail.d/kadmin_changepw diff --git a/selftest/knownfail.d/kadmin_changepw b/selftest/knownfail.d/kadmin_changepw deleted file mode 100644 index 97c14793ea5..00000000000 --- a/selftest/knownfail.d/kadmin_changepw +++ /dev/null @@ -1 +0,0 @@ -^samba4.blackbox.kpasswd.MIT kpasswd.change.user.password diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 7dc915a6099..29c350d333b 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -50,8 +50,6 @@ # # Kpasswd tests # -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 10f7d850b11..63eb73a95cd 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -894,6 +894,7 @@ static krb5_error_code samba_kdc_get_entry_principal( const char *samAccountName, enum samba_kdc_ent_type ent_type, unsigned flags, + bool is_kadmin_changepw, krb5_const_principal in_princ, krb5_principal *out_princ) { @@ -913,46 +914,52 @@ static krb5_error_code samba_kdc_get_entry_principal( * fixed UPPER case realm, but the as-sent username */ - if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) { - /* - * When requested to do so, ensure that the - * both realm values in the principal are set - * to the upper case, canonical realm - */ - code = smb_krb5_make_principal(context, - out_princ, - lpcfg_realm(lp_ctx), - "krbtgt", - lpcfg_realm(lp_ctx), - NULL); - if (code != 0) { - return code; - } - smb_krb5_principal_set_type(context, - *out_princ, - KRB5_NT_SRV_INST); + /* + * We need to ensure that the kadmin/changepw principal isn't able to + * issue krbtgt tickets, even if canonicalization is turned on. + */ + if (!is_kadmin_changepw) { + if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) { + /* + * When requested to do so, ensure that the + * both realm values in the principal are set + * to the upper case, canonical realm + */ + code = smb_krb5_make_principal(context, + out_princ, + lpcfg_realm(lp_ctx), + "krbtgt", + lpcfg_realm(lp_ctx), + NULL); + if (code != 0) { + return code; + } + smb_krb5_principal_set_type(context, + *out_princ, + KRB5_NT_SRV_INST); - return 0; - } + return 0; + } - if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) || - (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) { - /* - * SDB_F_CANON maps from the canonicalize flag in the - * packet, and has a different meaning between AS-REQ - * and TGS-REQ. We only change the principal in the - * AS-REQ case. - * - * The SDB_F_FORCE_CANON if for new MIT KDC code that - * wants the canonical name in all lookups, and takes - * care to canonicalize only when appropriate. - */ - code = smb_krb5_make_principal(context, - out_princ, - lpcfg_realm(lp_ctx), - samAccountName, - NULL); - return code; + if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) || + (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) { + /* + * SDB_F_CANON maps from the canonicalize flag in the + * packet, and has a different meaning between AS-REQ + * and TGS-REQ. We only change the principal in the + * AS-REQ case. + * + * The SDB_F_FORCE_CANON if for new MIT KDC code that + * wants the canonical name in all lookups, and takes + * care to canonicalize only when appropriate. + */ + code = smb_krb5_make_principal(context, + out_princ, + lpcfg_realm(lp_ctx), + samAccountName, + NULL); + return code; + } } /* @@ -1266,6 +1273,7 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, samAccountName, ent_type, flags, + entry_ex->entry.flags.change_pw, principal, &entry_ex->entry.principal); if (ret != 0) { -- 2.25.1 From f70ada5eb45baf192f72e9df11327dea5a49fa36 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 17:53:49 +1200 Subject: [PATCH 52/68] CVE-2022-2031 s4:kdc: Limit kpasswd ticket lifetime to two minutes or less This matches the behaviour of Windows. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Adapted entry to entry_ex->entry; included samba_kdc.h header file] --- selftest/knownfail_heimdal_kdc | 1 - selftest/knownfail_mit_kdc | 1 - source4/kdc/db-glue.c | 5 +++++ source4/kdc/mit-kdb/kdb_samba_principals.c | 2 +- source4/kdc/samba_kdc.h | 2 ++ 5 files changed, 8 insertions(+), 3 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 29c350d333b..84f265b312b 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -51,7 +51,6 @@ # Kpasswd tests # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index eafa08bfc07..13dd806aeb1 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -549,7 +549,6 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_lifetime.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index 63eb73a95cd..a936bd1fa83 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -1298,6 +1298,11 @@ static krb5_error_code samba_kdc_message2entry(krb5_context context, kdc_db_ctx->policy.usr_tkt_lifetime); } + if (entry_ex->entry.flags.change_pw) { + /* Limit lifetime of kpasswd tickets to two minutes or less. */ + *entry_ex->entry.max_life = MIN(*entry_ex->entry.max_life, CHANGEPW_LIFETIME); + } + entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life)); if (entry_ex->entry.max_renew == NULL) { ret = ENOMEM; diff --git a/source4/kdc/mit-kdb/kdb_samba_principals.c b/source4/kdc/mit-kdb/kdb_samba_principals.c index 3917b9824c6..da21251179b 100644 --- a/source4/kdc/mit-kdb/kdb_samba_principals.c +++ b/source4/kdc/mit-kdb/kdb_samba_principals.c @@ -27,6 +27,7 @@ #include #include +#include "kdc/samba_kdc.h" #include "kdc/mit_samba.h" #include "kdb_samba.h" @@ -34,7 +35,6 @@ #define DBGC_CLASS DBGC_KERBEROS #define ADMIN_LIFETIME 60*60*3 /* 3 hours */ -#define CHANGEPW_LIFETIME 60*5 /* 5 minutes */ krb5_error_code ks_get_principal(krb5_context context, krb5_const_principal principal, diff --git a/source4/kdc/samba_kdc.h b/source4/kdc/samba_kdc.h index 9b16fcc3b92..8339ba0b990 100644 --- a/source4/kdc/samba_kdc.h +++ b/source4/kdc/samba_kdc.h @@ -66,4 +66,6 @@ struct samba_kdc_entry { extern struct hdb_method hdb_samba4_interface; +#define CHANGEPW_LIFETIME 60*2 /* 2 minutes */ + #endif /* _SAMBA_KDC_H_ */ -- 2.25.1 From b77fb6e636ce46f1f62cf5b71efd8dd3dd6fdbdb Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 22 Jun 2022 20:01:12 +1200 Subject: [PATCH 53/68] CVE-2022-2031 third_party/heimdal: Add function to get current KDC time This allows the plugin to check the endtime of a ticket against the KDC's current time, to see if the ticket will expire in the next two minutes. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton --- third_party/heimdal/kdc/libkdc-exports.def | 1 + third_party/heimdal/kdc/process.c | 6 ++++++ third_party/heimdal/kdc/version-script.map | 1 + 3 files changed, 8 insertions(+) diff --git a/third_party/heimdal/kdc/libkdc-exports.def b/third_party/heimdal/kdc/libkdc-exports.def index 2c4564bcadc..fc4fb812a77 100644 --- a/third_party/heimdal/kdc/libkdc-exports.def +++ b/third_party/heimdal/kdc/libkdc-exports.def @@ -10,6 +10,7 @@ EXPORTS kdc_validate_token krb5_kdc_plugin_init krb5_kdc_get_config + krb5_kdc_get_time krb5_kdc_pkinit_config krb5_kdc_set_dbinfo krb5_kdc_process_krb5_request diff --git a/third_party/heimdal/kdc/process.c b/third_party/heimdal/kdc/process.c index cf8ab060ec9..98a405e17d9 100644 --- a/third_party/heimdal/kdc/process.c +++ b/third_party/heimdal/kdc/process.c @@ -216,6 +216,12 @@ krb5_kdc_update_time(struct timeval *tv) _kdc_now = *tv; } +KDC_LIB_FUNCTION struct timeval KDC_LIB_CALL +krb5_kdc_get_time(void) +{ + return _kdc_now; +} + #define EXTEND_REQUEST_T(LHS, RHS) do { \ RHS = realloc(LHS, sizeof(*RHS)); \ diff --git a/third_party/heimdal/kdc/version-script.map b/third_party/heimdal/kdc/version-script.map index 72a21e62950..55dc91e74be 100644 --- a/third_party/heimdal/kdc/version-script.map +++ b/third_party/heimdal/kdc/version-script.map @@ -13,6 +13,7 @@ HEIMDAL_KDC_1.0 { kdc_validate_token; krb5_kdc_plugin_init; krb5_kdc_get_config; + krb5_kdc_get_time; krb5_kdc_pkinit_config; krb5_kdc_set_dbinfo; krb5_kdc_process_krb5_request; -- 2.25.1 From 90e53b8eae98c6b8ae0982a84bf87c329ab8f2a4 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Mon, 30 May 2022 19:18:17 +1200 Subject: [PATCH 54/68] CVE-2022-2031 s4:kdc: Reject tickets during the last two minutes of their life For Heimdal, this now matches the behaviour of Windows. The object of this requirement is to ensure we don't allow kpasswd tickets, not having a lifetime of more than two minutes, to be passed off as TGTs. An existing requirement for TGTs to contain a REQUESTER_SID PAC buffer suffices to prevent kpasswd ticket misuse, so this is just an additional precaution on top. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- selftest/knownfail_heimdal_kdc | 1 - source4/kdc/wdc-samba4.c | 26 ++++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 84f265b312b..6148467e030 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -51,7 +51,6 @@ # Kpasswd tests # ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/wdc-samba4.c b/source4/kdc/wdc-samba4.c index 7f99233440e..ae0dc22fd49 100644 --- a/source4/kdc/wdc-samba4.c +++ b/source4/kdc/wdc-samba4.c @@ -772,6 +772,32 @@ static krb5_error_code samba_wdc_reget_pac(void *priv, astgs_request_t r, krbtgt = &signing_krbtgt_hdb; } } + } else if (!krbtgt_skdc_entry->is_trust) { + /* + * We expect to have received a TGT, so check that we haven't + * been given a kpasswd ticket instead. We don't need to do this + * check for an incoming trust, as they use a different secret + * and can't be confused with a normal TGT. + */ + krb5_ticket *tgt = kdc_request_get_ticket(r); + + struct timeval now = krb5_kdc_get_time(); + + /* + * Check if the ticket is in the last two minutes of its + * life. + */ + KerberosTime lifetime = rk_time_sub(tgt->ticket.endtime, now.tv_sec); + if (lifetime <= CHANGEPW_LIFETIME) { + /* + * This ticket has at most two minutes left to live. It + * may be a kpasswd ticket rather than a TGT, so don't + * accept it. + */ + kdc_audit_addreason((kdc_request_t)r, + "Ticket is not a ticket-granting ticket"); + return KRB5KRB_AP_ERR_TKT_EXPIRED; + } } ret = samba_wdc_reget_pac2(context, -- 2.25.1 From 8d8ffbfc7b567622c5682866bfec650583d026f2 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 24 May 2022 17:52:05 +1200 Subject: [PATCH 55/68] CVE-2022-32744 s4:kdc: Don't allow HDB keytab iteration A fallback in krb5_rd_req_ctx() means that Samba's kpasswd service will try many inappropriate keys to decrypt the ticket supplied to it. For example, it will accept a ticket encrypted with the Administrator's key, when it should rather accept only tickets encrypted with the krbtgt's key (and not an RODC krbtgt). To fix this, declare the HDB keytab using the HDBGET ops, which do not support iteration. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- selftest/knownfail_heimdal_kdc | 1 - source4/kdc/kdc-heimdal.c | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 6148467e030..fb6ac228c54 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -50,7 +50,6 @@ # # Kpasswd tests # -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_from_rodc.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/kdc-heimdal.c b/source4/kdc/kdc-heimdal.c index 0d2a410fc3b..542986c5ad3 100644 --- a/source4/kdc/kdc-heimdal.c +++ b/source4/kdc/kdc-heimdal.c @@ -463,7 +463,7 @@ static void kdc_post_fork(struct task_server *task, struct process_details *pd) return; } - kdc->keytab_name = talloc_asprintf(kdc, "HDB:samba4:&%p", kdc->base_ctx); + kdc->keytab_name = talloc_asprintf(kdc, "HDBGET:samba4:&%p", kdc->base_ctx); if (kdc->keytab_name == NULL) { task_server_terminate(task, "kdc: Failed to set keytab name", @@ -471,7 +471,7 @@ static void kdc_post_fork(struct task_server *task, struct process_details *pd) return; } - ret = krb5_kt_register(kdc->smb_krb5_context->krb5_context, &hdb_kt_ops); + ret = krb5_kt_register(kdc->smb_krb5_context->krb5_context, &hdb_get_kt_ops); if(ret) { task_server_terminate(task, "kdc: failed to register keytab plugin", true); return; -- 2.25.1 From 1f54e16cf1d5a1f113b88ae938c4752c630eb1d0 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Tue, 14 Jun 2022 15:23:55 +1200 Subject: [PATCH 56/68] CVE-2022-2031 tests/krb5: Test truncated forms of server principals We should not be able to use krb@REALM instead of krbtgt@REALM. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- python/samba/tests/krb5/as_req_tests.py | 30 ++++++++++++++++++++++--- selftest/knownfail_heimdal_kdc | 4 ++++ selftest/knownfail_mit_kdc | 4 ++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/python/samba/tests/krb5/as_req_tests.py b/python/samba/tests/krb5/as_req_tests.py index b52937530e6..6a573947067 100755 --- a/python/samba/tests/krb5/as_req_tests.py +++ b/python/samba/tests/krb5/as_req_tests.py @@ -28,6 +28,7 @@ import samba.tests.krb5.kcrypto as kcrypto import samba.tests.krb5.rfc4120_pyasn1 as krb5_asn1 from samba.tests.krb5.rfc4120_constants import ( KDC_ERR_C_PRINCIPAL_UNKNOWN, + KDC_ERR_S_PRINCIPAL_UNKNOWN, KDC_ERR_ETYPE_NOSUPP, KDC_ERR_PREAUTH_REQUIRED, KU_PA_ENC_TIMESTAMP, @@ -43,7 +44,7 @@ global_hexdump = False class AsReqBaseTest(KDCBaseTest): def _run_as_req_enc_timestamp(self, client_creds, client_account=None, - expected_cname=None, + expected_cname=None, sname=None, name_type=NT_PRINCIPAL, etypes=None, expected_error=None, expect_edata=None, kdc_options=None): @@ -59,8 +60,9 @@ class AsReqBaseTest(KDCBaseTest): cname = self.PrincipalName_create(name_type=name_type, names=client_account.split('/')) - sname = self.PrincipalName_create(name_type=NT_SRV_INST, - names=[krbtgt_account, realm]) + if sname is None: + sname = self.PrincipalName_create(name_type=NT_SRV_INST, + names=[krbtgt_account, realm]) expected_crealm = realm if expected_cname is None: @@ -492,6 +494,28 @@ class AsReqKerberosTests(AsReqBaseTest): name_type=NT_ENTERPRISE_PRINCIPAL, kdc_options=0) + # Ensure we can't use truncated well-known principals such as krb@REALM + # instead of krbtgt@REALM. + def test_krbtgt_wrong_principal(self): + client_creds = self.get_client_creds() + + krbtgt_creds = self.get_krbtgt_creds() + + krbtgt_account = krbtgt_creds.get_username() + realm = krbtgt_creds.get_realm() + + # Truncate the name of the krbtgt principal. + krbtgt_account = krbtgt_account[:3] + + wrong_krbtgt_princ = self.PrincipalName_create( + name_type=NT_SRV_INST, + names=[krbtgt_account, realm]) + + self._run_as_req_enc_timestamp( + client_creds, + sname=wrong_krbtgt_princ, + expected_error=KDC_ERR_S_PRINCIPAL_UNKNOWN) + if __name__ == "__main__": global_asn1_print = False diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index fb6ac228c54..26fc210c6f5 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -53,3 +53,7 @@ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc +# +# AS-REQ tests +# +^samba.tests.krb5.as_req_tests.samba.tests.krb5.as_req_tests.AsReqKerberosTests.test_krbtgt_wrong_principal\( diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index 13dd806aeb1..8bf0b88550e 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -552,3 +552,7 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc +# +# AS-REQ tests +# +^samba.tests.krb5.as_req_tests.samba.tests.krb5.as_req_tests.AsReqKerberosTests.test_krbtgt_wrong_principal\( -- 2.25.1 From 0cb4100d16d567f05669c192d6a20dbf5b9bbe98 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 25 May 2022 20:00:55 +1200 Subject: [PATCH 57/68] CVE-2022-2031 s4:kdc: Don't use strncmp to compare principal components We would only compare the first 'n' characters, where 'n' is the length of the principal component string, so 'k@REALM' would erroneously be considered equal to 'krbtgt@REALM'. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- selftest/knownfail_heimdal_kdc | 4 ---- selftest/knownfail_mit_kdc | 4 ---- source4/kdc/db-glue.c | 27 ++++++++++++++++++++++----- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 26fc210c6f5..fb6ac228c54 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -53,7 +53,3 @@ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc -# -# AS-REQ tests -# -^samba.tests.krb5.as_req_tests.samba.tests.krb5.as_req_tests.AsReqKerberosTests.test_krbtgt_wrong_principal\( diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index 8bf0b88550e..13dd806aeb1 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -552,7 +552,3 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc -# -# AS-REQ tests -# -^samba.tests.krb5.as_req_tests.samba.tests.krb5.as_req_tests.AsReqKerberosTests.test_krbtgt_wrong_principal\( diff --git a/source4/kdc/db-glue.c b/source4/kdc/db-glue.c index a936bd1fa83..231b30b623f 100644 --- a/source4/kdc/db-glue.c +++ b/source4/kdc/db-glue.c @@ -833,15 +833,19 @@ static int principal_comp_strcmp_int(krb5_context context, bool do_strcasecmp) { const char *p; - size_t len; #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) p = krb5_principal_get_comp_string(context, principal, component); if (p == NULL) { return -1; } - len = strlen(p); + if (do_strcasecmp) { + return strcasecmp(p, string); + } else { + return strcmp(p, string); + } #else + size_t len; krb5_data *d; if (component >= krb5_princ_size(context, principal)) { return -1; @@ -853,13 +857,26 @@ static int principal_comp_strcmp_int(krb5_context context, } p = d->data; - len = d->length; -#endif + + len = strlen(string); + + /* + * We explicitly return -1 or 1. Subtracting of the two lengths might + * give the wrong result if the result overflows or loses data when + * narrowed to int. + */ + if (d->length < len) { + return -1; + } else if (d->length > len) { + return 1; + } + if (do_strcasecmp) { return strncasecmp(p, string, len); } else { - return strncmp(p, string, len); + return memcmp(p, string, len); } +#endif } static int principal_comp_strcasecmp(krb5_context context, -- 2.25.1 From d03021791b8b51f45bfa9007a6b937f5eeba3d8a Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 26 May 2022 16:36:30 +1200 Subject: [PATCH 58/68] CVE-2022-32744 s4:kdc: Rename keytab_name -> kpasswd_keytab_name This makes explicitly clear the purpose of this keytab. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/kdc/kdc-heimdal.c | 4 ++-- source4/kdc/kdc-server.h | 2 +- source4/kdc/kdc-service-mit.c | 4 ++-- source4/kdc/kpasswd-service.c | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source4/kdc/kdc-heimdal.c b/source4/kdc/kdc-heimdal.c index 542986c5ad3..5b2b3e36652 100644 --- a/source4/kdc/kdc-heimdal.c +++ b/source4/kdc/kdc-heimdal.c @@ -463,8 +463,8 @@ static void kdc_post_fork(struct task_server *task, struct process_details *pd) return; } - kdc->keytab_name = talloc_asprintf(kdc, "HDBGET:samba4:&%p", kdc->base_ctx); - if (kdc->keytab_name == NULL) { + kdc->kpasswd_keytab_name = talloc_asprintf(kdc, "HDBGET:samba4:&%p", kdc->base_ctx); + if (kdc->kpasswd_keytab_name == NULL) { task_server_terminate(task, "kdc: Failed to set keytab name", true); diff --git a/source4/kdc/kdc-server.h b/source4/kdc/kdc-server.h index fd883c2e4b4..89b30f122f5 100644 --- a/source4/kdc/kdc-server.h +++ b/source4/kdc/kdc-server.h @@ -40,7 +40,7 @@ struct kdc_server { struct ldb_context *samdb; bool am_rodc; uint32_t proxy_timeout; - const char *keytab_name; + const char *kpasswd_keytab_name; void *private_data; }; diff --git a/source4/kdc/kdc-service-mit.c b/source4/kdc/kdc-service-mit.c index 5d4180aa7cc..22663b6ecc8 100644 --- a/source4/kdc/kdc-service-mit.c +++ b/source4/kdc/kdc-service-mit.c @@ -291,8 +291,8 @@ NTSTATUS mitkdc_task_init(struct task_server *task) return NT_STATUS_INTERNAL_ERROR; } - kdc->keytab_name = talloc_asprintf(kdc, "KDB:"); - if (kdc->keytab_name == NULL) { + kdc->kpasswd_keytab_name = talloc_asprintf(kdc, "KDB:"); + if (kdc->kpasswd_keytab_name == NULL) { task_server_terminate(task, "KDC: Out of memory", true); diff --git a/source4/kdc/kpasswd-service.c b/source4/kdc/kpasswd-service.c index 379ddebf3ad..aec30850173 100644 --- a/source4/kdc/kpasswd-service.c +++ b/source4/kdc/kpasswd-service.c @@ -170,7 +170,7 @@ kdc_code kpasswd_process(struct kdc_server *kdc, rv = cli_credentials_set_keytab_name(server_credentials, kdc->task->lp_ctx, - kdc->keytab_name, + kdc->kpasswd_keytab_name, CRED_SPECIFIED); if (rv != 0) { DBG_ERR("Failed to set credentials keytab name\n"); -- 2.25.1 From fa198ce28f82efd2e05178bab3b5606662c40a09 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Wed, 8 Jun 2022 13:53:29 +1200 Subject: [PATCH 59/68] s4:kdc: Remove kadmin mode from HDB plugin It appears we no longer require it. Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/kdc/hdb-samba4-plugin.c | 35 +++++++-------------------------- 1 file changed, 7 insertions(+), 28 deletions(-) diff --git a/source4/kdc/hdb-samba4-plugin.c b/source4/kdc/hdb-samba4-plugin.c index 9dc4784f379..7a5a9485e05 100644 --- a/source4/kdc/hdb-samba4-plugin.c +++ b/source4/kdc/hdb-samba4-plugin.c @@ -21,40 +21,20 @@ #include "includes.h" #include "kdc/kdc-glue.h" -#include "kdc/db-glue.h" -#include "lib/util/samba_util.h" #include "lib/param/param.h" -#include "source4/lib/events/events.h" static krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg) { NTSTATUS nt_status; - void *ptr; - struct samba_kdc_base_context *base_ctx; - - if (sscanf(arg, "&%p", &ptr) == 1) { - base_ctx = talloc_get_type_abort(ptr, struct samba_kdc_base_context); - } else if (arg[0] == '\0' || file_exist(arg)) { - /* This mode for use in kadmin, rather than in Samba */ - - setup_logging("hdb_samba4", DEBUG_DEFAULT_STDERR); - - base_ctx = talloc_zero(NULL, struct samba_kdc_base_context); - if (!base_ctx) { - return ENOMEM; - } - - base_ctx->ev_ctx = s4_event_context_init(base_ctx); - base_ctx->lp_ctx = loadparm_init_global(false); - if (arg[0]) { - lpcfg_load(base_ctx->lp_ctx, arg); - } else { - lpcfg_load_default(base_ctx->lp_ctx); - } - } else { + void *ptr = NULL; + struct samba_kdc_base_context *base_ctx = NULL; + + if (sscanf(arg, "&%p", &ptr) != 1) { return EINVAL; } + base_ctx = talloc_get_type_abort(ptr, struct samba_kdc_base_context); + /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */ nt_status = hdb_samba4_create_kdc(base_ctx, context, db); @@ -90,8 +70,7 @@ static void hdb_samba4_fini(void *ctx) /* Only used in the hdb-backed keytab code * for a keytab of 'samba4&
' or samba4, to find - * kpasswd's key in the main DB, and to - * copy all the keys into a file (libnet_keytab_export) + * kpasswd's key in the main DB * * The
is the string form of a pointer to a talloced struct hdb_samba_context */ -- 2.25.1 From c9e1949fa8e14a3f2516abb439a2ba83dab418ce Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 26 May 2022 16:39:20 +1200 Subject: [PATCH 60/68] CVE-2022-32744 s4:kdc: Modify HDB plugin to only look up kpasswd principal This plugin is now only used by the kpasswd service. Thus, ensuring we only look up the kadmin/changepw principal means we can't be fooled into accepting tickets for other service principals. We make sure not to specify a specific kvno, to ensure that we do not accept RODC-issued tickets. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Fixed knownfail conflicts] --- selftest/knownfail_heimdal_kdc | 5 --- source4/kdc/hdb-samba4-plugin.c | 2 +- source4/kdc/hdb-samba4.c | 66 +++++++++++++++++++++++++++++++++ source4/kdc/kdc-glue.h | 3 ++ 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index fb6ac228c54..0e363f67754 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -48,8 +48,3 @@ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_user2user_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_validate_rodc_not_revealed # -# Kpasswd tests -# -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/hdb-samba4-plugin.c b/source4/kdc/hdb-samba4-plugin.c index 7a5a9485e05..be6d2437d0e 100644 --- a/source4/kdc/hdb-samba4-plugin.c +++ b/source4/kdc/hdb-samba4-plugin.c @@ -36,7 +36,7 @@ static krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, base_ctx = talloc_get_type_abort(ptr, struct samba_kdc_base_context); /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */ - nt_status = hdb_samba4_create_kdc(base_ctx, context, db); + nt_status = hdb_samba4_kpasswd_create_kdc(base_ctx, context, db); if (NT_STATUS_IS_OK(nt_status)) { return 0; diff --git a/source4/kdc/hdb-samba4.c b/source4/kdc/hdb-samba4.c index e82ebbe7daa..3705a086bb2 100644 --- a/source4/kdc/hdb-samba4.c +++ b/source4/kdc/hdb-samba4.c @@ -292,6 +292,47 @@ static krb5_error_code hdb_samba4_fetch_kvno(krb5_context context, HDB *db, return code; } +static krb5_error_code hdb_samba4_kpasswd_fetch_kvno(krb5_context context, HDB *db, + krb5_const_principal _principal, + unsigned flags, + krb5_kvno _kvno, + hdb_entry *entry) +{ + struct samba_kdc_db_context *kdc_db_ctx = NULL; + krb5_error_code ret; + krb5_principal kpasswd_principal = NULL; + + kdc_db_ctx = talloc_get_type_abort(db->hdb_db, + struct samba_kdc_db_context); + + ret = smb_krb5_make_principal(context, &kpasswd_principal, + lpcfg_realm(kdc_db_ctx->lp_ctx), + "kadmin", "changepw", + NULL); + if (ret) { + return ret; + } + smb_krb5_principal_set_type(context, kpasswd_principal, KRB5_NT_SRV_INST); + + /* + * For the kpasswd service, always ensure we get the latest kvno. This + * also means we (correctly) refuse RODC-issued tickets. + */ + flags &= ~HDB_F_KVNO_SPECIFIED; + + /* Don't bother looking up a client or krbtgt. */ + flags &= ~(SDB_F_GET_CLIENT|SDB_F_GET_KRBTGT); + + ret = hdb_samba4_fetch_kvno(context, db, + kpasswd_principal, + flags, + 0, + entry); + + krb5_free_principal(context, kpasswd_principal); + return ret; +} + static krb5_error_code hdb_samba4_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry) { @@ -350,6 +391,14 @@ static krb5_error_code hdb_samba4_nextkey(krb5_context context, HDB *db, unsigne return ret; } +static krb5_error_code hdb_samba4_nextkey_panic(krb5_context context, HDB *db, + unsigned flags, + hdb_entry *entry) +{ + DBG_ERR("Attempt to iterate kpasswd keytab => PANIC\n"); + smb_panic("hdb_samba4_nextkey_panic: Attempt to iterate kpasswd keytab"); +} + static krb5_error_code hdb_samba4_destroy(krb5_context context, HDB *db) { talloc_free(db); @@ -812,3 +861,20 @@ NTSTATUS hdb_samba4_create_kdc(struct samba_kdc_base_context *base_ctx, return NT_STATUS_OK; } + +NTSTATUS hdb_samba4_kpasswd_create_kdc(struct samba_kdc_base_context *base_ctx, + krb5_context context, struct HDB **db) +{ + NTSTATUS nt_status; + + nt_status = hdb_samba4_create_kdc(base_ctx, context, db); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + (*db)->hdb_fetch_kvno = hdb_samba4_kpasswd_fetch_kvno; + (*db)->hdb_firstkey = hdb_samba4_nextkey_panic; + (*db)->hdb_nextkey = hdb_samba4_nextkey_panic; + + return NT_STATUS_OK; +} diff --git a/source4/kdc/kdc-glue.h b/source4/kdc/kdc-glue.h index 47642e12432..7a0184c4021 100644 --- a/source4/kdc/kdc-glue.h +++ b/source4/kdc/kdc-glue.h @@ -46,6 +46,9 @@ kdc_code kpasswdd_process(struct kdc_server *kdc, NTSTATUS hdb_samba4_create_kdc(struct samba_kdc_base_context *base_ctx, krb5_context context, struct HDB **db); +NTSTATUS hdb_samba4_kpasswd_create_kdc(struct samba_kdc_base_context *base_ctx, + krb5_context context, struct HDB **db); + /* from kdc-glue.c */ int kdc_check_pac(krb5_context krb5_context, DATA_BLOB server_sig, -- 2.25.1 From 7ee246ef9ca9c057779466bc9d0319606de46eff Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Mon, 30 May 2022 19:16:02 +1200 Subject: [PATCH 61/68] CVE-2022-32744 s4:kpasswd: Ensure we pass the kpasswd server principal into krb5_rd_req_ctx() To ensure that, when decrypting the kpasswd ticket, we look up the correct principal and don't trust the sname from the ticket, we should pass the principal name of the kpasswd service into krb5_rd_req_ctx(). However, gensec_krb5_update_internal() will pass in NULL unless the principal in our credentials is CRED_SPECIFIED. At present, our principal will be considered obtained as CRED_SMB_CONF (from the cli_credentials_set_conf() a few lines up), so we explicitly set the realm again, but this time as CRED_SPECIFIED. Now the value of server_in_keytab that we provide to smb_krb5_rd_req_decoded() will not be NULL. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- selftest/knownfail_mit_kdc | 2 -- source4/kdc/kpasswd-service.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index 13dd806aeb1..6d07ca4efb6 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -550,5 +550,3 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_server.ad_dc -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_wrong_key_service.ad_dc diff --git a/source4/kdc/kpasswd-service.c b/source4/kdc/kpasswd-service.c index aec30850173..d2f1bb02906 100644 --- a/source4/kdc/kpasswd-service.c +++ b/source4/kdc/kpasswd-service.c @@ -29,6 +29,7 @@ #include "kdc/kdc-server.h" #include "kdc/kpasswd-service.h" #include "kdc/kpasswd-helper.h" +#include "param/param.h" #define HEADER_LEN 6 #ifndef RFC3244_VERSION @@ -161,6 +162,20 @@ kdc_code kpasswd_process(struct kdc_server *kdc, goto done; } + /* + * After calling cli_credentials_set_conf(), explicitly set the realm + * with CRED_SPECIFIED. We need to do this so the result of + * principal_from_credentials() called from the gensec layer is + * CRED_SPECIFIED rather than CRED_SMB_CONF, avoiding a fallback to + * match-by-key (very undesirable in this case). + */ + ok = cli_credentials_set_realm(server_credentials, + lpcfg_realm(kdc->task->lp_ctx), + CRED_SPECIFIED); + if (!ok) { + goto done; + } + ok = cli_credentials_set_username(server_credentials, "kadmin/changepw", CRED_SPECIFIED); @@ -168,6 +183,21 @@ kdc_code kpasswd_process(struct kdc_server *kdc, goto done; } + /* Check that the server principal is indeed CRED_SPECIFIED. */ + { + char *principal = NULL; + enum credentials_obtained obtained; + + principal = cli_credentials_get_principal_and_obtained(server_credentials, + tmp_ctx, + &obtained); + if (obtained < CRED_SPECIFIED) { + goto done; + } + + TALLOC_FREE(principal); + } + rv = cli_credentials_set_keytab_name(server_credentials, kdc->task->lp_ctx, kdc->kpasswd_keytab_name, -- 2.25.1 From ff66f68a11c87531648c907ae2a7a6753868bc03 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 10 Jun 2022 19:17:11 +1200 Subject: [PATCH 62/68] CVE-2022-2031 tests/krb5: Add test that we cannot provide a TGT to kpasswd The kpasswd service should require a kpasswd service ticket, and disallow TGTs. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Fixed knownfail conflicts] --- python/samba/tests/krb5/kpasswd_tests.py | 28 ++++++++++++++++++++++++ selftest/knownfail_heimdal_kdc | 3 +++ selftest/knownfail_mit_kdc | 4 ++++ 3 files changed, 35 insertions(+) diff --git a/python/samba/tests/krb5/kpasswd_tests.py b/python/samba/tests/krb5/kpasswd_tests.py index 3a6c7d818dc..0db857f7bbd 100755 --- a/python/samba/tests/krb5/kpasswd_tests.py +++ b/python/samba/tests/krb5/kpasswd_tests.py @@ -31,6 +31,7 @@ from samba.tests.krb5.rfc4120_constants import ( KDC_ERR_TGT_REVOKED, KDC_ERR_TKT_EXPIRED, KPASSWD_ACCESSDENIED, + KPASSWD_AUTHERROR, KPASSWD_HARDERROR, KPASSWD_INITIAL_FLAG_NEEDED, KPASSWD_MALFORMED, @@ -779,6 +780,33 @@ class KpasswdTests(KDCBaseTest): self._make_tgs_request(creds, service_creds, ticket, expect_error=False) + # Show that we cannot provide a TGT to kpasswd to change the password. + def test_kpasswd_tgt(self): + # Create an account for testing, and get a TGT. + creds = self._get_creds() + tgt = self.get_tgt(creds) + + # Change the sname of the ticket to match that of kadmin/changepw. + tgt.set_sname(self.get_kpasswd_sname()) + + expected_code = KPASSWD_AUTHERROR + expected_msg = b'A TGT may not be used as a ticket to kpasswd' + + # Set the password. + new_password = generate_random_password(32, 32) + self.kpasswd_exchange(tgt, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.SET) + + # Change the password. + self.kpasswd_exchange(tgt, + new_password, + expected_code, + expected_msg, + mode=self.KpasswdMode.CHANGE) + # Test that kpasswd rejects requests with a service ticket. def test_kpasswd_non_initial(self): # Create an account for testing, and get a TGT. diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index 0e363f67754..c31ec8e11a1 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -48,3 +48,6 @@ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_user2user_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_validate_rodc_not_revealed # +# Kpasswd tests +# +^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_tgt.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index 6d07ca4efb6..db0f3541bf7 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -550,3 +550,7 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc +# +# Kpasswd tests +# +samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_tgt.ad_dc -- 2.25.1 From 9895018b64c56c6e5a291c0ae90f3fc33e26e0ef Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 10 Jun 2022 19:18:07 +1200 Subject: [PATCH 63/68] CVE-2022-2031 auth: Add ticket type field to auth_user_info_dc and auth_session_info This field may be used to convey whether we were provided with a TGT or a non-TGT. We ensure both structures are zeroed out to avoid incorrect results being produced by an uninitialised field. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- auth/auth_sam_reply.c | 2 +- auth/auth_util.c | 2 +- librpc/idl/auth.idl | 23 +++++++++++++++++++++++ source4/auth/ntlm/auth_developer.c | 2 +- source4/auth/sam.c | 2 +- source4/auth/session.c | 2 ++ source4/auth/system_session.c | 6 +++--- 7 files changed, 32 insertions(+), 7 deletions(-) diff --git a/auth/auth_sam_reply.c b/auth/auth_sam_reply.c index fda014c87d5..173a5132964 100644 --- a/auth/auth_sam_reply.c +++ b/auth/auth_sam_reply.c @@ -416,7 +416,7 @@ NTSTATUS make_user_info_dc_netlogon_validation(TALLOC_CTX *mem_ctx, return NT_STATUS_INVALID_LEVEL; } - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); /* diff --git a/auth/auth_util.c b/auth/auth_util.c index fe01babd107..ec9094d0f15 100644 --- a/auth/auth_util.c +++ b/auth/auth_util.c @@ -44,7 +44,7 @@ struct auth_session_info *copy_session_info(TALLOC_CTX *mem_ctx, return NULL; } - dst = talloc(mem_ctx, struct auth_session_info); + dst = talloc_zero(mem_ctx, struct auth_session_info); if (dst == NULL) { DBG_ERR("talloc failed\n"); TALLOC_FREE(frame); diff --git a/librpc/idl/auth.idl b/librpc/idl/auth.idl index 7de3d4c6bfb..59ed2c3c5ea 100644 --- a/librpc/idl/auth.idl +++ b/librpc/idl/auth.idl @@ -75,6 +75,26 @@ interface auth [unique,charset(UTF8),string] char *sanitized_username; } auth_user_info_unix; + /* + * If the user was authenticated with a Kerberos ticket, this indicates + * the type of the ticket; TGT, or non-TGT (i.e. service ticket). If + * unset, the type is unknown. This indicator is useful for the KDC and + * the kpasswd service, which share the same account and keys. By + * ensuring it is provided with the appopriate ticket type, each service + * avoids accepting a ticket meant for the other. + * + * The heuristic used to determine the type is the presence or absence + * of a REQUESTER_SID buffer in the PAC; we use its presence to assume + * we have a TGT. This heuristic will fail for older Samba versions and + * Windows prior to Nov. 2021 updates, which lack support for this + * buffer. + */ + typedef enum { + TICKET_TYPE_UNKNOWN = 0, + TICKET_TYPE_TGT = 1, + TICKET_TYPE_NON_TGT = 2 + } ticket_type; + /* This is the interim product of the auth subsystem, before * privileges and local groups are handled */ typedef [public] struct { @@ -83,6 +103,7 @@ interface auth auth_user_info *info; [noprint] DATA_BLOB user_session_key; [noprint] DATA_BLOB lm_session_key; + ticket_type ticket_type; } auth_user_info_dc; typedef [public] struct { @@ -112,6 +133,8 @@ interface auth * We generate this in auth_generate_session_info() */ GUID unique_session_token; + + ticket_type ticket_type; } auth_session_info; typedef [public] struct { diff --git a/source4/auth/ntlm/auth_developer.c b/source4/auth/ntlm/auth_developer.c index 1823989c68d..6e92252d5c5 100644 --- a/source4/auth/ntlm/auth_developer.c +++ b/source4/auth/ntlm/auth_developer.c @@ -76,7 +76,7 @@ static NTSTATUS name_to_ntstatus_check_password(struct auth_method_context *ctx, } NT_STATUS_NOT_OK_RETURN(nt_status); - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); /* This returns a pointer to a struct dom_sid, which is the diff --git a/source4/auth/sam.c b/source4/auth/sam.c index 8b233bab3ad..7c609655fcb 100644 --- a/source4/auth/sam.c +++ b/source4/auth/sam.c @@ -363,7 +363,7 @@ _PUBLIC_ NTSTATUS authsam_make_user_info_dc(TALLOC_CTX *mem_ctx, TALLOC_CTX *tmp_ctx; struct ldb_message_element *el; - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); tmp_ctx = talloc_new(user_info_dc); diff --git a/source4/auth/session.c b/source4/auth/session.c index 8cf8670d848..34ad557eebb 100644 --- a/source4/auth/session.c +++ b/source4/auth/session.c @@ -222,6 +222,8 @@ _PUBLIC_ NTSTATUS auth_generate_session_info(TALLOC_CTX *mem_ctx, session_info->credentials = NULL; + session_info->ticket_type = user_info_dc->ticket_type; + talloc_steal(mem_ctx, session_info); *_session_info = session_info; talloc_free(tmp_ctx); diff --git a/source4/auth/system_session.c b/source4/auth/system_session.c index e46b4584817..17cfc4bab8b 100644 --- a/source4/auth/system_session.c +++ b/source4/auth/system_session.c @@ -119,7 +119,7 @@ NTSTATUS auth_system_user_info_dc(TALLOC_CTX *mem_ctx, const char *netbios_name, struct auth_user_info_dc *user_info_dc; struct auth_user_info *info; - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); /* This returns a pointer to a struct dom_sid, which is the @@ -195,7 +195,7 @@ static NTSTATUS auth_domain_admin_user_info_dc(TALLOC_CTX *mem_ctx, struct auth_user_info_dc *user_info_dc; struct auth_user_info *info; - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); user_info_dc->num_sids = 7; @@ -364,7 +364,7 @@ _PUBLIC_ NTSTATUS auth_anonymous_user_info_dc(TALLOC_CTX *mem_ctx, { struct auth_user_info_dc *user_info_dc; struct auth_user_info *info; - user_info_dc = talloc(mem_ctx, struct auth_user_info_dc); + user_info_dc = talloc_zero(mem_ctx, struct auth_user_info_dc); NT_STATUS_HAVE_NO_MEMORY(user_info_dc); /* This returns a pointer to a struct dom_sid, which is the -- 2.25.1 From 8c0f421852dfcde31ef94e3af182e438a3bc460f Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 10 Jun 2022 19:18:35 +1200 Subject: [PATCH 64/68] CVE-2022-2031 s4:auth: Use PAC to determine whether ticket is a TGT We use the presence or absence of a REQUESTER_SID PAC buffer to determine whether the ticket is a TGT. We will later use this to reject TGTs where a service ticket is expected. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider --- source4/auth/kerberos/kerberos_pac.c | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/source4/auth/kerberos/kerberos_pac.c b/source4/auth/kerberos/kerberos_pac.c index dccf165384e..156a140b1de 100644 --- a/source4/auth/kerberos/kerberos_pac.c +++ b/source4/auth/kerberos/kerberos_pac.c @@ -282,6 +282,28 @@ return ret; } +static krb5_error_code kerberos_pac_buffer_present(krb5_context context, + const krb5_pac pac, + uint32_t type) +{ +#ifdef SAMBA4_USES_HEIMDAL + return krb5_pac_get_buffer(context, pac, type, NULL); +#else /* MIT */ + krb5_error_code ret; + krb5_data data; + + /* + * MIT won't let us pass NULL for the data parameter, so we are forced + * to allocate a new buffer and then immediately free it. + */ + ret = krb5_pac_get_buffer(context, pac, type, &data); + if (ret == 0) { + krb5_free_data_contents(context, &data); + } + return ret; +#endif /* SAMBA4_USES_HEIMDAL */ +} + krb5_error_code kerberos_pac_to_user_info_dc(TALLOC_CTX *mem_ctx, krb5_pac pac, krb5_context context, @@ -420,6 +442,28 @@ krb5_error_code kerberos_pac_to_user_info_dc(TALLOC_CTX *mem_ctx, return EINVAL; } } + + /* + * Based on the presence of a REQUESTER_SID PAC buffer, ascertain + * whether the ticket is a TGT. This helps the KDC and kpasswd service + * ensure they do not accept tickets meant for the other. + * + * This heuristic will fail for older Samba versions and Windows prior + * to Nov. 2021 updates, which lack support for the REQUESTER_SID PAC + * buffer. + */ + ret = kerberos_pac_buffer_present(context, pac, PAC_TYPE_REQUESTER_SID); + if (ret == ENOENT) { + /* This probably isn't a TGT. */ + user_info_dc_out->ticket_type = TICKET_TYPE_NON_TGT; + } else if (ret != 0) { + talloc_free(tmp_ctx); + return ret; + } else { + /* This probably is a TGT. */ + user_info_dc_out->ticket_type = TICKET_TYPE_TGT; + } + *user_info_dc = user_info_dc_out; return 0; -- 2.25.1 From a46dd2846f37ec7d64716c8e68d53cf1ab5e4f67 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Fri, 10 Jun 2022 19:18:53 +1200 Subject: [PATCH 65/68] CVE-2022-2031 s4:kpasswd: Do not accept TGTs as kpasswd tickets If TGTs can be used as kpasswd tickets, the two-minute lifetime of a authentic kpasswd ticket may be bypassed. Furthermore, kpasswd tickets are not supposed to be cached, but using this flaw, a stolen credentials cache containing a TGT may be used to change that account's password, and thus is made more valuable to an attacker. Since all TGTs should be issued with a REQUESTER_SID PAC buffer, and service tickets without it, we assert the absence of this buffer to ensure we're not accepting a TGT. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049 Signed-off-by: Joseph Sutton Reviewed-by: Andreas Schneider [jsutton@samba.org Fixed knownfail conflicts] --- selftest/knownfail_heimdal_kdc | 4 ---- selftest/knownfail_mit_kdc | 4 ---- source4/kdc/kpasswd-helper.c | 20 ++++++++++++++++++++ source4/kdc/kpasswd-helper.h | 2 ++ source4/kdc/kpasswd-service-heimdal.c | 13 +++++++++++++ source4/kdc/kpasswd-service-mit.c | 13 +++++++++++++ 6 files changed, 48 insertions(+), 8 deletions(-) diff --git a/selftest/knownfail_heimdal_kdc b/selftest/knownfail_heimdal_kdc index c31ec8e11a1..a5a995d92f0 100644 --- a/selftest/knownfail_heimdal_kdc +++ b/selftest/knownfail_heimdal_kdc @@ -47,7 +47,3 @@ ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_tgs_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_user2user_rodc_not_revealed ^samba.tests.krb5.kdc_tgs_tests.samba.tests.krb5.kdc_tgs_tests.KdcTgsTests.test_validate_rodc_not_revealed -# -# Kpasswd tests -# -^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_tgt.ad_dc diff --git a/selftest/knownfail_mit_kdc b/selftest/knownfail_mit_kdc index db0f3541bf7..6d07ca4efb6 100644 --- a/selftest/knownfail_mit_kdc +++ b/selftest/knownfail_mit_kdc @@ -550,7 +550,3 @@ samba.tests.krb5.as_canonicalization_tests.samba.tests.krb5.as_canonicalization_ ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_no_canonicalize_realm_case.ad_dc ^samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_ticket_requester_sid_tgs.ad_dc -# -# Kpasswd tests -# -samba.tests.krb5.kpasswd_tests.samba.tests.krb5.kpasswd_tests.KpasswdTests.test_kpasswd_tgt.ad_dc diff --git a/source4/kdc/kpasswd-helper.c b/source4/kdc/kpasswd-helper.c index 55a2f5b3bf6..2ffdb79aea5 100644 --- a/source4/kdc/kpasswd-helper.c +++ b/source4/kdc/kpasswd-helper.c @@ -241,3 +241,23 @@ NTSTATUS kpasswd_samdb_set_password(TALLOC_CTX *mem_ctx, return status; } + +krb5_error_code kpasswd_check_non_tgt(struct auth_session_info *session_info, + const char **error_string) +{ + switch(session_info->ticket_type) { + case TICKET_TYPE_TGT: + /* TGTs are disallowed here. */ + *error_string = "A TGT may not be used as a ticket to kpasswd"; + return KRB5_KPASSWD_AUTHERROR; + case TICKET_TYPE_NON_TGT: + /* Non-TGTs are permitted, and expected. */ + break; + default: + /* In case we forgot to set the type. */ + *error_string = "Failed to ascertain that ticket to kpasswd is not a TGT"; + return KRB5_KPASSWD_HARDERROR; + } + + return 0; +} diff --git a/source4/kdc/kpasswd-helper.h b/source4/kdc/kpasswd-helper.h index 8fad81e0a5d..94a6e2acfdd 100644 --- a/source4/kdc/kpasswd-helper.h +++ b/source4/kdc/kpasswd-helper.h @@ -43,4 +43,6 @@ NTSTATUS kpasswd_samdb_set_password(TALLOC_CTX *mem_ctx, enum samPwdChangeReason *reject_reason, struct samr_DomInfo1 **dominfo); +krb5_error_code kpasswd_check_non_tgt(struct auth_session_info *session_info, + const char **error_string); #endif /* _KPASSWD_HELPER_H */ diff --git a/source4/kdc/kpasswd-service-heimdal.c b/source4/kdc/kpasswd-service-heimdal.c index a0352d1ad35..4d009b9eb24 100644 --- a/source4/kdc/kpasswd-service-heimdal.c +++ b/source4/kdc/kpasswd-service-heimdal.c @@ -253,6 +253,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, { struct auth_session_info *session_info; NTSTATUS status; + krb5_error_code code; status = gensec_session_info(gensec_security, mem_ctx, @@ -264,6 +265,18 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, return KRB5_KPASSWD_HARDERROR; } + /* + * Since the kpasswd service shares its keys with the krbtgt, we might + * have received a TGT rather than a kpasswd ticket. We need to check + * the ticket type to ensure that TGTs cannot be misused in this manner. + */ + code = kpasswd_check_non_tgt(session_info, + error_string); + if (code != 0) { + DBG_WARNING("%s\n", *error_string); + return code; + } + switch(verno) { case KRB5_KPASSWD_VERS_CHANGEPW: { DATA_BLOB password = data_blob_null; diff --git a/source4/kdc/kpasswd-service-mit.c b/source4/kdc/kpasswd-service-mit.c index de4c6f3f622..6b051567b6e 100644 --- a/source4/kdc/kpasswd-service-mit.c +++ b/source4/kdc/kpasswd-service-mit.c @@ -332,6 +332,7 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, { struct auth_session_info *session_info; NTSTATUS status; + krb5_error_code code; status = gensec_session_info(gensec_security, mem_ctx, @@ -344,6 +345,18 @@ krb5_error_code kpasswd_handle_request(struct kdc_server *kdc, return KRB5_KPASSWD_HARDERROR; } + /* + * Since the kpasswd service shares its keys with the krbtgt, we might + * have received a TGT rather than a kpasswd ticket. We need to check + * the ticket type to ensure that TGTs cannot be misused in this manner. + */ + code = kpasswd_check_non_tgt(session_info, + error_string); + if (code != 0) { + DBG_WARNING("%s\n", *error_string); + return code; + } + switch(verno) { case 1: { DATA_BLOB password; -- 2.25.1 From e650b41ff907ac48f66844bbdf72f83a9e41ea16 Mon Sep 17 00:00:00 2001 From: Joseph Sutton Date: Thu, 23 Jun 2022 13:59:11 +1200 Subject: [PATCH 66/68] CVE-2022-2031 testprogs: Add test for short-lived ticket across an incoming trust We ensure that the KDC does not reject a TGS-REQ with our short-lived TGT over an incoming trust. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047 Signed-off-by: Joseph Sutton --- testprogs/blackbox/test_kinit_trusts_heimdal.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/testprogs/blackbox/test_kinit_trusts_heimdal.sh b/testprogs/blackbox/test_kinit_trusts_heimdal.sh index 52b1ac6589c..29ea1c510ce 100755 --- a/testprogs/blackbox/test_kinit_trusts_heimdal.sh +++ b/testprogs/blackbox/test_kinit_trusts_heimdal.sh @@ -55,6 +55,10 @@ testit "kinit with password" $samba4kinit $enctype --password-file=$PREFIX/tmppa test_smbclient "Test login with user kerberos ccache" 'ls' "$unc" --use-krb5-ccache=$KRB5CCNAME || failed=`expr $failed + 1` rm -rf $KRB5CCNAME_PATH +testit "kinit with password and two minute lifetime" $samba4kinit $enctype --password-file=$PREFIX/tmppassfile --request-pac --server=krbtgt/$REALM@$TRUST_REALM --lifetime=2m $TRUST_USERNAME@$TRUST_REALM || failed=`expr $failed + 1` +test_smbclient "Test login with user kerberos ccache and two minute lifetime" 'ls' "$unc" --use-krb5-ccache=$KRB5CCNAME || failed=`expr $failed + 1` +rm -rf $KRB5CCNAME_PATH + # Test with smbclient4 smbclient="$samba4bindir/smbclient4" testit "kinit with password" $samba4kinit $enctype --password-file=$PREFIX/tmppassfile --request-pac $TRUST_USERNAME@$TRUST_REALM || failed=`expr $failed + 1` @@ -95,5 +99,5 @@ testit "wbinfo check outgoing trust pw" $VALGRIND $wbinfo --check-secret --domai test_smbclient "Test user login with the changed outgoing secret" 'ls' "$unc" --use-kerberos=required -U$USERNAME@$REALM%$PASSWORD || failed=`expr $failed + 1` -rm -f $PREFIX/tmpccache tmpccfile tmppassfile tmpuserpassfile tmpuserccache +rm -f $PREFIX/tmpccache $PREFIX/tmppassfile exit $failed -- 2.25.1 From ed3f82f4d70bbc89b89af31153eed96a544a754a Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Tue, 7 Jun 2022 09:40:45 -0700 Subject: [PATCH 67/68] CVE-2022-32742: s4: torture: Add raw.write.bad-write test. Reproduces the test code in: BUG: https://bugzilla.samba.org/show_bug.cgi?id=15085 Add knownfail. Signed-off-by: Jeremy Allison Reviewed-by: David Disseldorp --- selftest/knownfail.d/bad-write | 2 + source4/torture/raw/write.c | 89 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 selftest/knownfail.d/bad-write diff --git a/selftest/knownfail.d/bad-write b/selftest/knownfail.d/bad-write new file mode 100644 index 00000000000..5fc16606a13 --- /dev/null +++ b/selftest/knownfail.d/bad-write @@ -0,0 +1,2 @@ +^samba3.raw.write.bad-write\(nt4_dc_smb1\) +^samba3.raw.write.bad-write\(ad_dc_smb1\) diff --git a/source4/torture/raw/write.c b/source4/torture/raw/write.c index 0a2f50f425b..661485bb548 100644 --- a/source4/torture/raw/write.c +++ b/source4/torture/raw/write.c @@ -25,6 +25,7 @@ #include "libcli/libcli.h" #include "torture/util.h" #include "torture/raw/proto.h" +#include "libcli/raw/raw_proto.h" #define CHECK_STATUS(status, correct) do { \ if (!NT_STATUS_EQUAL(status, correct)) { \ @@ -694,6 +695,93 @@ done: return ret; } +/* + test a deliberately bad SMB1 write. +*/ +static bool test_bad_write(struct torture_context *tctx, + struct smbcli_state *cli) +{ + bool ret = false; + int fnum = -1; + struct smbcli_request *req = NULL; + const char *fname = BASEDIR "\\badwrite.txt"; + bool ok = false; + + if (!torture_setup_dir(cli, BASEDIR)) { + torture_fail(tctx, "failed to setup basedir"); + } + + torture_comment(tctx, "Testing RAW_BAD_WRITE\n"); + + fnum = smbcli_open(cli->tree, fname, O_RDWR|O_CREAT, DENY_NONE); + if (fnum == -1) { + torture_fail_goto(tctx, + done, + talloc_asprintf(tctx, + "Failed to create %s - %s\n", + fname, + smbcli_errstr(cli->tree))); + } + + req = smbcli_request_setup(cli->tree, + SMBwrite, + 5, + 0); + if (req == NULL) { + torture_fail_goto(tctx, + done, + talloc_asprintf(tctx, "talloc fail\n")); + } + + SSVAL(req->out.vwv, VWV(0), fnum); + SSVAL(req->out.vwv, VWV(1), 65535); /* bad write length. */ + SIVAL(req->out.vwv, VWV(2), 0); /* offset */ + SSVAL(req->out.vwv, VWV(4), 0); /* remaining. */ + + if (!smbcli_request_send(req)) { + torture_fail_goto(tctx, + done, + talloc_asprintf(tctx, "Send failed\n")); + } + + if (!smbcli_request_receive(req)) { + torture_fail_goto(tctx, + done, + talloc_asprintf(tctx, "Reveive failed\n")); + } + + /* + * Check for expected error codes. + * ntvfs returns NT_STATUS_UNSUCCESSFUL. + */ + ok = (NT_STATUS_EQUAL(req->status, NT_STATUS_INVALID_PARAMETER) || + NT_STATUS_EQUAL(req->status, NT_STATUS_UNSUCCESSFUL)); + + if (!ok) { + torture_fail_goto(tctx, + done, + talloc_asprintf(tctx, + "Should have returned " + "NT_STATUS_INVALID_PARAMETER or " + "NT_STATUS_UNSUCCESSFUL " + "got %s\n", + nt_errstr(req->status))); + } + + ret = true; + +done: + if (req != NULL) { + smbcli_request_destroy(req); + } + if (fnum != -1) { + smbcli_close(cli->tree, fnum); + } + smb_raw_exit(cli->session); + smbcli_deltree(cli->tree, BASEDIR); + return ret; +} + /* basic testing of write calls */ @@ -705,6 +793,7 @@ struct torture_suite *torture_raw_write(TALLOC_CTX *mem_ctx) torture_suite_add_1smb_test(suite, "write unlock", test_writeunlock); torture_suite_add_1smb_test(suite, "write close", test_writeclose); torture_suite_add_1smb_test(suite, "writex", test_writex); + torture_suite_add_1smb_test(suite, "bad-write", test_bad_write); return suite; } -- 2.25.1 From 74946420dd59a102c8d5f4a0127d5e479da5470d Mon Sep 17 00:00:00 2001 From: Jeremy Allison Date: Wed, 8 Jun 2022 13:50:51 -0700 Subject: [PATCH 68/68] CVE-2022-32742: s3: smbd: Harden the smbreq_bufrem() macro. Fixes the raw.write.bad-write test. NB. We need the two (==0) changes in source3/smbd/reply.c as the gcc optimizer now knows that the return from smbreq_bufrem() can never be less than zero. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15085 Remove knownfail. Signed-off-by: Jeremy Allison Reviewed-by: David Disseldorp --- selftest/knownfail.d/bad-write | 2 -- source3/include/smb_macros.h | 2 +- source3/smbd/reply.c | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) delete mode 100644 selftest/knownfail.d/bad-write diff --git a/selftest/knownfail.d/bad-write b/selftest/knownfail.d/bad-write deleted file mode 100644 index 5fc16606a13..00000000000 --- a/selftest/knownfail.d/bad-write +++ /dev/null @@ -1,2 +0,0 @@ -^samba3.raw.write.bad-write\(nt4_dc_smb1\) -^samba3.raw.write.bad-write\(ad_dc_smb1\) diff --git a/source3/include/smb_macros.h b/source3/include/smb_macros.h index 344a997cbd2..c75b93fcc25 100644 --- a/source3/include/smb_macros.h +++ b/source3/include/smb_macros.h @@ -152,7 +152,7 @@ /* the remaining number of bytes in smb buffer 'buf' from pointer 'p'. */ #define smb_bufrem(buf, p) (smb_buflen(buf)-PTR_DIFF(p, smb_buf(buf))) -#define smbreq_bufrem(req, p) (req->buflen - PTR_DIFF(p, req->buf)) +#define smbreq_bufrem(req, p) ((req)->buflen < PTR_DIFF((p), (req)->buf) ? 0 : (req)->buflen - PTR_DIFF((p), (req)->buf)) /* Note that chain_size must be available as an extern int to this macro. */ diff --git a/source3/smbd/reply.c b/source3/smbd/reply.c index d4573d3da55..e1a47a65662 100644 --- a/source3/smbd/reply.c +++ b/source3/smbd/reply.c @@ -345,7 +345,7 @@ size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req, { ssize_t bufrem = smbreq_bufrem(req, src); - if (bufrem < 0) { + if (bufrem == 0) { *err = NT_STATUS_INVALID_PARAMETER; return 0; } @@ -383,7 +383,7 @@ size_t srvstr_pull_req_talloc(TALLOC_CTX *ctx, struct smb_request *req, { ssize_t bufrem = smbreq_bufrem(req, src); - if (bufrem < 0) { + if (bufrem == 0) { return 0; } -- 2.25.1