2 Unix SMB/CIFS implementation.
4 endpoint server for the backupkey interface
6 Copyright (C) Matthieu Patou <mat@samba.org> 2010
7 Copyright (C) Andreas Schneider <asn@samba.org> 2015
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "rpc_server/dcerpc_server.h"
25 #include "librpc/gen_ndr/ndr_backupkey.h"
26 #include "dsdb/common/util.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "lib/ldb/include/ldb_errors.h"
29 #include "../lib/util/util_ldb.h"
30 #include "param/param.h"
31 #include "auth/session.h"
32 #include "system/network.h"
34 #include "../lib/tsocket/tsocket.h"
35 #include "../libcli/security/security.h"
36 #include "librpc/gen_ndr/ndr_security.h"
38 #include <gnutls/gnutls.h>
39 #include <gnutls/x509.h>
40 #include <gnutls/crypto.h>
41 #include <gnutls/abstract.h>
43 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
44 struct ldb_context *ldb,
46 const DATA_BLOB *lsa_secret)
48 struct ldb_message *msg;
49 struct ldb_result *res;
50 struct ldb_dn *domain_dn;
51 struct ldb_dn *system_dn;
55 struct timeval now = timeval_current();
56 NTTIME nt_now = timeval_to_nttime(&now);
57 const char *attrs[] = {
61 domain_dn = ldb_get_default_basedn(ldb);
63 return NT_STATUS_INTERNAL_ERROR;
66 msg = ldb_msg_new(mem_ctx);
68 return NT_STATUS_NO_MEMORY;
72 * This function is a lot like dcesrv_lsa_CreateSecret
73 * in the rpc_server/lsa directory
74 * The reason why we duplicate the effort here is that:
75 * * we want to keep the former function static
76 * * we want to avoid the burden of doing LSA calls
77 * when we can just manipulate the secrets directly
78 * * taillor the function to the particular needs of backup protocol
81 system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
82 if (system_dn == NULL) {
84 return NT_STATUS_NO_MEMORY;
87 name2 = talloc_asprintf(msg, "%s Secret", name);
90 return NT_STATUS_NO_MEMORY;
93 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
94 "(&(cn=%s)(objectclass=secret))",
95 ldb_binary_encode_string(mem_ctx, name2));
97 if (ret != LDB_SUCCESS || res->count != 0 ) {
98 DEBUG(2, ("Secret %s already exists !\n", name2));
100 return NT_STATUS_OBJECT_NAME_COLLISION;
104 * We don't care about previous value as we are
105 * here only if the key didn't exists before
108 msg->dn = ldb_dn_copy(mem_ctx, system_dn);
109 if (msg->dn == NULL) {
111 return NT_STATUS_NO_MEMORY;
113 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
115 return NT_STATUS_NO_MEMORY;
118 ret = ldb_msg_add_string(msg, "cn", name2);
119 if (ret != LDB_SUCCESS) {
121 return NT_STATUS_NO_MEMORY;
123 ret = ldb_msg_add_string(msg, "objectClass", "secret");
124 if (ret != LDB_SUCCESS) {
126 return NT_STATUS_NO_MEMORY;
128 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
129 if (ret != LDB_SUCCESS) {
131 return NT_STATUS_NO_MEMORY;
133 val.data = lsa_secret->data;
134 val.length = lsa_secret->length;
135 ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
136 if (ret != LDB_SUCCESS) {
138 return NT_STATUS_NO_MEMORY;
140 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
141 if (ret != LDB_SUCCESS) {
143 return NT_STATUS_NO_MEMORY;
147 * create the secret with DSDB_MODIFY_RELAX
148 * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
149 * the create of LSA secret object
151 ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
152 if (ret != LDB_SUCCESS) {
153 DEBUG(2,("Failed to create secret record %s: %s\n",
154 ldb_dn_get_linearized(msg->dn),
155 ldb_errstring(ldb)));
157 return NT_STATUS_ACCESS_DENIED;
164 /* This function is pretty much like dcesrv_lsa_QuerySecret */
165 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
166 struct ldb_context *ldb,
168 DATA_BLOB *lsa_secret)
171 struct ldb_result *res;
172 struct ldb_dn *domain_dn;
173 struct ldb_dn *system_dn;
174 const struct ldb_val *val;
176 const char *attrs[] = {
182 lsa_secret->data = NULL;
183 lsa_secret->length = 0;
185 domain_dn = ldb_get_default_basedn(ldb);
187 return NT_STATUS_INTERNAL_ERROR;
190 tmp_mem = talloc_new(mem_ctx);
191 if (tmp_mem == NULL) {
192 return NT_STATUS_NO_MEMORY;
195 system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
196 if (system_dn == NULL) {
197 talloc_free(tmp_mem);
198 return NT_STATUS_NO_MEMORY;
201 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
202 "(&(cn=%s Secret)(objectclass=secret))",
203 ldb_binary_encode_string(tmp_mem, name));
205 if (ret != LDB_SUCCESS) {
206 talloc_free(tmp_mem);
207 return NT_STATUS_INTERNAL_DB_CORRUPTION;
209 if (res->count == 0) {
210 talloc_free(tmp_mem);
211 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
213 if (res->count > 1) {
214 DEBUG(2, ("Secret %s collision\n", name));
215 talloc_free(tmp_mem);
216 return NT_STATUS_INTERNAL_DB_CORRUPTION;
219 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
222 * The secret object is here but we don't have the secret value
223 * The most common case is a RODC
225 *lsa_secret = data_blob_null;
226 talloc_free(tmp_mem);
231 lsa_secret->data = talloc_move(mem_ctx, &data);
232 lsa_secret->length = val->length;
234 talloc_free(tmp_mem);
238 static int reverse_and_get_bignum(TALLOC_CTX *mem_ctx,
240 gnutls_datum_t *datum)
244 datum->data = talloc_array(mem_ctx, uint8_t, blob.length);
245 if (datum->data == NULL) {
249 for(i = 0; i < blob.length; i++) {
250 datum->data[i] = blob.data[blob.length - i - 1];
252 datum->size = blob.length;
257 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
258 struct bkrp_exported_RSA_key_pair *keypair,
259 gnutls_privkey_t *pk)
261 gnutls_x509_privkey_t x509_privkey = NULL;
262 gnutls_privkey_t privkey = NULL;
263 gnutls_datum_t m, e, d, p, q, u, e1, e2;
266 rc = reverse_and_get_bignum(ctx, keypair->modulus, &m);
268 return NT_STATUS_INVALID_PARAMETER;
270 rc = reverse_and_get_bignum(ctx, keypair->public_exponent, &e);
272 return NT_STATUS_INVALID_PARAMETER;
274 rc = reverse_and_get_bignum(ctx, keypair->private_exponent, &d);
276 return NT_STATUS_INVALID_PARAMETER;
279 rc = reverse_and_get_bignum(ctx, keypair->prime1, &p);
281 return NT_STATUS_INVALID_PARAMETER;
283 rc = reverse_and_get_bignum(ctx, keypair->prime2, &q);
285 return NT_STATUS_INVALID_PARAMETER;
288 rc = reverse_and_get_bignum(ctx, keypair->coefficient, &u);
290 return NT_STATUS_INVALID_PARAMETER;
293 rc = reverse_and_get_bignum(ctx, keypair->exponent1, &e1);
295 return NT_STATUS_INVALID_PARAMETER;
297 rc = reverse_and_get_bignum(ctx, keypair->exponent2, &e2);
299 return NT_STATUS_INVALID_PARAMETER;
302 rc = gnutls_x509_privkey_init(&x509_privkey);
303 if (rc != GNUTLS_E_SUCCESS) {
304 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
305 gnutls_strerror(rc));
306 return NT_STATUS_INTERNAL_ERROR;
309 rc = gnutls_x509_privkey_import_rsa_raw2(x509_privkey,
318 if (rc != GNUTLS_E_SUCCESS) {
319 DBG_ERR("gnutls_x509_privkey_import_rsa_raw2 failed - %s\n",
320 gnutls_strerror(rc));
321 return NT_STATUS_INTERNAL_ERROR;
324 rc = gnutls_privkey_init(&privkey);
325 if (rc != GNUTLS_E_SUCCESS) {
326 DBG_ERR("gnutls_privkey_init failed - %s\n",
327 gnutls_strerror(rc));
328 gnutls_x509_privkey_deinit(x509_privkey);
329 return NT_STATUS_INTERNAL_ERROR;
332 rc = gnutls_privkey_import_x509(privkey,
334 GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
335 if (rc != GNUTLS_E_SUCCESS) {
336 DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
337 gnutls_strerror(rc));
338 gnutls_x509_privkey_deinit(x509_privkey);
339 return NT_STATUS_INTERNAL_ERROR;
347 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
350 uint8_t *access_check,
351 uint32_t access_check_len,
352 struct auth_session_info *session_info)
354 gnutls_cipher_hd_t cipher_handle = { 0 };
355 gnutls_cipher_algorithm_t cipher_algo;
357 enum ndr_err_code ndr_err;
361 struct dom_sid *access_sid = NULL;
362 struct dom_sid *caller_sid = NULL;
367 cipher_algo = GNUTLS_CIPHER_3DES_CBC;
370 cipher_algo = GNUTLS_CIPHER_AES_256_CBC;
373 return WERR_INVALID_DATA;
376 key.data = key_and_iv;
377 key.size = gnutls_cipher_get_key_size(cipher_algo);
379 iv.data = key_and_iv + key.size;
380 iv.size = gnutls_cipher_get_iv_size(cipher_algo);
382 /* Allocate data structure for the plaintext */
383 blob_us = data_blob_talloc_zero(sub_ctx, access_check_len);
384 if (blob_us.data == NULL) {
385 return WERR_INVALID_DATA;
388 rc = gnutls_cipher_init(&cipher_handle,
393 DBG_ERR("gnutls_cipher_init failed: %s\n",
394 gnutls_strerror(rc));
395 return WERR_INVALID_DATA;
398 rc = gnutls_cipher_decrypt2(cipher_handle,
403 gnutls_cipher_deinit(cipher_handle);
405 DBG_ERR("gnutls_cipher_decrypt2 failed: %s\n",
406 gnutls_strerror(rc));
407 return WERR_INVALID_DATA;
413 uint32_t hash_size = 20;
414 uint8_t hash[hash_size];
415 gnutls_hash_hd_t dig_ctx;
416 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
418 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
419 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
420 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
421 /* Unable to unmarshall */
422 return WERR_INVALID_DATA;
424 if (uncrypted_accesscheckv2.magic != 0x1) {
426 return WERR_INVALID_DATA;
429 gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA1);
432 blob_us.length - hash_size);
433 gnutls_hash_deinit(dig_ctx, hash);
435 * We free it after the sha1 calculation because blob.data
436 * point to the same area
439 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
440 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
441 return WERR_INVALID_DATA;
443 access_sid = &(uncrypted_accesscheckv2.sid);
448 uint32_t hash_size = 64;
449 uint8_t hash[hash_size];
450 gnutls_hash_hd_t dig_ctx;
451 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
453 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
454 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
455 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
456 /* Unable to unmarshall */
457 return WERR_INVALID_DATA;
459 if (uncrypted_accesscheckv3.magic != 0x1) {
461 return WERR_INVALID_DATA;
464 gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA512);
467 blob_us.length - hash_size);
468 gnutls_hash_deinit(dig_ctx, hash);
471 * We free it after the sha1 calculation because blob.data
472 * point to the same area
475 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
476 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
477 return WERR_INVALID_DATA;
479 access_sid = &(uncrypted_accesscheckv3.sid);
483 /* Never reached normally as we filtered at the switch / case level */
484 return WERR_INVALID_DATA;
487 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
489 if (!dom_sid_equal(caller_sid, access_sid)) {
490 return WERR_INVALID_ACCESS;
496 * We have some data, such as saved website or IMAP passwords that the
497 * client has in profile on-disk. This needs to be decrypted. This
498 * version gives the server the data over the network (protected by
499 * the X.509 certificate and public key encryption, and asks that it
500 * be decrypted returned for short-term use, protected only by the
501 * negotiated transport encryption.
503 * The data is NOT stored in the LSA, but a X.509 certificate, public
504 * and private keys used to encrypt the data will be stored. There is
505 * only one active encryption key pair and certificate per domain, it
506 * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
508 * The potentially multiple valid decrypting key pairs are in turn
509 * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
512 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
514 struct bkrp_BackupKey *r,
515 struct ldb_context *ldb_ctx)
517 struct bkrp_client_side_wrapped uncrypt_request;
519 enum ndr_err_code ndr_err;
521 char *cert_secret_name;
522 DATA_BLOB lsa_secret;
523 DATA_BLOB *uncrypted_data = NULL;
525 uint32_t requested_version;
527 blob.data = r->in.data_in;
528 blob.length = r->in.data_in_len;
530 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
531 return WERR_INVALID_PARAM;
535 * We check for the version here, so we can actually print the
536 * message as we are unlikely to parse it with NDR.
538 requested_version = IVAL(r->in.data_in, 0);
539 if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
540 && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
541 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
542 return WERR_INVALID_PARAMETER;
545 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
546 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
547 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
548 return WERR_INVALID_PARAM;
551 if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
552 && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
553 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
554 return WERR_INVALID_PARAMETER;
557 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
558 if (guid_string == NULL) {
562 cert_secret_name = talloc_asprintf(mem_ctx,
565 if (cert_secret_name == NULL) {
569 status = get_lsa_secret(mem_ctx,
573 if (!NT_STATUS_IS_OK(status)) {
574 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
575 return WERR_INVALID_DATA;
576 } else if (lsa_secret.length == 0) {
577 /* we do not have the real secret attribute, like if we are an RODC */
578 return WERR_INVALID_PARAMETER;
580 struct bkrp_exported_RSA_key_pair keypair;
581 gnutls_privkey_t privkey = NULL;
582 gnutls_datum_t reversed_secret;
583 gnutls_datum_t uncrypted_secret;
589 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
590 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
591 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
592 return WERR_FILE_NOT_FOUND;
595 status = get_pk_from_raw_keypair_params(mem_ctx,
598 if (!NT_STATUS_IS_OK(status)) {
599 return WERR_INTERNAL_ERROR;
602 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
603 uncrypt_request.encrypted_secret_len);
604 if (reversed_secret.data == NULL) {
605 gnutls_privkey_deinit(privkey);
609 /* The secret has to be reversed ... */
610 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
611 uint8_t *reversed = (uint8_t *)reversed_secret.data;
612 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
613 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
615 reversed_secret.size = uncrypt_request.encrypted_secret_len;
618 * Let's try to decrypt the secret now that
619 * we have the private key ...
621 rc = gnutls_privkey_decrypt_data(privkey,
625 gnutls_privkey_deinit(privkey);
626 if (rc != GNUTLS_E_SUCCESS) {
627 /* We are not able to decrypt the secret, looks like something is wrong */
628 return WERR_INVALID_PARAMETER;
630 blob_us.data = uncrypted_secret.data;
631 blob_us.length = uncrypted_secret.size;
633 if (uncrypt_request.version == 2) {
634 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
636 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
637 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
638 gnutls_free(uncrypted_secret.data);
639 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
640 /* Unable to unmarshall */
641 return WERR_INVALID_DATA;
643 if (uncrypted_secretv2.magic != 0x20) {
645 return WERR_INVALID_DATA;
648 werr = get_and_verify_access_check(mem_ctx, 2,
649 uncrypted_secretv2.payload_key,
650 uncrypt_request.access_check,
651 uncrypt_request.access_check_len,
652 dce_call->conn->auth_state.session_info);
653 if (!W_ERROR_IS_OK(werr)) {
656 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
657 if (uncrypted_data == NULL) {
658 return WERR_INVALID_DATA;
661 uncrypted_data->data = uncrypted_secretv2.secret;
662 uncrypted_data->length = uncrypted_secretv2.secret_len;
664 if (uncrypt_request.version == 3) {
665 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
667 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
668 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
669 gnutls_free(uncrypted_secret.data);
670 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
671 /* Unable to unmarshall */
672 return WERR_INVALID_DATA;
675 if (uncrypted_secretv3.magic1 != 0x30 ||
676 uncrypted_secretv3.magic2 != 0x6610 ||
677 uncrypted_secretv3.magic3 != 0x800e) {
679 return WERR_INVALID_DATA;
683 * Confirm that the caller is permitted to
684 * read this particular data. Because one key
685 * pair is used per domain, the caller could
686 * have stolen the profile data on-disk and
687 * would otherwise be able to read the
691 werr = get_and_verify_access_check(mem_ctx, 3,
692 uncrypted_secretv3.payload_key,
693 uncrypt_request.access_check,
694 uncrypt_request.access_check_len,
695 dce_call->conn->auth_state.session_info);
696 if (!W_ERROR_IS_OK(werr)) {
700 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
701 if (uncrypted_data == NULL) {
702 return WERR_INVALID_DATA;
705 uncrypted_data->data = uncrypted_secretv3.secret;
706 uncrypted_data->length = uncrypted_secretv3.secret_len;
710 * Yeah if we are here all looks pretty good:
712 * - user sid is the same as the one in access check
713 * - we were able to decrypt the whole stuff
717 if (uncrypted_data->data == NULL) {
718 return WERR_INVALID_DATA;
721 /* There is a magic value a the beginning of the data
722 * we can use an adhoc structure but as the
723 * parent structure is just an array of bytes it a lot of work
724 * work just prepending 4 bytes
726 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
727 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
728 memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
729 *(r->out.data_out_len) = uncrypted_data->length + 4;
734 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx,
735 gnutls_datum_t *datum)
740 blob = talloc(mem_ctx, DATA_BLOB);
745 blob->length = datum->size;
746 if (datum->data[0] == '\0') {
747 /* The datum has a leading byte zero, skip it */
748 blob->length = datum->size - 1;
750 blob->data = talloc_zero_array(mem_ctx, uint8_t, blob->length);
751 if (blob->data == NULL) {
756 for (i = 0; i < blob->length; i++) {
757 blob->data[i] = datum->data[datum->size - i - 1];
763 static WERROR create_privkey_rsa(gnutls_privkey_t *pk)
766 gnutls_x509_privkey_t x509_privkey = NULL;
767 gnutls_privkey_t privkey = NULL;
770 rc = gnutls_x509_privkey_init(&x509_privkey);
771 if (rc != GNUTLS_E_SUCCESS) {
772 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
773 gnutls_strerror(rc));
774 return WERR_INTERNAL_ERROR;
777 rc = gnutls_x509_privkey_generate(x509_privkey,
781 if (rc != GNUTLS_E_SUCCESS) {
782 DBG_ERR("gnutls_x509_privkey_generate failed - %s\n",
783 gnutls_strerror(rc));
784 gnutls_x509_privkey_deinit(x509_privkey);
785 return WERR_INTERNAL_ERROR;
788 rc = gnutls_privkey_init(&privkey);
789 if (rc != GNUTLS_E_SUCCESS) {
790 DBG_ERR("gnutls_privkey_init failed - %s\n",
791 gnutls_strerror(rc));
792 gnutls_x509_privkey_deinit(x509_privkey);
793 return WERR_INTERNAL_ERROR;
796 rc = gnutls_privkey_import_x509(privkey,
798 GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
799 if (rc != GNUTLS_E_SUCCESS) {
800 DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
801 gnutls_strerror(rc));
802 gnutls_x509_privkey_deinit(x509_privkey);
803 return WERR_INTERNAL_ERROR;
811 static WERROR self_sign_cert(TALLOC_CTX *mem_ctx,
814 gnutls_privkey_t issuer_privkey,
815 gnutls_x509_crt_t *certificate,
818 gnutls_datum_t unique_id;
819 gnutls_datum_t serial_number;
820 gnutls_x509_crt_t issuer_cert;
821 gnutls_x509_privkey_t x509_issuer_privkey;
822 time_t activation = time(NULL);
823 time_t expiry = activation + lifetime;
824 const char *error_string;
829 unique_id.size = guidblob->length;
830 unique_id.data = talloc_memdup(mem_ctx,
833 if (unique_id.data == NULL) {
837 reversed = talloc_array(mem_ctx, uint8_t, guidblob->length);
838 if (reversed == NULL) {
839 talloc_free(unique_id.data);
843 /* Native AD generates certificates with serialnumber in reversed notation */
844 for (i = 0; i < guidblob->length; i++) {
845 uint8_t *uncrypt = guidblob->data;
846 reversed[i] = uncrypt[guidblob->length - i - 1];
848 serial_number.size = guidblob->length;
849 serial_number.data = reversed;
851 /* Create certificate to sign */
852 rc = gnutls_x509_crt_init(&issuer_cert);
853 if (rc != GNUTLS_E_SUCCESS) {
854 DBG_ERR("gnutls_x509_crt_init failed - %s\n",
855 gnutls_strerror(rc));
859 rc = gnutls_x509_crt_set_dn(issuer_cert, dn, &error_string);
860 if (rc != GNUTLS_E_SUCCESS) {
861 DBG_ERR("gnutls_x509_crt_set_dn failed - %s (%s)\n",
864 gnutls_x509_crt_deinit(issuer_cert);
865 return WERR_INVALID_PARAM;
868 rc = gnutls_x509_crt_set_issuer_dn(issuer_cert, dn, &error_string);
869 if (rc != GNUTLS_E_SUCCESS) {
870 DBG_ERR("gnutls_x509_crt_set_issuer_dn failed - %s (%s)\n",
873 gnutls_x509_crt_deinit(issuer_cert);
874 return WERR_INVALID_PARAM;
877 /* Get x509 privkey for subjectPublicKeyInfo */
878 rc = gnutls_x509_privkey_init(&x509_issuer_privkey);
879 if (rc != GNUTLS_E_SUCCESS) {
880 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
881 gnutls_strerror(rc));
882 gnutls_x509_crt_deinit(issuer_cert);
883 return WERR_INVALID_PARAM;
886 rc = gnutls_privkey_export_x509(issuer_privkey,
887 &x509_issuer_privkey);
888 if (rc != GNUTLS_E_SUCCESS) {
889 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
890 gnutls_strerror(rc));
891 gnutls_x509_privkey_deinit(x509_issuer_privkey);
892 gnutls_x509_crt_deinit(issuer_cert);
893 return WERR_INVALID_PARAM;
896 /* Set subjectPublicKeyInfo */
897 rc = gnutls_x509_crt_set_key(issuer_cert, x509_issuer_privkey);
898 gnutls_x509_privkey_deinit(x509_issuer_privkey);
899 if (rc != GNUTLS_E_SUCCESS) {
900 DBG_ERR("gnutls_x509_crt_set_pubkey failed - %s\n",
901 gnutls_strerror(rc));
902 gnutls_x509_crt_deinit(issuer_cert);
903 return WERR_INVALID_PARAM;
906 rc = gnutls_x509_crt_set_activation_time(issuer_cert, activation);
907 if (rc != GNUTLS_E_SUCCESS) {
908 DBG_ERR("gnutls_x509_crt_set_activation_time failed - %s\n",
909 gnutls_strerror(rc));
910 gnutls_x509_crt_deinit(issuer_cert);
911 return WERR_INVALID_PARAM;
914 rc = gnutls_x509_crt_set_expiration_time(issuer_cert, expiry);
915 if (rc != GNUTLS_E_SUCCESS) {
916 DBG_ERR("gnutls_x509_crt_set_expiration_time failed - %s\n",
917 gnutls_strerror(rc));
918 gnutls_x509_crt_deinit(issuer_cert);
919 return WERR_INVALID_PARAM;
922 rc = gnutls_x509_crt_set_version(issuer_cert, 3);
923 if (rc != GNUTLS_E_SUCCESS) {
924 DBG_ERR("gnutls_x509_crt_set_version failed - %s\n",
925 gnutls_strerror(rc));
926 gnutls_x509_crt_deinit(issuer_cert);
927 return WERR_INVALID_PARAM;
930 rc = gnutls_x509_crt_set_subject_unique_id(issuer_cert,
933 if (rc != GNUTLS_E_SUCCESS) {
934 DBG_ERR("gnutls_x509_crt_set_subject_key_id failed - %s\n",
935 gnutls_strerror(rc));
936 gnutls_x509_crt_deinit(issuer_cert);
937 return WERR_INVALID_PARAM;
940 rc = gnutls_x509_crt_set_issuer_unique_id(issuer_cert,
943 if (rc != GNUTLS_E_SUCCESS) {
944 DBG_ERR("gnutls_x509_crt_set_issuer_unique_id failed - %s\n",
945 gnutls_strerror(rc));
946 gnutls_x509_crt_deinit(issuer_cert);
947 return WERR_INVALID_PARAM;
950 rc = gnutls_x509_crt_set_serial(issuer_cert,
953 if (rc != GNUTLS_E_SUCCESS) {
954 DBG_ERR("gnutls_x509_crt_set_serial failed - %s\n",
955 gnutls_strerror(rc));
956 gnutls_x509_crt_deinit(issuer_cert);
957 return WERR_INVALID_PARAM;
960 rc = gnutls_x509_crt_privkey_sign(issuer_cert,
965 if (rc != GNUTLS_E_SUCCESS) {
966 DBG_ERR("gnutls_x509_crt_privkey_sign failed - %s\n",
967 gnutls_strerror(rc));
968 return WERR_INVALID_PARAM;
971 *certificate = issuer_cert;
976 /* Return an error when we fail to generate a certificate */
977 static WERROR generate_bkrp_cert(TALLOC_CTX *mem_ctx,
978 struct dcesrv_call_state *dce_call,
979 struct ldb_context *ldb_ctx,
983 gnutls_privkey_t issuer_privkey = NULL;
984 gnutls_x509_crt_t cert = NULL;
985 gnutls_datum_t cert_blob;
986 gnutls_datum_t m, e, d, p, q, u, e1, e2;
988 DATA_BLOB blobkeypair;
991 struct GUID guid = GUID_random();
994 struct bkrp_exported_RSA_key_pair keypair;
995 enum ndr_err_code ndr_err;
996 time_t nb_seconds_validity = 3600 * 24 * 365;
999 DEBUG(6, ("Trying to generate a certificate\n"));
1000 werr = create_privkey_rsa(&issuer_privkey);
1001 if (!W_ERROR_IS_OK(werr)) {
1005 status = GUID_to_ndr_blob(&guid, mem_ctx, &blob);
1006 if (!NT_STATUS_IS_OK(status)) {
1007 gnutls_privkey_deinit(issuer_privkey);
1008 return WERR_INVALID_DATA;
1011 werr = self_sign_cert(mem_ctx,
1012 nb_seconds_validity,
1017 if (!W_ERROR_IS_OK(werr)) {
1018 gnutls_privkey_deinit(issuer_privkey);
1019 return WERR_INVALID_DATA;
1022 rc = gnutls_x509_crt_export2(cert, GNUTLS_X509_FMT_DER, &cert_blob);
1023 if (rc != GNUTLS_E_SUCCESS) {
1024 DBG_ERR("gnutls_x509_crt_export2 failed - %s\n",
1025 gnutls_strerror(rc));
1026 gnutls_privkey_deinit(issuer_privkey);
1027 gnutls_x509_crt_deinit(cert);
1028 return WERR_INVALID_DATA;
1031 keypair.cert.length = cert_blob.size;
1032 keypair.cert.data = talloc_memdup(mem_ctx, cert_blob.data, cert_blob.size);
1033 gnutls_x509_crt_deinit(cert);
1034 gnutls_free(cert_blob.data);
1035 if (keypair.cert.data == NULL) {
1036 gnutls_privkey_deinit(issuer_privkey);
1040 rc = gnutls_privkey_export_rsa_raw(issuer_privkey,
1049 if (rc != GNUTLS_E_SUCCESS) {
1050 gnutls_privkey_deinit(issuer_privkey);
1051 return WERR_INVALID_DATA;
1055 * Heimdal's bignum are big endian and the
1056 * structure expect it to be in little endian
1057 * so we reverse the buffer to make it work
1059 tmp = reverse_and_get_blob(mem_ctx, &e);
1063 SMB_ASSERT(tmp->length <= 4);
1064 keypair.public_exponent = *tmp;
1067 tmp = reverse_and_get_blob(mem_ctx, &d);
1071 keypair.private_exponent = *tmp;
1074 tmp = reverse_and_get_blob(mem_ctx, &m);
1078 keypair.modulus = *tmp;
1081 tmp = reverse_and_get_blob(mem_ctx, &p);
1085 keypair.prime1 = *tmp;
1088 tmp = reverse_and_get_blob(mem_ctx, &q);
1092 keypair.prime2 = *tmp;
1095 tmp = reverse_and_get_blob(mem_ctx, &e1);
1099 keypair.exponent1 = *tmp;
1102 tmp = reverse_and_get_blob(mem_ctx, &e2);
1106 keypair.exponent2 = *tmp;
1109 tmp = reverse_and_get_blob(mem_ctx, &u);
1113 keypair.coefficient = *tmp;
1116 /* One of the keypair allocation was wrong */
1118 gnutls_privkey_deinit(issuer_privkey);
1119 return WERR_INVALID_DATA;
1122 keypair.certificate_len = keypair.cert.length;
1123 ndr_err = ndr_push_struct_blob(&blobkeypair,
1126 (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1127 gnutls_privkey_deinit(issuer_privkey);
1128 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1129 return WERR_INVALID_DATA;
1132 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", GUID_string(mem_ctx, &guid));
1133 if (secret_name == NULL) {
1134 return WERR_OUTOFMEMORY;
1137 status = set_lsa_secret(mem_ctx, ldb_ctx, secret_name, &blobkeypair);
1138 if (!NT_STATUS_IS_OK(status)) {
1139 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1141 talloc_free(secret_name);
1143 GUID_to_ndr_blob(&guid, mem_ctx, &blob);
1144 status = set_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1145 if (!NT_STATUS_IS_OK(status)) {
1146 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1152 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1153 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1157 DATA_BLOB lsa_secret;
1158 enum ndr_err_code ndr_err;
1162 * here we basicaly need to return our certificate
1163 * search for lsa secret BCKUPKEY_PREFERRED first
1166 status = get_lsa_secret(mem_ctx,
1168 "BCKUPKEY_PREFERRED",
1170 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1171 /* Ok we can be in this case if there was no certs */
1172 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1173 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1174 lpcfg_realm(lp_ctx));
1176 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1177 if (!W_ERROR_IS_OK(werr)) {
1178 return WERR_INVALID_PARAMETER;
1180 status = get_lsa_secret(mem_ctx,
1182 "BCKUPKEY_PREFERRED",
1185 if (!NT_STATUS_IS_OK(status)) {
1186 /* Ok we really don't manage to get this certs ...*/
1187 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1188 return WERR_FILE_NOT_FOUND;
1190 } else if (!NT_STATUS_IS_OK(status)) {
1191 return WERR_INTERNAL_ERROR;
1194 if (lsa_secret.length == 0) {
1195 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1196 return WERR_INTERNAL_ERROR;
1198 char *cert_secret_name;
1200 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1201 if (!NT_STATUS_IS_OK(status)) {
1202 return WERR_FILE_NOT_FOUND;
1205 guid_string = GUID_string(mem_ctx, &guid);
1206 if (guid_string == NULL) {
1207 /* We return file not found because the client
1210 return WERR_FILE_NOT_FOUND;
1213 cert_secret_name = talloc_asprintf(mem_ctx,
1216 status = get_lsa_secret(mem_ctx,
1220 if (!NT_STATUS_IS_OK(status)) {
1221 return WERR_FILE_NOT_FOUND;
1224 if (lsa_secret.length != 0) {
1225 struct bkrp_exported_RSA_key_pair keypair;
1226 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1227 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1228 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1229 return WERR_FILE_NOT_FOUND;
1231 *(r->out.data_out_len) = keypair.cert.length;
1232 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1233 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1236 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1237 return WERR_INTERNAL_ERROR;
1241 return WERR_NOT_SUPPORTED;
1244 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1246 struct GUID guid = GUID_random();
1247 enum ndr_err_code ndr_err;
1248 DATA_BLOB blob_wrap_key, guid_blob;
1249 struct bkrp_dc_serverwrap_key wrap_key;
1252 TALLOC_CTX *frame = talloc_stackframe();
1254 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1256 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1257 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1259 return WERR_INVALID_DATA;
1262 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1263 if (secret_name == NULL) {
1268 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1269 if (!NT_STATUS_IS_OK(status)) {
1270 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1272 return WERR_INTERNAL_ERROR;
1275 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1276 if (!NT_STATUS_IS_OK(status)) {
1277 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1281 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1282 if (!NT_STATUS_IS_OK(status)) {
1283 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1285 return WERR_INTERNAL_ERROR;
1294 * Find the specified decryption keys from the LSA secrets store as
1295 * G$BCKUPKEY_keyGuidString.
1298 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1299 struct bkrp_dc_serverwrap_key *server_key,
1303 DATA_BLOB lsa_secret;
1306 enum ndr_err_code ndr_err;
1308 guid_string = GUID_string(mem_ctx, guid);
1309 if (guid_string == NULL) {
1310 /* We return file not found because the client
1313 return WERR_FILE_NOT_FOUND;
1316 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1317 if (secret_name == NULL) {
1321 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1322 if (!NT_STATUS_IS_OK(status)) {
1323 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1324 return WERR_INVALID_DATA;
1326 if (lsa_secret.length == 0) {
1327 /* RODC case, we do not have secrets locally */
1328 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1330 return WERR_INTERNAL_ERROR;
1332 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1333 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1334 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1335 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1336 return WERR_INVALID_DATA;
1343 * Find the current, preferred ServerWrap Key by looking at
1344 * G$BCKUPKEY_P in the LSA secrets store.
1346 * Then find the current decryption keys from the LSA secrets store as
1347 * G$BCKUPKEY_keyGuidString.
1350 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1351 struct ldb_context *ldb_ctx,
1352 struct bkrp_dc_serverwrap_key *server_key,
1353 struct GUID *returned_guid)
1356 DATA_BLOB guid_binary;
1358 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1359 if (!NT_STATUS_IS_OK(status)) {
1360 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1361 return WERR_FILE_NOT_FOUND;
1362 } else if (guid_binary.length == 0) {
1363 /* RODC case, we do not have secrets locally */
1364 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1365 return WERR_INTERNAL_ERROR;
1368 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1369 if (!NT_STATUS_IS_OK(status)) {
1370 return WERR_FILE_NOT_FOUND;
1373 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1374 server_key, returned_guid);
1377 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1378 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1381 struct bkrp_server_side_wrapped decrypt_request;
1382 DATA_BLOB sid_blob, encrypted_blob;
1384 enum ndr_err_code ndr_err;
1385 struct bkrp_dc_serverwrap_key server_key;
1386 struct bkrp_rc4encryptedpayload rc4payload;
1387 struct dom_sid *caller_sid;
1388 uint8_t symkey[20]; /* SHA-1 hash len */
1389 uint8_t mackey[20]; /* SHA-1 hash len */
1390 uint8_t mac[20]; /* SHA-1 hash len */
1391 gnutls_hmac_hd_t hmac_hnd;
1392 gnutls_cipher_hd_t cipher_hnd;
1393 gnutls_datum_t cipher_key;
1396 blob.data = r->in.data_in;
1397 blob.length = r->in.data_in_len;
1399 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1400 return WERR_INVALID_PARAM;
1403 ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1404 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1405 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1406 return WERR_INVALID_PARAM;
1409 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1410 return WERR_INVALID_PARAM;
1413 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1414 &decrypt_request.guid);
1415 if (!W_ERROR_IS_OK(werr)) {
1419 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1421 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1424 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1425 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1428 gnutls_hmac_init(&hmac_hnd,
1431 sizeof(server_key.key));
1432 gnutls_hmac(hmac_hnd,
1434 sizeof(decrypt_request.r2));
1435 gnutls_hmac_output(hmac_hnd, symkey);
1437 dump_data_pw("symkey: \n", symkey, sizeof(symkey));
1439 /* rc4 decrypt sid and secret using sym key */
1440 cipher_key.data = symkey;
1441 cipher_key.size = sizeof(symkey);
1443 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1444 decrypt_request.ciphertext_length);
1446 rc = gnutls_cipher_init(&cipher_hnd,
1447 GNUTLS_CIPHER_ARCFOUR_128,
1450 if (rc != GNUTLS_E_SUCCESS) {
1451 DBG_ERR("gnutls_cipher_init failed - %s\n",
1452 gnutls_strerror(rc));
1453 return WERR_INVALID_PARAM;
1455 rc = gnutls_cipher_encrypt2(cipher_hnd,
1456 encrypted_blob.data,
1457 encrypted_blob.length,
1458 encrypted_blob.data,
1459 encrypted_blob.length);
1460 gnutls_cipher_deinit(cipher_hnd);
1461 if (rc != GNUTLS_E_SUCCESS) {
1462 DBG_ERR("gnutls_cipher_encrypt2 failed - %s\n",
1463 gnutls_strerror(rc));
1464 return WERR_INVALID_PARAM;
1467 ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1468 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1469 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1470 return WERR_INVALID_PARAM;
1473 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1474 return WERR_INVALID_PARAM;
1477 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1480 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1481 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1483 gnutls_hmac(hmac_hnd,
1485 sizeof(rc4payload.r3));
1486 gnutls_hmac_deinit(hmac_hnd, mackey);
1488 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1490 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1491 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1492 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1493 return WERR_INTERNAL_ERROR;
1496 gnutls_hmac_init(&hmac_hnd,
1501 gnutls_hmac(hmac_hnd,
1505 gnutls_hmac(hmac_hnd,
1506 rc4payload.secret_data.data,
1507 rc4payload.secret_data.length);
1508 gnutls_hmac_deinit(hmac_hnd, mac);
1510 dump_data_pw("mac: \n", mac, sizeof(mac));
1511 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1513 if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1514 return WERR_INVALID_ACCESS;
1517 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1519 if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1520 return WERR_INVALID_ACCESS;
1523 *(r->out.data_out) = rc4payload.secret_data.data;
1524 *(r->out.data_out_len) = rc4payload.secret_data.length;
1530 * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1531 * determine what type of restore is wanted.
1533 * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1536 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1537 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1539 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1540 return WERR_INVALID_PARAM;
1543 if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1544 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1547 return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1551 * We have some data, such as saved website or IMAP passwords that the
1552 * client would like to put into the profile on-disk. This needs to
1553 * be encrypted. This version gives the server the data over the
1554 * network (protected only by the negotiated transport encryption),
1555 * and asks that it be encrypted and returned for long-term storage.
1557 * The data is NOT stored in the LSA, but a key to encrypt the data
1558 * will be stored. There is only one active encryption key per domain,
1559 * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1561 * The potentially multiple valid decryptiong keys (and the encryption
1562 * key) are in turn stored in the LSA secrets store as
1563 * G$BCKUPKEY_keyGuidString.
1567 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1568 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1570 DATA_BLOB sid_blob, encrypted_blob, server_wrapped_blob;
1572 struct dom_sid *caller_sid;
1573 uint8_t symkey[20]; /* SHA-1 hash len */
1574 uint8_t mackey[20]; /* SHA-1 hash len */
1575 struct bkrp_rc4encryptedpayload rc4payload;
1576 gnutls_hmac_hd_t hmac_hnd;
1577 struct bkrp_dc_serverwrap_key server_key;
1578 enum ndr_err_code ndr_err;
1579 struct bkrp_server_side_wrapped server_side_wrapped;
1581 gnutls_cipher_hd_t cipher_hnd;
1582 gnutls_datum_t cipher_key;
1585 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1586 return WERR_INVALID_PARAM;
1589 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1590 ldb_ctx, &server_key,
1593 if (!W_ERROR_IS_OK(werr)) {
1594 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1595 /* Generate the server wrap key since one wasn't found */
1596 werr = generate_bkrp_server_wrap_key(mem_ctx,
1598 if (!W_ERROR_IS_OK(werr)) {
1599 return WERR_INVALID_PARAMETER;
1601 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1606 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1607 /* Ok we really don't manage to get this secret ...*/
1608 return WERR_FILE_NOT_FOUND;
1611 /* In theory we should NEVER reach this point as it
1612 should only appear in a rodc server */
1613 /* we do not have the real secret attribute */
1614 return WERR_INVALID_PARAMETER;
1618 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1620 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1623 * This is the key derivation step, so that the HMAC and RC4
1624 * operations over the user-supplied data are not able to
1625 * disclose the master key. By using random data, the symkey
1626 * and mackey values are unique for this operation, and
1627 * discovering these (by reversing the RC4 over the
1628 * attacker-controlled data) does not return something able to
1629 * be used to decyrpt the encrypted data of other users
1631 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1633 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1635 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1637 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1641 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1642 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1644 gnutls_hmac_init(&hmac_hnd,
1647 sizeof(server_key.key));
1648 gnutls_hmac(hmac_hnd,
1649 server_side_wrapped.r2,
1650 sizeof(server_side_wrapped.r2));
1651 gnutls_hmac_output(hmac_hnd, symkey);
1653 dump_data_pw("symkey: \n", symkey, sizeof(symkey));
1656 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1657 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1659 gnutls_hmac(hmac_hnd,
1661 sizeof(rc4payload.r3));
1662 gnutls_hmac_deinit(hmac_hnd, mackey);
1664 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1666 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1667 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1668 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1669 return WERR_INTERNAL_ERROR;
1672 rc4payload.secret_data.data = r->in.data_in;
1673 rc4payload.secret_data.length = r->in.data_in_len;
1675 gnutls_hmac_init(&hmac_hnd,
1680 gnutls_hmac(hmac_hnd,
1684 gnutls_hmac(hmac_hnd,
1685 rc4payload.secret_data.data,
1686 rc4payload.secret_data.length);
1687 gnutls_hmac_deinit(hmac_hnd, rc4payload.mac);
1689 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1691 rc4payload.sid = *caller_sid;
1693 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1694 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1695 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1696 return WERR_INTERNAL_ERROR;
1699 /* rc4 encrypt sid and secret using sym key */
1700 cipher_key.data = symkey;
1701 cipher_key.size = sizeof(symkey);
1703 rc = gnutls_cipher_init(&cipher_hnd,
1704 GNUTLS_CIPHER_ARCFOUR_128,
1707 if (rc != GNUTLS_E_SUCCESS) {
1708 DBG_ERR("gnutls_cipher_init failed - %s\n",
1709 gnutls_strerror(rc));
1710 return WERR_INVALID_PARAM;
1712 rc = gnutls_cipher_encrypt2(cipher_hnd,
1713 encrypted_blob.data,
1714 encrypted_blob.length,
1715 encrypted_blob.data,
1716 encrypted_blob.length);
1717 gnutls_cipher_deinit(cipher_hnd);
1718 if (rc != GNUTLS_E_SUCCESS) {
1719 DBG_ERR("gnutls_cipher_encrypt2 failed - %s\n",
1720 gnutls_strerror(rc));
1721 return WERR_INVALID_PARAM;
1724 /* create server wrap structure */
1726 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1727 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1728 server_side_wrapped.guid = guid;
1729 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1731 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1732 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1733 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1734 return WERR_INTERNAL_ERROR;
1737 *(r->out.data_out) = server_wrapped_blob.data;
1738 *(r->out.data_out_len) = server_wrapped_blob.length;
1743 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1744 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1746 WERROR error = WERR_INVALID_PARAM;
1747 struct ldb_context *ldb_ctx;
1749 const char *addr = "unknown";
1750 /* At which level we start to add more debug of what is done in the protocol */
1751 const int debuglevel = 4;
1753 gnutls_global_init();
1755 if (DEBUGLVL(debuglevel)) {
1756 const struct tsocket_address *remote_address;
1757 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1758 if (tsocket_address_is_inet(remote_address, "ip")) {
1759 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1760 W_ERROR_HAVE_NO_MEMORY(addr);
1764 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1765 return WERR_NOT_SUPPORTED;
1768 if (!dce_call->conn->auth_state.auth_info ||
1769 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1770 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1773 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1774 dce_call->conn->dce_ctx->lp_ctx,
1775 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1777 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1778 talloc_unlink(mem_ctx, ldb_ctx);
1779 return WERR_INVALID_PARAM;
1783 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1784 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1785 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1786 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1789 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1790 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1791 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1792 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1795 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1796 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1797 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1798 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1801 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1802 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1803 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1804 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1807 /*else: I am a RODC so I don't handle backup key protocol */
1809 gnutls_global_deinit();
1810 talloc_unlink(mem_ctx, ldb_ctx);
1814 /* include the generated boilerplate */
1815 #include "librpc/gen_ndr/ndr_backupkey_s.c"