2 Unix SMB/CIFS implementation.
4 endpoint server for the backupkey interface
6 Copyright (C) Matthieu Patou <mat@samba.org> 2010
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "rpc_server/dcerpc_server.h"
24 #include "librpc/gen_ndr/ndr_backupkey.h"
25 #include "dsdb/common/util.h"
26 #include "dsdb/samdb/samdb.h"
27 #include "lib/ldb/include/ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "param/param.h"
30 #include "auth/session.h"
31 #include "system/network.h"
34 #include <hcrypto/rsa.h>
35 #include <hcrypto/bn.h>
36 #include <hcrypto/sha.h>
37 #include <hcrypto/evp.h>
38 #include <hcrypto/hmac.h>
40 #include "../lib/tsocket/tsocket.h"
41 #include "../libcli/security/security.h"
42 #include "librpc/gen_ndr/ndr_security.h"
43 #include "lib/crypto/arcfour.h"
44 #include <gnutls/gnutls.h>
45 #include <gnutls/x509.h>
46 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
51 static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
52 /* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
53 static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
54 { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
57 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
58 struct ldb_context *ldb,
60 const DATA_BLOB *lsa_secret)
62 struct ldb_message *msg;
63 struct ldb_result *res;
64 struct ldb_dn *domain_dn;
65 struct ldb_dn *system_dn;
69 struct timeval now = timeval_current();
70 NTTIME nt_now = timeval_to_nttime(&now);
71 const char *attrs[] = {
75 domain_dn = ldb_get_default_basedn(ldb);
77 return NT_STATUS_INTERNAL_ERROR;
80 msg = ldb_msg_new(mem_ctx);
82 return NT_STATUS_NO_MEMORY;
86 * This function is a lot like dcesrv_lsa_CreateSecret
87 * in the rpc_server/lsa directory
88 * The reason why we duplicate the effort here is that:
89 * * we want to keep the former function static
90 * * we want to avoid the burden of doing LSA calls
91 * when we can just manipulate the secrets directly
92 * * taillor the function to the particular needs of backup protocol
95 system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
96 if (system_dn == NULL) {
98 return NT_STATUS_NO_MEMORY;
101 name2 = talloc_asprintf(msg, "%s Secret", name);
104 return NT_STATUS_NO_MEMORY;
107 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
108 "(&(cn=%s)(objectclass=secret))",
109 ldb_binary_encode_string(mem_ctx, name2));
111 if (ret != LDB_SUCCESS || res->count != 0 ) {
112 DEBUG(2, ("Secret %s already exists !\n", name2));
114 return NT_STATUS_OBJECT_NAME_COLLISION;
118 * We don't care about previous value as we are
119 * here only if the key didn't exists before
122 msg->dn = ldb_dn_copy(mem_ctx, system_dn);
123 if (msg->dn == NULL) {
125 return NT_STATUS_NO_MEMORY;
127 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
129 return NT_STATUS_NO_MEMORY;
132 ret = ldb_msg_add_string(msg, "cn", name2);
133 if (ret != LDB_SUCCESS) {
135 return NT_STATUS_NO_MEMORY;
137 ret = ldb_msg_add_string(msg, "objectClass", "secret");
138 if (ret != LDB_SUCCESS) {
140 return NT_STATUS_NO_MEMORY;
142 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
143 if (ret != LDB_SUCCESS) {
145 return NT_STATUS_NO_MEMORY;
147 val.data = lsa_secret->data;
148 val.length = lsa_secret->length;
149 ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
150 if (ret != LDB_SUCCESS) {
152 return NT_STATUS_NO_MEMORY;
154 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
155 if (ret != LDB_SUCCESS) {
157 return NT_STATUS_NO_MEMORY;
161 * create the secret with DSDB_MODIFY_RELAX
162 * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
163 * the create of LSA secret object
165 ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
166 if (ret != LDB_SUCCESS) {
167 DEBUG(2,("Failed to create secret record %s: %s\n",
168 ldb_dn_get_linearized(msg->dn),
169 ldb_errstring(ldb)));
171 return NT_STATUS_ACCESS_DENIED;
178 /* This function is pretty much like dcesrv_lsa_QuerySecret */
179 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
180 struct ldb_context *ldb,
182 DATA_BLOB *lsa_secret)
185 struct ldb_result *res;
186 struct ldb_dn *domain_dn;
187 struct ldb_dn *system_dn;
188 const struct ldb_val *val;
190 const char *attrs[] = {
196 lsa_secret->data = NULL;
197 lsa_secret->length = 0;
199 domain_dn = ldb_get_default_basedn(ldb);
201 return NT_STATUS_INTERNAL_ERROR;
204 tmp_mem = talloc_new(mem_ctx);
205 if (tmp_mem == NULL) {
206 return NT_STATUS_NO_MEMORY;
209 system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
210 if (system_dn == NULL) {
211 talloc_free(tmp_mem);
212 return NT_STATUS_NO_MEMORY;
215 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
216 "(&(cn=%s Secret)(objectclass=secret))",
217 ldb_binary_encode_string(tmp_mem, name));
219 if (ret != LDB_SUCCESS) {
220 talloc_free(tmp_mem);
221 return NT_STATUS_INTERNAL_DB_CORRUPTION;
223 if (res->count == 0) {
224 talloc_free(tmp_mem);
225 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
227 if (res->count > 1) {
228 DEBUG(2, ("Secret %s collision\n", name));
229 talloc_free(tmp_mem);
230 return NT_STATUS_INTERNAL_DB_CORRUPTION;
233 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
236 * The secret object is here but we don't have the secret value
237 * The most common case is a RODC
239 *lsa_secret = data_blob_null;
240 talloc_free(tmp_mem);
245 lsa_secret->data = talloc_move(mem_ctx, &data);
246 lsa_secret->length = val->length;
248 talloc_free(tmp_mem);
252 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
255 DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
258 blob.length = BN_num_bytes(bn);
259 blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
261 if (blob.data == NULL) {
265 BN_bn2bin(bn, blob.data);
267 rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
268 if (rev->data == NULL) {
272 for(i=0; i < blob.length; i++) {
273 rev->data[i] = blob.data[blob.length - i -1];
275 rev->length = blob.length;
276 talloc_free(blob.data);
280 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
286 rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
287 if (rev.data == NULL) {
291 for(i=0; i < blob->length; i++) {
292 rev.data[i] = blob->data[blob->length - i -1];
294 rev.length = blob->length;
296 ret = BN_bin2bn(rev.data, rev.length, NULL);
297 talloc_free(rev.data);
302 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
303 struct bkrp_exported_RSA_key_pair *keypair,
304 hx509_private_key *pk)
308 struct hx509_private_key_ops *ops;
309 hx509_private_key privkey = NULL;
311 hx509_context_init(&hctx);
312 ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
314 DEBUG(2, ("Not supported algorithm\n"));
315 hx509_context_free(&hctx);
316 return NT_STATUS_INTERNAL_ERROR;
319 if (hx509_private_key_init(&privkey, ops, NULL) != 0) {
320 hx509_context_free(&hctx);
321 return NT_STATUS_NO_MEMORY;
326 hx509_private_key_free(&privkey);
327 hx509_context_free(&hctx);
328 return NT_STATUS_INVALID_PARAMETER;
331 rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
332 if (rsa->n == NULL) {
334 hx509_private_key_free(&privkey);
335 hx509_context_free(&hctx);
336 return NT_STATUS_INVALID_PARAMETER;
338 rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
339 if (rsa->d == NULL) {
341 hx509_private_key_free(&privkey);
342 hx509_context_free(&hctx);
343 return NT_STATUS_INVALID_PARAMETER;
345 rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
346 if (rsa->p == NULL) {
348 hx509_private_key_free(&privkey);
349 hx509_context_free(&hctx);
350 return NT_STATUS_INVALID_PARAMETER;
352 rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
353 if (rsa->q == NULL) {
355 hx509_private_key_free(&privkey);
356 hx509_context_free(&hctx);
357 return NT_STATUS_INVALID_PARAMETER;
359 rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
360 if (rsa->dmp1 == NULL) {
362 hx509_private_key_free(&privkey);
363 hx509_context_free(&hctx);
364 return NT_STATUS_INVALID_PARAMETER;
366 rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
367 if (rsa->dmq1 == NULL) {
369 hx509_private_key_free(&privkey);
370 hx509_context_free(&hctx);
371 return NT_STATUS_INVALID_PARAMETER;
373 rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
374 if (rsa->iqmp == NULL) {
376 hx509_private_key_free(&privkey);
377 hx509_context_free(&hctx);
378 return NT_STATUS_INVALID_PARAMETER;
380 rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
381 if (rsa->e == NULL) {
383 hx509_private_key_free(&privkey);
384 hx509_context_free(&hctx);
385 return NT_STATUS_INVALID_PARAMETER;
390 hx509_private_key_assign_rsa(*pk, rsa);
392 hx509_context_free(&hctx);
396 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
399 uint8_t *access_check,
400 uint32_t access_check_len,
401 struct auth_session_info *session_info)
403 heim_octet_string iv;
404 heim_octet_string access_check_os;
411 enum ndr_err_code ndr_err;
414 struct dom_sid *access_sid = NULL;
415 struct dom_sid *caller_sid = NULL;
417 /* This one should not be freed */
418 const AlgorithmIdentifier *alg;
424 alg = hx509_crypto_des_rsdi_ede3_cbc();
430 alg =hx509_crypto_aes256_cbc();
434 return WERR_INVALID_DATA;
437 hx509_context_init(&hctx);
438 res = hx509_crypto_init(hctx, NULL,
441 hx509_context_free(&hctx);
444 return WERR_INVALID_DATA;
447 res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
449 iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
453 hx509_crypto_destroy(crypto);
454 return WERR_INVALID_DATA;
457 hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
458 res = hx509_crypto_decrypt(crypto,
465 hx509_crypto_destroy(crypto);
466 return WERR_INVALID_DATA;
469 blob_us.data = access_check_os.data;
470 blob_us.length = access_check_os.length;
472 hx509_crypto_destroy(crypto);
477 uint32_t hash_size = 20;
478 uint8_t hash[hash_size];
480 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
482 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
483 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
484 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
485 /* Unable to unmarshall */
486 der_free_octet_string(&access_check_os);
487 return WERR_INVALID_DATA;
489 if (uncrypted_accesscheckv2.magic != 0x1) {
491 der_free_octet_string(&access_check_os);
492 return WERR_INVALID_DATA;
496 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
497 SHA1_Final(hash, &sctx);
498 der_free_octet_string(&access_check_os);
500 * We free it after the sha1 calculation because blob.data
501 * point to the same area
504 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
505 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
506 return WERR_INVALID_DATA;
508 access_sid = &(uncrypted_accesscheckv2.sid);
513 uint32_t hash_size = 64;
514 uint8_t hash[hash_size];
515 struct hc_sha512state sctx;
516 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
518 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
519 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
520 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
521 /* Unable to unmarshall */
522 der_free_octet_string(&access_check_os);
523 return WERR_INVALID_DATA;
525 if (uncrypted_accesscheckv3.magic != 0x1) {
527 der_free_octet_string(&access_check_os);
528 return WERR_INVALID_DATA;
532 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
533 SHA512_Final(hash, &sctx);
534 der_free_octet_string(&access_check_os);
536 * We free it after the sha1 calculation because blob.data
537 * point to the same area
540 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
541 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
542 return WERR_INVALID_DATA;
544 access_sid = &(uncrypted_accesscheckv3.sid);
548 /* Never reached normally as we filtered at the switch / case level */
549 return WERR_INVALID_DATA;
552 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
554 if (!dom_sid_equal(caller_sid, access_sid)) {
555 return WERR_INVALID_ACCESS;
561 * We have some data, such as saved website or IMAP passwords that the
562 * client has in profile on-disk. This needs to be decrypted. This
563 * version gives the server the data over the network (protected by
564 * the X.509 certificate and public key encryption, and asks that it
565 * be decrypted returned for short-term use, protected only by the
566 * negotiated transport encryption.
568 * The data is NOT stored in the LSA, but a X.509 certificate, public
569 * and private keys used to encrypt the data will be stored. There is
570 * only one active encryption key pair and certificate per domain, it
571 * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
573 * The potentially multiple valid decrypting key pairs are in turn
574 * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
577 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
579 struct bkrp_BackupKey *r,
580 struct ldb_context *ldb_ctx)
582 struct bkrp_client_side_wrapped uncrypt_request;
584 enum ndr_err_code ndr_err;
586 char *cert_secret_name;
587 DATA_BLOB lsa_secret;
588 DATA_BLOB *uncrypted_data = NULL;
590 uint32_t requested_version;
592 blob.data = r->in.data_in;
593 blob.length = r->in.data_in_len;
595 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
596 return WERR_INVALID_PARAM;
600 * We check for the version here, so we can actually print the
601 * message as we are unlikely to parse it with NDR.
603 requested_version = IVAL(r->in.data_in, 0);
604 if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
605 && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
606 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
607 return WERR_INVALID_PARAMETER;
610 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
611 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
612 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
613 return WERR_INVALID_PARAM;
616 if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
617 && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
618 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
619 return WERR_INVALID_PARAMETER;
622 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
623 if (guid_string == NULL) {
627 cert_secret_name = talloc_asprintf(mem_ctx,
630 if (cert_secret_name == NULL) {
634 status = get_lsa_secret(mem_ctx,
638 if (!NT_STATUS_IS_OK(status)) {
639 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
640 return WERR_INVALID_DATA;
641 } else if (lsa_secret.length == 0) {
642 /* we do not have the real secret attribute, like if we are an RODC */
643 return WERR_INVALID_PARAMETER;
646 struct bkrp_exported_RSA_key_pair keypair;
647 hx509_private_key pk;
649 heim_octet_string reversed_secret;
650 heim_octet_string uncrypted_secret;
651 AlgorithmIdentifier alg;
655 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
656 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
657 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
658 return WERR_FILE_NOT_FOUND;
661 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
662 if (!NT_STATUS_IS_OK(status)) {
663 return WERR_INTERNAL_ERROR;
666 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
667 uncrypt_request.encrypted_secret_len);
668 if (reversed_secret.data == NULL) {
669 hx509_private_key_free(&pk);
673 /* The secret has to be reversed ... */
674 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
675 uint8_t *reversed = (uint8_t *)reversed_secret.data;
676 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
677 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
679 reversed_secret.length = uncrypt_request.encrypted_secret_len;
682 * Let's try to decrypt the secret now that
683 * we have the private key ...
685 hx509_context_init(&hctx);
686 res = hx509_private_key_private_decrypt(hctx, &reversed_secret,
689 hx509_context_free(&hctx);
690 hx509_private_key_free(&pk);
692 /* We are not able to decrypt the secret, looks like something is wrong */
693 return WERR_INVALID_PARAMETER;
695 blob_us.data = uncrypted_secret.data;
696 blob_us.length = uncrypted_secret.length;
698 if (uncrypt_request.version == 2) {
699 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
701 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
702 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
703 der_free_octet_string(&uncrypted_secret);
704 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
705 /* Unable to unmarshall */
706 return WERR_INVALID_DATA;
708 if (uncrypted_secretv2.magic != 0x20) {
710 return WERR_INVALID_DATA;
713 werr = get_and_verify_access_check(mem_ctx, 2,
714 uncrypted_secretv2.payload_key,
715 uncrypt_request.access_check,
716 uncrypt_request.access_check_len,
717 dce_call->conn->auth_state.session_info);
718 if (!W_ERROR_IS_OK(werr)) {
721 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
722 if (uncrypted_data == NULL) {
723 return WERR_INVALID_DATA;
726 uncrypted_data->data = uncrypted_secretv2.secret;
727 uncrypted_data->length = uncrypted_secretv2.secret_len;
729 if (uncrypt_request.version == 3) {
730 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
732 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
733 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
735 der_free_octet_string(&uncrypted_secret);
736 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
737 /* Unable to unmarshall */
738 return WERR_INVALID_DATA;
741 if (uncrypted_secretv3.magic1 != 0x30 ||
742 uncrypted_secretv3.magic2 != 0x6610 ||
743 uncrypted_secretv3.magic3 != 0x800e) {
745 return WERR_INVALID_DATA;
749 * Confirm that the caller is permitted to
750 * read this particular data. Because one key
751 * pair is used per domain, the caller could
752 * have stolen the profile data on-disk and
753 * would otherwise be able to read the
757 werr = get_and_verify_access_check(mem_ctx, 3,
758 uncrypted_secretv3.payload_key,
759 uncrypt_request.access_check,
760 uncrypt_request.access_check_len,
761 dce_call->conn->auth_state.session_info);
762 if (!W_ERROR_IS_OK(werr)) {
766 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
767 if (uncrypted_data == NULL) {
768 return WERR_INVALID_DATA;
771 uncrypted_data->data = uncrypted_secretv3.secret;
772 uncrypted_data->length = uncrypted_secretv3.secret_len;
776 * Yeah if we are here all looks pretty good:
778 * - user sid is the same as the one in access check
779 * - we were able to decrypt the whole stuff
783 if (uncrypted_data->data == NULL) {
784 return WERR_INVALID_DATA;
787 /* There is a magic value a the beginning of the data
788 * we can use an adhoc structure but as the
789 * parent structure is just an array of bytes it a lot of work
790 * work just prepending 4 bytes
792 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
793 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
794 memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
795 *(r->out.data_out_len) = uncrypted_data->length + 4;
801 * Strictly, this function no longer uses Heimdal in order to generate an RSA
804 * The resulting key is then imported into Heimdal's RSA structure.
806 * We use GnuTLS because it can reliably generate 2048 bit keys every time.
807 * Windows clients strictly require 2048, no more since it won't fit and no
808 * less either. Heimdal would almost always generate a smaller key.
810 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
811 hx509_private_key *pk, RSA **rsa)
818 int RSA_returned_bits;
819 gnutls_x509_privkey gtls_key;
824 gnutls_global_init();
825 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
826 DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
827 gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
829 ret = gnutls_x509_privkey_init(>ls_key);
831 gnutls_global_deinit();
832 return WERR_INTERNAL_ERROR;
836 * Unlike Heimdal's RSA_generate_key_ex(), this generates a
837 * 2048 bit key 100% of the time. The heimdal code had a ~1/8
838 * chance of doing so, chewing vast quantities of computation
839 * and entropy in the process.
842 ret = gnutls_x509_privkey_generate(gtls_key, GNUTLS_PK_RSA, bits, 0);
844 werr = WERR_INTERNAL_ERROR;
848 /* No need to check error code, this SHOULD fail */
849 gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, NULL, &len);
852 werr = WERR_INTERNAL_ERROR;
856 p0 = talloc_size(ctx, len);
864 * Only this GnuTLS export function correctly exports the key,
865 * we can't use gnutls_rsa_params_export_raw() because while
866 * it appears to be fixed in more recent versions, in the
867 * Ubuntu 14.04 version 2.12.23 (at least) it incorrectly
868 * exports one of the key parameters (qInv). Additionally, we
869 * would have to work around subtle differences in big number
872 * We need access to the RSA parameters directly (in the
873 * parameter RSA **rsa) as the caller has to manually encode
874 * them in a non-standard data structure.
876 ret = gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, p0, &len);
879 werr = WERR_INTERNAL_ERROR;
884 * To dump the key we can use :
885 * rk_dumpdata("h5lkey", p0, len);
887 ret = hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
888 p0, len, HX509_KEY_FORMAT_DER, pk);
891 werr = WERR_INTERNAL_ERROR;
895 *rsa = d2i_RSAPrivateKey(NULL, &p, len);
899 hx509_private_key_free(pk);
900 werr = WERR_INTERNAL_ERROR;
904 RSA_returned_bits = BN_num_bits((*rsa)->n);
905 DEBUG(6, ("GnuTLS returned an RSA private key with %d bits\n", RSA_returned_bits));
907 if (RSA_returned_bits != bits) {
908 DEBUG(0, ("GnuTLS unexpectedly returned an RSA private key with %d bits, needed %d\n", RSA_returned_bits, bits));
909 hx509_private_key_free(pk);
910 werr = WERR_INTERNAL_ERROR;
922 gnutls_x509_privkey_deinit(gtls_key);
923 gnutls_global_deinit();
927 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
928 time_t lifetime, hx509_private_key *private_key,
929 hx509_cert *cert, DATA_BLOB *guidblob)
931 SubjectPublicKeyInfo spki;
932 hx509_name subject = NULL;
934 struct heim_bit_string uniqueid;
935 struct heim_integer serialnumber;
938 uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
939 if (uniqueid.data == NULL) {
942 /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
943 * so as 1 byte is 8 bits we need to provision 8 times more space as in the
946 uniqueid.length = 8 * guidblob->length;
948 serialnumber.data = talloc_array(ctx, uint8_t,
950 if (serialnumber.data == NULL) {
951 talloc_free(uniqueid.data);
955 /* Native AD generates certificates with serialnumber in reversed notation */
956 for (i = 0; i < guidblob->length; i++) {
957 uint8_t *reversed = (uint8_t *)serialnumber.data;
958 uint8_t *uncrypt = guidblob->data;
959 reversed[i] = uncrypt[guidblob->length - 1 - i];
961 serialnumber.length = guidblob->length;
962 serialnumber.negative = 0;
964 memset(&spki, 0, sizeof(spki));
966 ret = hx509_request_get_name(*hctx, *req, &subject);
970 ret = hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
975 ret = hx509_ca_tbs_init(*hctx, &tbs);
980 ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
984 ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
988 ret = hx509_ca_tbs_set_ca(*hctx, tbs, 1);
992 ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
996 ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
1000 ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
1004 ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
1008 hx509_name_free(&subject);
1009 free_SubjectPublicKeyInfo(&spki);
1010 hx509_ca_tbs_free(&tbs);
1015 hx509_ca_tbs_free(&tbs);
1017 free_SubjectPublicKeyInfo(&spki);
1019 hx509_name_free(&subject);
1021 talloc_free(uniqueid.data);
1022 talloc_free(serialnumber.data);
1023 return WERR_INTERNAL_ERROR;
1026 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
1027 hx509_private_key *signer,RSA **rsa, const char *dn)
1030 SubjectPublicKeyInfo key;
1035 werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1036 if (!W_ERROR_IS_OK(werr)) {
1040 hx509_request_init(*hctx, req);
1041 ret = hx509_parse_name(*hctx, dn, &name);
1044 hx509_private_key_free(signer);
1045 hx509_request_free(req);
1046 hx509_name_free(&name);
1047 return WERR_INTERNAL_ERROR;
1050 ret = hx509_request_set_name(*hctx, *req, name);
1053 hx509_private_key_free(signer);
1054 hx509_request_free(req);
1055 hx509_name_free(&name);
1056 return WERR_INTERNAL_ERROR;
1058 hx509_name_free(&name);
1060 ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1063 hx509_private_key_free(signer);
1064 hx509_request_free(req);
1065 return WERR_INTERNAL_ERROR;
1067 ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1070 hx509_private_key_free(signer);
1071 free_SubjectPublicKeyInfo(&key);
1072 hx509_request_free(req);
1073 return WERR_INTERNAL_ERROR;
1076 free_SubjectPublicKeyInfo(&key);
1081 /* Return an error when we fail to generate a certificate */
1082 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1084 heim_octet_string data;
1088 hx509_private_key pk;
1092 DATA_BLOB blobkeypair;
1096 struct GUID guid = GUID_random();
1099 struct bkrp_exported_RSA_key_pair keypair;
1100 enum ndr_err_code ndr_err;
1101 uint32_t nb_seconds_validity = 3600 * 24 * 365;
1103 DEBUG(6, ("Trying to generate a certificate\n"));
1104 hx509_context_init(&hctx);
1105 werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1106 if (!W_ERROR_IS_OK(werr)) {
1107 hx509_context_free(&hctx);
1111 status = GUID_to_ndr_blob(&guid, ctx, &blob);
1112 if (!NT_STATUS_IS_OK(status)) {
1113 hx509_context_free(&hctx);
1114 hx509_private_key_free(&pk);
1116 return WERR_INVALID_DATA;
1119 werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1120 if (!W_ERROR_IS_OK(werr)) {
1121 hx509_private_key_free(&pk);
1122 hx509_context_free(&hctx);
1123 return WERR_INVALID_DATA;
1126 ret = hx509_cert_binary(hctx, cert, &data);
1128 hx509_cert_free(cert);
1129 hx509_private_key_free(&pk);
1130 hx509_context_free(&hctx);
1131 return WERR_INVALID_DATA;
1134 keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1135 keypair.cert.length = data.length;
1138 * Heimdal's bignum are big endian and the
1139 * structure expect it to be in little endian
1140 * so we reverse the buffer to make it work
1142 tmp = reverse_and_get_blob(ctx, rsa->e);
1146 keypair.public_exponent = *tmp;
1147 SMB_ASSERT(tmp->length <= 4);
1149 * The value is now in little endian but if can happen that the length is
1150 * less than 4 bytes.
1151 * So if we have less than 4 bytes we pad with zeros so that it correctly
1152 * fit into the structure.
1154 if (tmp->length < 4) {
1156 * We need the expo to fit 4 bytes
1158 keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1159 memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1160 keypair.public_exponent.length = 4;
1164 tmp = reverse_and_get_blob(ctx,rsa->d);
1168 keypair.private_exponent = *tmp;
1171 tmp = reverse_and_get_blob(ctx,rsa->n);
1175 keypair.modulus = *tmp;
1178 tmp = reverse_and_get_blob(ctx,rsa->p);
1182 keypair.prime1 = *tmp;
1185 tmp = reverse_and_get_blob(ctx,rsa->q);
1189 keypair.prime2 = *tmp;
1192 tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1196 keypair.exponent1 = *tmp;
1199 tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1203 keypair.exponent2 = *tmp;
1206 tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1210 keypair.coefficient = *tmp;
1213 /* One of the keypair allocation was wrong */
1215 der_free_octet_string(&data);
1216 hx509_cert_free(cert);
1217 hx509_private_key_free(&pk);
1218 hx509_context_free(&hctx);
1220 return WERR_INVALID_DATA;
1222 keypair.certificate_len = keypair.cert.length;
1223 ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1224 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1225 der_free_octet_string(&data);
1226 hx509_cert_free(cert);
1227 hx509_private_key_free(&pk);
1228 hx509_context_free(&hctx);
1230 return WERR_INVALID_DATA;
1233 secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1234 if (secret_name == NULL) {
1235 der_free_octet_string(&data);
1236 hx509_cert_free(cert);
1237 hx509_private_key_free(&pk);
1238 hx509_context_free(&hctx);
1240 return WERR_OUTOFMEMORY;
1243 status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1244 if (!NT_STATUS_IS_OK(status)) {
1245 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1247 talloc_free(secret_name);
1249 GUID_to_ndr_blob(&guid, ctx, &blob);
1250 status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1251 if (!NT_STATUS_IS_OK(status)) {
1252 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1255 der_free_octet_string(&data);
1256 hx509_cert_free(cert);
1257 hx509_private_key_free(&pk);
1258 hx509_context_free(&hctx);
1263 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1264 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1268 DATA_BLOB lsa_secret;
1269 enum ndr_err_code ndr_err;
1273 * here we basicaly need to return our certificate
1274 * search for lsa secret BCKUPKEY_PREFERRED first
1277 status = get_lsa_secret(mem_ctx,
1279 "BCKUPKEY_PREFERRED",
1281 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1282 /* Ok we can be in this case if there was no certs */
1283 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1284 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1285 lpcfg_realm(lp_ctx));
1287 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1288 if (!W_ERROR_IS_OK(werr)) {
1289 return WERR_INVALID_PARAMETER;
1291 status = get_lsa_secret(mem_ctx,
1293 "BCKUPKEY_PREFERRED",
1296 if (!NT_STATUS_IS_OK(status)) {
1297 /* Ok we really don't manage to get this certs ...*/
1298 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1299 return WERR_FILE_NOT_FOUND;
1301 } else if (!NT_STATUS_IS_OK(status)) {
1302 return WERR_INTERNAL_ERROR;
1305 if (lsa_secret.length == 0) {
1306 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1307 return WERR_INTERNAL_ERROR;
1309 char *cert_secret_name;
1311 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1312 if (!NT_STATUS_IS_OK(status)) {
1313 return WERR_FILE_NOT_FOUND;
1316 guid_string = GUID_string(mem_ctx, &guid);
1317 if (guid_string == NULL) {
1318 /* We return file not found because the client
1321 return WERR_FILE_NOT_FOUND;
1324 cert_secret_name = talloc_asprintf(mem_ctx,
1327 status = get_lsa_secret(mem_ctx,
1331 if (!NT_STATUS_IS_OK(status)) {
1332 return WERR_FILE_NOT_FOUND;
1335 if (lsa_secret.length != 0) {
1336 struct bkrp_exported_RSA_key_pair keypair;
1337 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1338 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1339 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1340 return WERR_FILE_NOT_FOUND;
1342 *(r->out.data_out_len) = keypair.cert.length;
1343 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1344 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1347 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1348 return WERR_INTERNAL_ERROR;
1352 return WERR_NOT_SUPPORTED;
1355 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1357 struct GUID guid = GUID_random();
1358 enum ndr_err_code ndr_err;
1359 DATA_BLOB blob_wrap_key, guid_blob;
1360 struct bkrp_dc_serverwrap_key wrap_key;
1363 TALLOC_CTX *frame = talloc_stackframe();
1365 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1367 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1368 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1370 return WERR_INVALID_DATA;
1373 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1374 if (secret_name == NULL) {
1379 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1380 if (!NT_STATUS_IS_OK(status)) {
1381 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1383 return WERR_INTERNAL_ERROR;
1386 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1387 if (!NT_STATUS_IS_OK(status)) {
1388 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1392 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1393 if (!NT_STATUS_IS_OK(status)) {
1394 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1396 return WERR_INTERNAL_ERROR;
1405 * Find the specified decryption keys from the LSA secrets store as
1406 * G$BCKUPKEY_keyGuidString.
1409 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1410 struct bkrp_dc_serverwrap_key *server_key,
1414 DATA_BLOB lsa_secret;
1417 enum ndr_err_code ndr_err;
1419 guid_string = GUID_string(mem_ctx, guid);
1420 if (guid_string == NULL) {
1421 /* We return file not found because the client
1424 return WERR_FILE_NOT_FOUND;
1427 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1428 if (secret_name == NULL) {
1432 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1433 if (!NT_STATUS_IS_OK(status)) {
1434 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1435 return WERR_INVALID_DATA;
1437 if (lsa_secret.length == 0) {
1438 /* RODC case, we do not have secrets locally */
1439 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1441 return WERR_INTERNAL_ERROR;
1443 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1444 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1445 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1446 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1447 return WERR_INVALID_DATA;
1454 * Find the current, preferred ServerWrap Key by looking at
1455 * G$BCKUPKEY_P in the LSA secrets store.
1457 * Then find the current decryption keys from the LSA secrets store as
1458 * G$BCKUPKEY_keyGuidString.
1461 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1462 struct ldb_context *ldb_ctx,
1463 struct bkrp_dc_serverwrap_key *server_key,
1464 struct GUID *returned_guid)
1467 DATA_BLOB guid_binary;
1469 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1470 if (!NT_STATUS_IS_OK(status)) {
1471 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1472 return WERR_FILE_NOT_FOUND;
1473 } else if (guid_binary.length == 0) {
1474 /* RODC case, we do not have secrets locally */
1475 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1476 return WERR_INTERNAL_ERROR;
1479 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1480 if (!NT_STATUS_IS_OK(status)) {
1481 return WERR_FILE_NOT_FOUND;
1484 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1485 server_key, returned_guid);
1488 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1489 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1492 struct bkrp_server_side_wrapped decrypt_request;
1493 DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1495 enum ndr_err_code ndr_err;
1496 struct bkrp_dc_serverwrap_key server_key;
1497 struct bkrp_rc4encryptedpayload rc4payload;
1498 struct dom_sid *caller_sid;
1499 uint8_t symkey[20]; /* SHA-1 hash len */
1500 uint8_t mackey[20]; /* SHA-1 hash len */
1501 uint8_t mac[20]; /* SHA-1 hash len */
1502 unsigned int hash_len;
1505 blob.data = r->in.data_in;
1506 blob.length = r->in.data_in_len;
1508 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1509 return WERR_INVALID_PARAM;
1512 ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1513 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1514 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1515 return WERR_INVALID_PARAM;
1518 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1519 return WERR_INVALID_PARAM;
1522 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1523 &decrypt_request.guid);
1524 if (!W_ERROR_IS_OK(werr)) {
1528 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1530 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1533 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1534 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1536 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1537 decrypt_request.r2, sizeof(decrypt_request.r2),
1540 dump_data_pw("symkey: \n", symkey, hash_len);
1542 /* rc4 decrypt sid and secret using sym key */
1543 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1545 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1546 decrypt_request.ciphertext_length);
1548 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1550 ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1551 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1552 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1553 return WERR_INVALID_PARAM;
1556 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1557 return WERR_INVALID_PARAM;
1560 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1563 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1564 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1566 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1567 rc4payload.r3, sizeof(rc4payload.r3),
1570 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1572 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1573 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1574 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1575 return WERR_INTERNAL_ERROR;
1578 HMAC_CTX_init(&ctx);
1579 HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1581 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1583 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1584 HMAC_Final(&ctx, mac, &hash_len);
1585 HMAC_CTX_cleanup(&ctx);
1587 dump_data_pw("mac: \n", mac, sizeof(mac));
1588 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1590 if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1591 return WERR_INVALID_ACCESS;
1594 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1596 if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1597 return WERR_INVALID_ACCESS;
1600 *(r->out.data_out) = rc4payload.secret_data.data;
1601 *(r->out.data_out_len) = rc4payload.secret_data.length;
1607 * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1608 * determine what type of restore is wanted.
1610 * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1613 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1614 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1616 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1617 return WERR_INVALID_PARAM;
1620 if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1621 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1624 return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1628 * We have some data, such as saved website or IMAP passwords that the
1629 * client would like to put into the profile on-disk. This needs to
1630 * be encrypted. This version gives the server the data over the
1631 * network (protected only by the negotiated transport encryption),
1632 * and asks that it be encrypted and returned for long-term storage.
1634 * The data is NOT stored in the LSA, but a key to encrypt the data
1635 * will be stored. There is only one active encryption key per domain,
1636 * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1638 * The potentially multiple valid decryptiong keys (and the encryption
1639 * key) are in turn stored in the LSA secrets store as
1640 * G$BCKUPKEY_keyGuidString.
1644 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1645 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1647 DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1649 struct dom_sid *caller_sid;
1650 uint8_t symkey[20]; /* SHA-1 hash len */
1651 uint8_t mackey[20]; /* SHA-1 hash len */
1652 unsigned int hash_len;
1653 struct bkrp_rc4encryptedpayload rc4payload;
1655 struct bkrp_dc_serverwrap_key server_key;
1656 enum ndr_err_code ndr_err;
1657 struct bkrp_server_side_wrapped server_side_wrapped;
1660 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1661 return WERR_INVALID_PARAM;
1664 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1665 ldb_ctx, &server_key,
1668 if (!W_ERROR_IS_OK(werr)) {
1669 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1670 /* Generate the server wrap key since one wasn't found */
1671 werr = generate_bkrp_server_wrap_key(mem_ctx,
1673 if (!W_ERROR_IS_OK(werr)) {
1674 return WERR_INVALID_PARAMETER;
1676 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1681 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1682 /* Ok we really don't manage to get this secret ...*/
1683 return WERR_FILE_NOT_FOUND;
1686 /* In theory we should NEVER reach this point as it
1687 should only appear in a rodc server */
1688 /* we do not have the real secret attribute */
1689 return WERR_INVALID_PARAMETER;
1693 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1695 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1698 * This is the key derivation step, so that the HMAC and RC4
1699 * operations over the user-supplied data are not able to
1700 * disclose the master key. By using random data, the symkey
1701 * and mackey values are unique for this operation, and
1702 * discovering these (by reversing the RC4 over the
1703 * attacker-controlled data) does not return something able to
1704 * be used to decyrpt the encrypted data of other users
1706 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1708 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1710 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1712 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1716 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1717 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1719 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1720 server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1723 dump_data_pw("symkey: \n", symkey, hash_len);
1726 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1727 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1729 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1730 rc4payload.r3, sizeof(rc4payload.r3),
1733 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1735 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1736 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1737 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1738 return WERR_INTERNAL_ERROR;
1741 rc4payload.secret_data.data = r->in.data_in;
1742 rc4payload.secret_data.length = r->in.data_in_len;
1744 HMAC_CTX_init(&ctx);
1745 HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1747 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1749 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1750 HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1751 HMAC_CTX_cleanup(&ctx);
1753 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1755 rc4payload.sid = *caller_sid;
1757 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1758 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1759 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1760 return WERR_INTERNAL_ERROR;
1763 /* rc4 encrypt sid and secret using sym key */
1764 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1765 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1767 /* create server wrap structure */
1769 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1770 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1771 server_side_wrapped.guid = guid;
1772 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1774 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1775 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1776 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1777 return WERR_INTERNAL_ERROR;
1780 *(r->out.data_out) = server_wrapped_blob.data;
1781 *(r->out.data_out_len) = server_wrapped_blob.length;
1786 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1787 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1789 WERROR error = WERR_INVALID_PARAM;
1790 struct ldb_context *ldb_ctx;
1792 const char *addr = "unknown";
1793 /* At which level we start to add more debug of what is done in the protocol */
1794 const int debuglevel = 4;
1796 if (DEBUGLVL(debuglevel)) {
1797 const struct tsocket_address *remote_address;
1798 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1799 if (tsocket_address_is_inet(remote_address, "ip")) {
1800 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1801 W_ERROR_HAVE_NO_MEMORY(addr);
1805 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1806 return WERR_NOT_SUPPORTED;
1809 if (!dce_call->conn->auth_state.auth_info ||
1810 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1811 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1814 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1815 dce_call->conn->dce_ctx->lp_ctx,
1816 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1818 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1819 talloc_unlink(mem_ctx, ldb_ctx);
1820 return WERR_INVALID_PARAM;
1824 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1825 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1826 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1827 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1830 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1831 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1832 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1833 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1836 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1837 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1838 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1839 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1842 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1843 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1844 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1845 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1848 /*else: I am a RODC so I don't handle backup key protocol */
1850 talloc_unlink(mem_ctx, ldb_ctx);
1854 /* include the generated boilerplate */
1855 #include "librpc/gen_ndr/ndr_backupkey_s.c"