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_t 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_notAfter_lifetime(*hctx, tbs, lifetime);
992 ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
996 ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
1000 ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
1004 hx509_name_free(&subject);
1005 free_SubjectPublicKeyInfo(&spki);
1006 hx509_ca_tbs_free(&tbs);
1011 hx509_ca_tbs_free(&tbs);
1013 free_SubjectPublicKeyInfo(&spki);
1015 hx509_name_free(&subject);
1017 talloc_free(uniqueid.data);
1018 talloc_free(serialnumber.data);
1019 return WERR_INTERNAL_ERROR;
1022 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
1023 hx509_private_key *signer,RSA **rsa, const char *dn)
1026 SubjectPublicKeyInfo key;
1031 werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1032 if (!W_ERROR_IS_OK(werr)) {
1036 hx509_request_init(*hctx, req);
1037 ret = hx509_parse_name(*hctx, dn, &name);
1040 hx509_private_key_free(signer);
1041 hx509_request_free(req);
1042 hx509_name_free(&name);
1043 return WERR_INTERNAL_ERROR;
1046 ret = hx509_request_set_name(*hctx, *req, name);
1049 hx509_private_key_free(signer);
1050 hx509_request_free(req);
1051 hx509_name_free(&name);
1052 return WERR_INTERNAL_ERROR;
1054 hx509_name_free(&name);
1056 ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1059 hx509_private_key_free(signer);
1060 hx509_request_free(req);
1061 return WERR_INTERNAL_ERROR;
1063 ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1066 hx509_private_key_free(signer);
1067 free_SubjectPublicKeyInfo(&key);
1068 hx509_request_free(req);
1069 return WERR_INTERNAL_ERROR;
1072 free_SubjectPublicKeyInfo(&key);
1077 /* Return an error when we fail to generate a certificate */
1078 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1080 heim_octet_string data;
1084 hx509_private_key pk;
1088 DATA_BLOB blobkeypair;
1092 struct GUID guid = GUID_random();
1095 struct bkrp_exported_RSA_key_pair keypair;
1096 enum ndr_err_code ndr_err;
1097 uint32_t nb_seconds_validity = 3600 * 24 * 365;
1099 DEBUG(6, ("Trying to generate a certificate\n"));
1100 hx509_context_init(&hctx);
1101 werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1102 if (!W_ERROR_IS_OK(werr)) {
1103 hx509_context_free(&hctx);
1107 status = GUID_to_ndr_blob(&guid, ctx, &blob);
1108 if (!NT_STATUS_IS_OK(status)) {
1109 hx509_context_free(&hctx);
1110 hx509_private_key_free(&pk);
1112 return WERR_INVALID_DATA;
1115 werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1116 if (!W_ERROR_IS_OK(werr)) {
1117 hx509_private_key_free(&pk);
1118 hx509_context_free(&hctx);
1119 return WERR_INVALID_DATA;
1122 ret = hx509_cert_binary(hctx, cert, &data);
1124 hx509_cert_free(cert);
1125 hx509_private_key_free(&pk);
1126 hx509_context_free(&hctx);
1127 return WERR_INVALID_DATA;
1130 keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1131 keypair.cert.length = data.length;
1134 * Heimdal's bignum are big endian and the
1135 * structure expect it to be in little endian
1136 * so we reverse the buffer to make it work
1138 tmp = reverse_and_get_blob(ctx, rsa->e);
1142 keypair.public_exponent = *tmp;
1143 SMB_ASSERT(tmp->length <= 4);
1145 * The value is now in little endian but if can happen that the length is
1146 * less than 4 bytes.
1147 * So if we have less than 4 bytes we pad with zeros so that it correctly
1148 * fit into the structure.
1150 if (tmp->length < 4) {
1152 * We need the expo to fit 4 bytes
1154 keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1155 memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1156 keypair.public_exponent.length = 4;
1160 tmp = reverse_and_get_blob(ctx,rsa->d);
1164 keypair.private_exponent = *tmp;
1167 tmp = reverse_and_get_blob(ctx,rsa->n);
1171 keypair.modulus = *tmp;
1174 tmp = reverse_and_get_blob(ctx,rsa->p);
1178 keypair.prime1 = *tmp;
1181 tmp = reverse_and_get_blob(ctx,rsa->q);
1185 keypair.prime2 = *tmp;
1188 tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1192 keypair.exponent1 = *tmp;
1195 tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1199 keypair.exponent2 = *tmp;
1202 tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1206 keypair.coefficient = *tmp;
1209 /* One of the keypair allocation was wrong */
1211 der_free_octet_string(&data);
1212 hx509_cert_free(cert);
1213 hx509_private_key_free(&pk);
1214 hx509_context_free(&hctx);
1216 return WERR_INVALID_DATA;
1218 keypair.certificate_len = keypair.cert.length;
1219 ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1220 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1221 der_free_octet_string(&data);
1222 hx509_cert_free(cert);
1223 hx509_private_key_free(&pk);
1224 hx509_context_free(&hctx);
1226 return WERR_INVALID_DATA;
1229 secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1230 if (secret_name == NULL) {
1231 der_free_octet_string(&data);
1232 hx509_cert_free(cert);
1233 hx509_private_key_free(&pk);
1234 hx509_context_free(&hctx);
1236 return WERR_OUTOFMEMORY;
1239 status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1240 if (!NT_STATUS_IS_OK(status)) {
1241 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1243 talloc_free(secret_name);
1245 GUID_to_ndr_blob(&guid, ctx, &blob);
1246 status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1247 if (!NT_STATUS_IS_OK(status)) {
1248 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1251 der_free_octet_string(&data);
1252 hx509_cert_free(cert);
1253 hx509_private_key_free(&pk);
1254 hx509_context_free(&hctx);
1259 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1260 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1264 DATA_BLOB lsa_secret;
1265 enum ndr_err_code ndr_err;
1269 * here we basicaly need to return our certificate
1270 * search for lsa secret BCKUPKEY_PREFERRED first
1273 status = get_lsa_secret(mem_ctx,
1275 "BCKUPKEY_PREFERRED",
1277 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1278 /* Ok we can be in this case if there was no certs */
1279 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1280 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1281 lpcfg_realm(lp_ctx));
1283 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1284 if (!W_ERROR_IS_OK(werr)) {
1285 return WERR_INVALID_PARAMETER;
1287 status = get_lsa_secret(mem_ctx,
1289 "BCKUPKEY_PREFERRED",
1292 if (!NT_STATUS_IS_OK(status)) {
1293 /* Ok we really don't manage to get this certs ...*/
1294 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1295 return WERR_FILE_NOT_FOUND;
1297 } else if (!NT_STATUS_IS_OK(status)) {
1298 return WERR_INTERNAL_ERROR;
1301 if (lsa_secret.length == 0) {
1302 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1303 return WERR_INTERNAL_ERROR;
1305 char *cert_secret_name;
1307 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1308 if (!NT_STATUS_IS_OK(status)) {
1309 return WERR_FILE_NOT_FOUND;
1312 guid_string = GUID_string(mem_ctx, &guid);
1313 if (guid_string == NULL) {
1314 /* We return file not found because the client
1317 return WERR_FILE_NOT_FOUND;
1320 cert_secret_name = talloc_asprintf(mem_ctx,
1323 status = get_lsa_secret(mem_ctx,
1327 if (!NT_STATUS_IS_OK(status)) {
1328 return WERR_FILE_NOT_FOUND;
1331 if (lsa_secret.length != 0) {
1332 struct bkrp_exported_RSA_key_pair keypair;
1333 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1334 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1335 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1336 return WERR_FILE_NOT_FOUND;
1338 *(r->out.data_out_len) = keypair.cert.length;
1339 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1340 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1343 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1344 return WERR_INTERNAL_ERROR;
1348 return WERR_NOT_SUPPORTED;
1351 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1353 struct GUID guid = GUID_random();
1354 enum ndr_err_code ndr_err;
1355 DATA_BLOB blob_wrap_key, guid_blob;
1356 struct bkrp_dc_serverwrap_key wrap_key;
1359 TALLOC_CTX *frame = talloc_stackframe();
1361 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1363 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1364 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1366 return WERR_INVALID_DATA;
1369 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1370 if (secret_name == NULL) {
1375 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1376 if (!NT_STATUS_IS_OK(status)) {
1377 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1379 return WERR_INTERNAL_ERROR;
1382 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1383 if (!NT_STATUS_IS_OK(status)) {
1384 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1388 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1389 if (!NT_STATUS_IS_OK(status)) {
1390 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1392 return WERR_INTERNAL_ERROR;
1401 * Find the specified decryption keys from the LSA secrets store as
1402 * G$BCKUPKEY_keyGuidString.
1405 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1406 struct bkrp_dc_serverwrap_key *server_key,
1410 DATA_BLOB lsa_secret;
1413 enum ndr_err_code ndr_err;
1415 guid_string = GUID_string(mem_ctx, guid);
1416 if (guid_string == NULL) {
1417 /* We return file not found because the client
1420 return WERR_FILE_NOT_FOUND;
1423 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1424 if (secret_name == NULL) {
1428 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1429 if (!NT_STATUS_IS_OK(status)) {
1430 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1431 return WERR_INVALID_DATA;
1433 if (lsa_secret.length == 0) {
1434 /* RODC case, we do not have secrets locally */
1435 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1437 return WERR_INTERNAL_ERROR;
1439 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1440 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1441 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1442 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1443 return WERR_INVALID_DATA;
1450 * Find the current, preferred ServerWrap Key by looking at
1451 * G$BCKUPKEY_P in the LSA secrets store.
1453 * Then find the current decryption keys from the LSA secrets store as
1454 * G$BCKUPKEY_keyGuidString.
1457 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1458 struct ldb_context *ldb_ctx,
1459 struct bkrp_dc_serverwrap_key *server_key,
1460 struct GUID *returned_guid)
1463 DATA_BLOB guid_binary;
1465 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1466 if (!NT_STATUS_IS_OK(status)) {
1467 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1468 return WERR_FILE_NOT_FOUND;
1469 } else if (guid_binary.length == 0) {
1470 /* RODC case, we do not have secrets locally */
1471 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1472 return WERR_INTERNAL_ERROR;
1475 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1476 if (!NT_STATUS_IS_OK(status)) {
1477 return WERR_FILE_NOT_FOUND;
1480 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1481 server_key, returned_guid);
1484 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1485 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1488 struct bkrp_server_side_wrapped decrypt_request;
1489 DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1491 enum ndr_err_code ndr_err;
1492 struct bkrp_dc_serverwrap_key server_key;
1493 struct bkrp_rc4encryptedpayload rc4payload;
1494 struct dom_sid *caller_sid;
1495 uint8_t symkey[20]; /* SHA-1 hash len */
1496 uint8_t mackey[20]; /* SHA-1 hash len */
1497 uint8_t mac[20]; /* SHA-1 hash len */
1498 unsigned int hash_len;
1501 blob.data = r->in.data_in;
1502 blob.length = r->in.data_in_len;
1504 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1505 return WERR_INVALID_PARAM;
1508 ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1509 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1510 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1511 return WERR_INVALID_PARAM;
1514 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1515 return WERR_INVALID_PARAM;
1518 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1519 &decrypt_request.guid);
1520 if (!W_ERROR_IS_OK(werr)) {
1524 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1526 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1529 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1530 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1532 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1533 decrypt_request.r2, sizeof(decrypt_request.r2),
1536 dump_data_pw("symkey: \n", symkey, hash_len);
1538 /* rc4 decrypt sid and secret using sym key */
1539 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1541 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1542 decrypt_request.ciphertext_length);
1544 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1546 ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1547 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1548 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1549 return WERR_INVALID_PARAM;
1552 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1553 return WERR_INVALID_PARAM;
1556 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1559 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1560 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1562 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1563 rc4payload.r3, sizeof(rc4payload.r3),
1566 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1568 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1569 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1570 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1571 return WERR_INTERNAL_ERROR;
1574 HMAC_CTX_init(&ctx);
1575 HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1577 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1579 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1580 HMAC_Final(&ctx, mac, &hash_len);
1581 HMAC_CTX_cleanup(&ctx);
1583 dump_data_pw("mac: \n", mac, sizeof(mac));
1584 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1586 if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1587 return WERR_INVALID_ACCESS;
1590 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1592 if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1593 return WERR_INVALID_ACCESS;
1596 *(r->out.data_out) = rc4payload.secret_data.data;
1597 *(r->out.data_out_len) = rc4payload.secret_data.length;
1603 * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1604 * determine what type of restore is wanted.
1606 * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1609 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1610 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1612 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1613 return WERR_INVALID_PARAM;
1616 if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1617 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1620 return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1624 * We have some data, such as saved website or IMAP passwords that the
1625 * client would like to put into the profile on-disk. This needs to
1626 * be encrypted. This version gives the server the data over the
1627 * network (protected only by the negotiated transport encryption),
1628 * and asks that it be encrypted and returned for long-term storage.
1630 * The data is NOT stored in the LSA, but a key to encrypt the data
1631 * will be stored. There is only one active encryption key per domain,
1632 * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1634 * The potentially multiple valid decryptiong keys (and the encryption
1635 * key) are in turn stored in the LSA secrets store as
1636 * G$BCKUPKEY_keyGuidString.
1640 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1641 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1643 DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1645 struct dom_sid *caller_sid;
1646 uint8_t symkey[20]; /* SHA-1 hash len */
1647 uint8_t mackey[20]; /* SHA-1 hash len */
1648 unsigned int hash_len;
1649 struct bkrp_rc4encryptedpayload rc4payload;
1651 struct bkrp_dc_serverwrap_key server_key;
1652 enum ndr_err_code ndr_err;
1653 struct bkrp_server_side_wrapped server_side_wrapped;
1656 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1657 return WERR_INVALID_PARAM;
1660 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1661 ldb_ctx, &server_key,
1664 if (!W_ERROR_IS_OK(werr)) {
1665 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1666 /* Generate the server wrap key since one wasn't found */
1667 werr = generate_bkrp_server_wrap_key(mem_ctx,
1669 if (!W_ERROR_IS_OK(werr)) {
1670 return WERR_INVALID_PARAMETER;
1672 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1677 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1678 /* Ok we really don't manage to get this secret ...*/
1679 return WERR_FILE_NOT_FOUND;
1682 /* In theory we should NEVER reach this point as it
1683 should only appear in a rodc server */
1684 /* we do not have the real secret attribute */
1685 return WERR_INVALID_PARAMETER;
1689 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1691 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1694 * This is the key derivation step, so that the HMAC and RC4
1695 * operations over the user-supplied data are not able to
1696 * disclose the master key. By using random data, the symkey
1697 * and mackey values are unique for this operation, and
1698 * discovering these (by reversing the RC4 over the
1699 * attacker-controlled data) does not return something able to
1700 * be used to decyrpt the encrypted data of other users
1702 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1704 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1706 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1708 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1712 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1713 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1715 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1716 server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1719 dump_data_pw("symkey: \n", symkey, hash_len);
1722 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1723 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1725 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1726 rc4payload.r3, sizeof(rc4payload.r3),
1729 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1731 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1732 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1733 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1734 return WERR_INTERNAL_ERROR;
1737 rc4payload.secret_data.data = r->in.data_in;
1738 rc4payload.secret_data.length = r->in.data_in_len;
1740 HMAC_CTX_init(&ctx);
1741 HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1743 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1745 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1746 HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1747 HMAC_CTX_cleanup(&ctx);
1749 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1751 rc4payload.sid = *caller_sid;
1753 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1754 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1755 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1756 return WERR_INTERNAL_ERROR;
1759 /* rc4 encrypt sid and secret using sym key */
1760 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1761 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1763 /* create server wrap structure */
1765 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1766 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1767 server_side_wrapped.guid = guid;
1768 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1770 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1771 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1772 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1773 return WERR_INTERNAL_ERROR;
1776 *(r->out.data_out) = server_wrapped_blob.data;
1777 *(r->out.data_out_len) = server_wrapped_blob.length;
1782 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1783 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1785 WERROR error = WERR_INVALID_PARAM;
1786 struct ldb_context *ldb_ctx;
1788 const char *addr = "unknown";
1789 /* At which level we start to add more debug of what is done in the protocol */
1790 const int debuglevel = 4;
1792 if (DEBUGLVL(debuglevel)) {
1793 const struct tsocket_address *remote_address;
1794 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1795 if (tsocket_address_is_inet(remote_address, "ip")) {
1796 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1797 W_ERROR_HAVE_NO_MEMORY(addr);
1801 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1802 return WERR_NOT_SUPPORTED;
1805 if (!dce_call->conn->auth_state.auth_info ||
1806 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1807 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1810 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1811 dce_call->conn->dce_ctx->lp_ctx,
1812 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1814 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1815 talloc_unlink(mem_ctx, ldb_ctx);
1816 return WERR_INVALID_PARAM;
1820 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1821 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1822 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1823 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1826 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1827 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1828 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1829 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1832 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1833 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1834 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1835 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1838 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1839 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1840 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1841 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1844 /*else: I am a RODC so I don't handle backup key protocol */
1846 talloc_unlink(mem_ctx, ldb_ctx);
1850 /* include the generated boilerplate */
1851 #include "librpc/gen_ndr/ndr_backupkey_s.c"