backupkey: replace heimdal rsa key generation with GnuTLS
[Samba.git] / source4 / rpc_server / backupkey / dcesrv_backupkey.c
blobae4c871d9d9c1fc39d921f05ab52f468d2822b69
1 /*
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/>.
22 #include "includes.h"
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"
32 #include <com_err.h>
33 #include <hx509.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>
39 #include <der.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 HAVE_GCRYPT_H
47 #include <gcrypt.h>
48 #endif
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,
59 const char *name,
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;
66 struct ldb_val val;
67 int ret;
68 char *name2;
69 struct timeval now = timeval_current();
70 NTTIME nt_now = timeval_to_nttime(&now);
71 const char *attrs[] = {
72 NULL
75 domain_dn = ldb_get_default_basedn(ldb);
76 if (!domain_dn) {
77 return NT_STATUS_INTERNAL_ERROR;
80 msg = ldb_msg_new(mem_ctx);
81 if (msg == NULL) {
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) {
97 talloc_free(msg);
98 return NT_STATUS_NO_MEMORY;
101 name2 = talloc_asprintf(msg, "%s Secret", name);
102 if (name2 == NULL) {
103 talloc_free(msg);
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));
113 talloc_free(msg);
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) {
124 talloc_free(msg);
125 return NT_STATUS_NO_MEMORY;
127 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
128 talloc_free(msg);
129 return NT_STATUS_NO_MEMORY;
132 ret = ldb_msg_add_string(msg, "cn", name2);
133 if (ret != LDB_SUCCESS) {
134 talloc_free(msg);
135 return NT_STATUS_NO_MEMORY;
137 ret = ldb_msg_add_string(msg, "objectClass", "secret");
138 if (ret != LDB_SUCCESS) {
139 talloc_free(msg);
140 return NT_STATUS_NO_MEMORY;
142 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
143 if (ret != LDB_SUCCESS) {
144 talloc_free(msg);
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) {
151 talloc_free(msg);
152 return NT_STATUS_NO_MEMORY;
154 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
155 if (ret != LDB_SUCCESS) {
156 talloc_free(msg);
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)));
170 talloc_free(msg);
171 return NT_STATUS_ACCESS_DENIED;
174 talloc_free(msg);
175 return NT_STATUS_OK;
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,
181 const char *name,
182 DATA_BLOB *lsa_secret)
184 TALLOC_CTX *tmp_mem;
185 struct ldb_result *res;
186 struct ldb_dn *domain_dn;
187 struct ldb_dn *system_dn;
188 const struct ldb_val *val;
189 uint8_t *data;
190 const char *attrs[] = {
191 "currentValue",
192 NULL
194 int ret;
196 lsa_secret->data = NULL;
197 lsa_secret->length = 0;
199 domain_dn = ldb_get_default_basedn(ldb);
200 if (!domain_dn) {
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;
222 } else if (res->count == 0) {
223 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
224 } else if (res->count > 1) {
225 DEBUG(2, ("Secret %s collision\n", name));
226 talloc_free(tmp_mem);
227 return NT_STATUS_INTERNAL_DB_CORRUPTION;
230 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
231 if (val == NULL) {
233 * The secret object is here but we don't have the secret value
234 * The most common case is a RODC
236 *lsa_secret = data_blob_null;
237 talloc_free(tmp_mem);
238 return NT_STATUS_OK;
241 data = val->data;
242 lsa_secret->data = talloc_move(mem_ctx, &data);
243 lsa_secret->length = val->length;
245 talloc_free(tmp_mem);
246 return NT_STATUS_OK;
249 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
251 DATA_BLOB blob;
252 DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
253 uint32_t i;
255 blob.length = BN_num_bytes(bn);
256 blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
258 if (blob.data == NULL) {
259 return NULL;
262 BN_bn2bin(bn, blob.data);
264 rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
265 if (rev->data == NULL) {
266 return NULL;
269 for(i=0; i < blob.length; i++) {
270 rev->data[i] = blob.data[blob.length - i -1];
272 rev->length = blob.length;
273 talloc_free(blob.data);
274 return rev;
277 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
279 BIGNUM *ret;
280 DATA_BLOB rev;
281 uint32_t i;
283 rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
284 if (rev.data == NULL) {
285 return NULL;
288 for(i=0; i < blob->length; i++) {
289 rev.data[i] = blob->data[blob->length - i -1];
291 rev.length = blob->length;
293 ret = BN_bin2bn(rev.data, rev.length, NULL);
294 talloc_free(rev.data);
296 return ret;
299 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
300 struct bkrp_exported_RSA_key_pair *keypair,
301 hx509_private_key *pk)
303 hx509_context hctx;
304 RSA *rsa;
305 struct hx509_private_key_ops *ops;
307 hx509_context_init(&hctx);
308 ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
309 if (ops == NULL) {
310 DEBUG(2, ("Not supported algorithm\n"));
311 return NT_STATUS_INTERNAL_ERROR;
314 if (hx509_private_key_init(pk, ops, NULL) != 0) {
315 hx509_context_free(&hctx);
316 return NT_STATUS_NO_MEMORY;
319 rsa = RSA_new();
320 if (rsa ==NULL) {
321 hx509_context_free(&hctx);
322 return NT_STATUS_INVALID_PARAMETER;
325 rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
326 if (rsa->n == NULL) {
327 RSA_free(rsa);
328 hx509_context_free(&hctx);
329 return NT_STATUS_INVALID_PARAMETER;
331 rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
332 if (rsa->d == NULL) {
333 RSA_free(rsa);
334 hx509_context_free(&hctx);
335 return NT_STATUS_INVALID_PARAMETER;
337 rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
338 if (rsa->p == NULL) {
339 RSA_free(rsa);
340 hx509_context_free(&hctx);
341 return NT_STATUS_INVALID_PARAMETER;
343 rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
344 if (rsa->q == NULL) {
345 RSA_free(rsa);
346 hx509_context_free(&hctx);
347 return NT_STATUS_INVALID_PARAMETER;
349 rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
350 if (rsa->dmp1 == NULL) {
351 RSA_free(rsa);
352 hx509_context_free(&hctx);
353 return NT_STATUS_INVALID_PARAMETER;
355 rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
356 if (rsa->dmq1 == NULL) {
357 RSA_free(rsa);
358 hx509_context_free(&hctx);
359 return NT_STATUS_INVALID_PARAMETER;
361 rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
362 if (rsa->iqmp == NULL) {
363 RSA_free(rsa);
364 hx509_context_free(&hctx);
365 return NT_STATUS_INVALID_PARAMETER;
367 rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
368 if (rsa->e == NULL) {
369 RSA_free(rsa);
370 hx509_context_free(&hctx);
371 return NT_STATUS_INVALID_PARAMETER;
374 hx509_private_key_assign_rsa(*pk, rsa);
376 hx509_context_free(&hctx);
377 return NT_STATUS_OK;
380 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
381 uint32_t version,
382 uint8_t *key_and_iv,
383 uint8_t *access_check,
384 uint32_t access_check_len,
385 struct auth_session_info *session_info)
387 heim_octet_string iv;
388 heim_octet_string access_check_os;
389 hx509_crypto crypto;
391 DATA_BLOB blob_us;
392 uint32_t key_len;
393 uint32_t iv_len;
394 int res;
395 enum ndr_err_code ndr_err;
396 hx509_context hctx;
398 struct dom_sid *access_sid = NULL;
399 struct dom_sid *caller_sid = NULL;
401 /* This one should not be freed */
402 const AlgorithmIdentifier *alg;
404 switch (version) {
405 case 2:
406 key_len = 24;
407 iv_len = 8;
408 alg = hx509_crypto_des_rsdi_ede3_cbc();
409 break;
411 case 3:
412 key_len = 32;
413 iv_len = 16;
414 alg =hx509_crypto_aes256_cbc();
415 break;
417 default:
418 return WERR_INVALID_DATA;
421 hx509_context_init(&hctx);
422 res = hx509_crypto_init(hctx, NULL,
423 &(alg->algorithm),
424 &crypto);
425 hx509_context_free(&hctx);
427 if (res != 0) {
428 return WERR_INVALID_DATA;
431 res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
433 iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
434 iv.length = iv_len;
436 if (res != 0) {
437 hx509_crypto_destroy(crypto);
438 return WERR_INVALID_DATA;
441 hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
442 res = hx509_crypto_decrypt(crypto,
443 access_check,
444 access_check_len,
445 &iv,
446 &access_check_os);
448 if (res != 0) {
449 hx509_crypto_destroy(crypto);
450 return WERR_INVALID_DATA;
453 blob_us.data = access_check_os.data;
454 blob_us.length = access_check_os.length;
456 hx509_crypto_destroy(crypto);
458 switch (version) {
459 case 2:
461 uint32_t hash_size = 20;
462 uint8_t hash[hash_size];
463 struct sha sctx;
464 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
466 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
467 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
468 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
469 /* Unable to unmarshall */
470 der_free_octet_string(&access_check_os);
471 return WERR_INVALID_DATA;
473 if (uncrypted_accesscheckv2.magic != 0x1) {
474 /* wrong magic */
475 der_free_octet_string(&access_check_os);
476 return WERR_INVALID_DATA;
479 SHA1_Init(&sctx);
480 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
481 SHA1_Final(hash, &sctx);
482 der_free_octet_string(&access_check_os);
484 * We free it after the sha1 calculation because blob.data
485 * point to the same area
488 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
489 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
490 return WERR_INVALID_DATA;
492 access_sid = &(uncrypted_accesscheckv2.sid);
493 break;
495 case 3:
497 uint32_t hash_size = 64;
498 uint8_t hash[hash_size];
499 struct hc_sha512state sctx;
500 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
502 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
503 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
504 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
505 /* Unable to unmarshall */
506 der_free_octet_string(&access_check_os);
507 return WERR_INVALID_DATA;
509 if (uncrypted_accesscheckv3.magic != 0x1) {
510 /* wrong magic */
511 der_free_octet_string(&access_check_os);
512 return WERR_INVALID_DATA;
515 SHA512_Init(&sctx);
516 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
517 SHA512_Final(hash, &sctx);
518 der_free_octet_string(&access_check_os);
520 * We free it after the sha1 calculation because blob.data
521 * point to the same area
524 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
525 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
526 return WERR_INVALID_DATA;
528 access_sid = &(uncrypted_accesscheckv3.sid);
529 break;
531 default:
532 /* Never reached normally as we filtered at the switch / case level */
533 return WERR_INVALID_DATA;
536 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
538 if (!dom_sid_equal(caller_sid, access_sid)) {
539 return WERR_INVALID_ACCESS;
541 return WERR_OK;
545 * We have some data, such as saved website or IMAP passwords that the
546 * client has in profile on-disk. This needs to be decrypted. This
547 * version gives the server the data over the network (protected by
548 * the X.509 certificate and public key encryption, and asks that it
549 * be decrypted returned for short-term use, protected only by the
550 * negotiated transport encryption.
552 * The data is NOT stored in the LSA, but a X.509 certificate, public
553 * and private keys used to encrypt the data will be stored. There is
554 * only one active encryption key pair and certificate per domain, it
555 * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
557 * The potentially multiple valid decrypting key pairs are in turn
558 * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
561 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
562 TALLOC_CTX *mem_ctx,
563 struct bkrp_BackupKey *r,
564 struct ldb_context *ldb_ctx)
566 struct bkrp_client_side_wrapped uncrypt_request;
567 DATA_BLOB blob;
568 enum ndr_err_code ndr_err;
569 char *guid_string;
570 char *cert_secret_name;
571 DATA_BLOB lsa_secret;
572 DATA_BLOB *uncrypted_data;
573 NTSTATUS status;
574 uint32_t requested_version;
576 blob.data = r->in.data_in;
577 blob.length = r->in.data_in_len;
579 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
580 return WERR_INVALID_PARAM;
584 * We check for the version here, so we can actually print the
585 * message as we are unlikely to parse it with NDR.
587 requested_version = IVAL(r->in.data_in, 0);
588 if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
589 && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
590 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
591 return WERR_INVALID_PARAMETER;
594 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
595 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
596 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
597 return WERR_INVALID_PARAM;
600 if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
601 && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
602 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
603 return WERR_INVALID_PARAMETER;
606 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
607 if (guid_string == NULL) {
608 return WERR_NOMEM;
611 cert_secret_name = talloc_asprintf(mem_ctx,
612 "BCKUPKEY_%s",
613 guid_string);
614 if (cert_secret_name == NULL) {
615 return WERR_NOMEM;
618 status = get_lsa_secret(mem_ctx,
619 ldb_ctx,
620 cert_secret_name,
621 &lsa_secret);
622 if (!NT_STATUS_IS_OK(status)) {
623 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
624 return WERR_INVALID_DATA;
625 } else if (lsa_secret.length == 0) {
626 /* we do not have the real secret attribute, like if we are an RODC */
627 return WERR_INVALID_PARAMETER;
628 } else {
629 hx509_context hctx;
630 struct bkrp_exported_RSA_key_pair keypair;
631 hx509_private_key pk;
632 uint32_t i, res;
633 heim_octet_string reversed_secret;
634 heim_octet_string uncrypted_secret;
635 AlgorithmIdentifier alg;
636 DATA_BLOB blob_us;
637 WERROR werr;
639 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
640 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
641 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
642 return WERR_FILE_NOT_FOUND;
645 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
646 if (!NT_STATUS_IS_OK(status)) {
647 return WERR_INTERNAL_ERROR;
650 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
651 uncrypt_request.encrypted_secret_len);
652 if (reversed_secret.data == NULL) {
653 hx509_private_key_free(&pk);
654 return WERR_NOMEM;
657 /* The secret has to be reversed ... */
658 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
659 uint8_t *reversed = (uint8_t *)reversed_secret.data;
660 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
661 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
663 reversed_secret.length = uncrypt_request.encrypted_secret_len;
666 * Let's try to decrypt the secret now that
667 * we have the private key ...
669 hx509_context_init(&hctx);
670 res = hx509_private_key_private_decrypt(hctx, &reversed_secret,
671 &alg.algorithm, pk,
672 &uncrypted_secret);
673 hx509_context_free(&hctx);
674 hx509_private_key_free(&pk);
675 if (res != 0) {
676 /* We are not able to decrypt the secret, looks like something is wrong */
677 return WERR_INVALID_PARAMETER;
679 blob_us.data = uncrypted_secret.data;
680 blob_us.length = uncrypted_secret.length;
682 if (uncrypt_request.version == 2) {
683 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
685 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
686 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
687 der_free_octet_string(&uncrypted_secret);
688 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
689 /* Unable to unmarshall */
690 return WERR_INVALID_DATA;
692 if (uncrypted_secretv2.magic != 0x20) {
693 /* wrong magic */
694 return WERR_INVALID_DATA;
697 werr = get_and_verify_access_check(mem_ctx, 2,
698 uncrypted_secretv2.payload_key,
699 uncrypt_request.access_check,
700 uncrypt_request.access_check_len,
701 dce_call->conn->auth_state.session_info);
702 if (!W_ERROR_IS_OK(werr)) {
703 return werr;
705 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
706 if (uncrypted_data == NULL) {
707 return WERR_INVALID_DATA;
710 uncrypted_data->data = uncrypted_secretv2.secret;
711 uncrypted_data->length = uncrypted_secretv2.secret_len;
713 if (uncrypt_request.version == 3) {
714 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
716 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
717 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
719 der_free_octet_string(&uncrypted_secret);
720 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
721 /* Unable to unmarshall */
722 return WERR_INVALID_DATA;
725 if (uncrypted_secretv3.magic1 != 0x30 ||
726 uncrypted_secretv3.magic2 != 0x6610 ||
727 uncrypted_secretv3.magic3 != 0x800e) {
728 /* wrong magic */
729 return WERR_INVALID_DATA;
733 * Confirm that the caller is permitted to
734 * read this particular data. Because one key
735 * pair is used per domain, the caller could
736 * have stolen the profile data on-disk and
737 * would otherwise be able to read the
738 * passwords.
741 werr = get_and_verify_access_check(mem_ctx, 3,
742 uncrypted_secretv3.payload_key,
743 uncrypt_request.access_check,
744 uncrypt_request.access_check_len,
745 dce_call->conn->auth_state.session_info);
746 if (!W_ERROR_IS_OK(werr)) {
747 return werr;
750 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
751 if (uncrypted_data == NULL) {
752 return WERR_INVALID_DATA;
755 uncrypted_data->data = uncrypted_secretv3.secret;
756 uncrypted_data->length = uncrypted_secretv3.secret_len;
760 * Yeah if we are here all looks pretty good:
761 * - hash is ok
762 * - user sid is the same as the one in access check
763 * - we were able to decrypt the whole stuff
767 if (uncrypted_data->data == NULL) {
768 return WERR_INVALID_DATA;
771 /* There is a magic value a the beginning of the data
772 * we can use an adhoc structure but as the
773 * parent structure is just an array of bytes it a lot of work
774 * work just prepending 4 bytes
776 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
777 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
778 memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
779 *(r->out.data_out_len) = uncrypted_data->length + 4;
781 return WERR_OK;
785 * Strictly, this function no longer uses Heimdal in order to generate an RSA
786 * key, but GnuTLS.
788 * The resulting key is then imported into Heimdal's RSA structure.
790 * We use GnuTLS because it can reliably generate 2048 bit keys every time.
791 * Windows clients strictly require 2048, no more since it won't fit and no
792 * less either. Heimdal would almost always generate a smaller key.
794 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
795 hx509_private_key *pk, RSA **rsa)
797 int ret;
798 uint8_t *p0 = NULL;
799 const uint8_t *p;
800 size_t len;
801 int bits = 2048;
802 int RSA_returned_bits;
803 gnutls_x509_privkey gtls_key;
804 WERROR werr;
806 *rsa = NULL;
808 gnutls_global_init();
809 #ifdef HAVE_GCRYPT_H
810 DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
811 gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
812 #endif
813 ret = gnutls_x509_privkey_init(&gtls_key);
814 if (ret != 0) {
815 gnutls_global_deinit();
816 return WERR_INTERNAL_ERROR;
819 ret = gnutls_x509_privkey_generate(gtls_key, GNUTLS_PK_RSA, bits, 0);
820 if (ret != 0) {
821 werr = WERR_INTERNAL_ERROR;
822 goto done;
825 /* No need to check error code, this SHOULD fail */
826 gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, NULL, &len);
828 if (len < 1) {
829 werr = WERR_INTERNAL_ERROR;
830 goto done;
833 p0 = talloc_size(ctx, len);
834 if (p0 == NULL) {
835 werr = WERR_NOMEM;
836 goto done;
838 p = p0;
840 ret = gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, p0, &len);
842 if (ret != 0) {
843 werr = WERR_INTERNAL_ERROR;
844 goto done;
848 * To dump the key we can use :
849 * rk_dumpdata("h5lkey", p0, len);
851 ret = hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
852 p0, len, HX509_KEY_FORMAT_DER, pk);
854 if (ret != 0) {
855 werr = WERR_INTERNAL_ERROR;
856 goto done;
859 *rsa = d2i_RSAPrivateKey(NULL, &p, len);
860 TALLOC_FREE(p0);
862 if (*rsa == NULL) {
863 hx509_private_key_free(pk);
864 werr = WERR_INTERNAL_ERROR;
865 goto done;
868 RSA_returned_bits = BN_num_bits((*rsa)->n);
869 DEBUG(6, ("GnuTLS returned an RSA private key with %d bits\n", RSA_returned_bits));
871 if (RSA_returned_bits != bits) {
872 DEBUG(0, ("GnuTLS unexpectedly returned an RSA private key with %d bits, needed %d\n", RSA_returned_bits, bits));
873 hx509_private_key_free(pk);
874 werr = WERR_INTERNAL_ERROR;
875 goto done;
878 werr = WERR_OK;
880 done:
881 if (p0 != NULL) {
882 memset(p0, 0, len);
883 TALLOC_FREE(p0);
886 gnutls_x509_privkey_deinit(gtls_key);
887 gnutls_global_deinit();
888 return werr;
891 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
892 time_t lifetime, hx509_private_key *private_key,
893 hx509_cert *cert, DATA_BLOB *guidblob)
895 SubjectPublicKeyInfo spki;
896 hx509_name subject = NULL;
897 hx509_ca_tbs tbs;
898 struct heim_bit_string uniqueid;
899 struct heim_integer serialnumber;
900 int ret, i;
902 uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
903 if (uniqueid.data == NULL) {
904 return WERR_NOMEM;
906 /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
907 * so as 1 byte is 8 bits we need to provision 8 times more space as in the
908 * blob
910 uniqueid.length = 8 * guidblob->length;
912 serialnumber.data = talloc_array(ctx, uint8_t,
913 guidblob->length);
914 if (serialnumber.data == NULL) {
915 talloc_free(uniqueid.data);
916 return WERR_NOMEM;
919 /* Native AD generates certificates with serialnumber in reversed notation */
920 for (i = 0; i < guidblob->length; i++) {
921 uint8_t *reversed = (uint8_t *)serialnumber.data;
922 uint8_t *uncrypt = guidblob->data;
923 reversed[i] = uncrypt[guidblob->length - 1 - i];
925 serialnumber.length = guidblob->length;
926 serialnumber.negative = 0;
928 memset(&spki, 0, sizeof(spki));
930 ret = hx509_request_get_name(*hctx, *req, &subject);
931 if (ret !=0) {
932 goto fail_subject;
934 ret = hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
935 if (ret !=0) {
936 goto fail_spki;
939 ret = hx509_ca_tbs_init(*hctx, &tbs);
940 if (ret !=0) {
941 goto fail_tbs;
944 ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
945 if (ret !=0) {
946 goto fail;
948 ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
949 if (ret !=0) {
950 goto fail;
952 ret = hx509_ca_tbs_set_ca(*hctx, tbs, 1);
953 if (ret !=0) {
954 goto fail;
956 ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
957 if (ret !=0) {
958 goto fail;
960 ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
961 if (ret !=0) {
962 goto fail;
964 ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
965 if (ret !=0) {
966 goto fail;
968 ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
969 if (ret !=0) {
970 goto fail;
972 hx509_name_free(&subject);
973 free_SubjectPublicKeyInfo(&spki);
974 hx509_ca_tbs_free(&tbs);
976 return WERR_OK;
978 fail:
979 hx509_ca_tbs_free(&tbs);
980 fail_tbs:
981 free_SubjectPublicKeyInfo(&spki);
982 fail_spki:
983 hx509_name_free(&subject);
984 fail_subject:
985 talloc_free(uniqueid.data);
986 talloc_free(serialnumber.data);
987 return WERR_INTERNAL_ERROR;
990 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
991 hx509_private_key *signer,RSA **rsa, const char *dn)
993 int ret;
994 SubjectPublicKeyInfo key;
996 hx509_name name;
997 WERROR werr;
999 werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1000 if (!W_ERROR_IS_OK(werr)) {
1001 return werr;
1004 hx509_request_init(*hctx, req);
1005 ret = hx509_parse_name(*hctx, dn, &name);
1006 if (ret != 0) {
1007 RSA_free(*rsa);
1008 hx509_private_key_free(signer);
1009 hx509_request_free(req);
1010 hx509_name_free(&name);
1011 return WERR_INTERNAL_ERROR;
1014 ret = hx509_request_set_name(*hctx, *req, name);
1015 if (ret != 0) {
1016 RSA_free(*rsa);
1017 hx509_private_key_free(signer);
1018 hx509_request_free(req);
1019 hx509_name_free(&name);
1020 return WERR_INTERNAL_ERROR;
1022 hx509_name_free(&name);
1024 ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1025 if (ret != 0) {
1026 RSA_free(*rsa);
1027 hx509_private_key_free(signer);
1028 hx509_request_free(req);
1029 return WERR_INTERNAL_ERROR;
1031 ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1032 if (ret != 0) {
1033 RSA_free(*rsa);
1034 hx509_private_key_free(signer);
1035 free_SubjectPublicKeyInfo(&key);
1036 hx509_request_free(req);
1037 return WERR_INTERNAL_ERROR;
1040 free_SubjectPublicKeyInfo(&key);
1042 return WERR_OK;
1045 /* Return an error when we fail to generate a certificate */
1046 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1048 heim_octet_string data;
1049 WERROR werr;
1050 RSA *rsa;
1051 hx509_context hctx;
1052 hx509_private_key pk;
1053 hx509_request req;
1054 hx509_cert cert;
1055 DATA_BLOB blob;
1056 DATA_BLOB blobkeypair;
1057 DATA_BLOB *tmp;
1058 int ret;
1059 bool ok = true;
1060 struct GUID guid = GUID_random();
1061 NTSTATUS status;
1062 char *secret_name;
1063 struct bkrp_exported_RSA_key_pair keypair;
1064 enum ndr_err_code ndr_err;
1065 uint32_t nb_seconds_validity = 3600 * 24 * 365;
1067 DEBUG(6, ("Trying to generate a certificate\n"));
1068 hx509_context_init(&hctx);
1069 werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1070 if (!W_ERROR_IS_OK(werr)) {
1071 hx509_context_free(&hctx);
1072 return werr;
1075 status = GUID_to_ndr_blob(&guid, ctx, &blob);
1076 if (!NT_STATUS_IS_OK(status)) {
1077 hx509_context_free(&hctx);
1078 hx509_private_key_free(&pk);
1079 RSA_free(rsa);
1080 return WERR_INVALID_DATA;
1083 werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1084 if (!W_ERROR_IS_OK(werr)) {
1085 hx509_private_key_free(&pk);
1086 hx509_context_free(&hctx);
1087 return WERR_INVALID_DATA;
1090 ret = hx509_cert_binary(hctx, cert, &data);
1091 if (ret !=0) {
1092 hx509_cert_free(cert);
1093 hx509_private_key_free(&pk);
1094 hx509_context_free(&hctx);
1095 return WERR_INVALID_DATA;
1098 keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1099 keypair.cert.length = data.length;
1102 * Heimdal's bignum are big endian and the
1103 * structure expect it to be in little endian
1104 * so we reverse the buffer to make it work
1106 tmp = reverse_and_get_blob(ctx, rsa->e);
1107 if (tmp == NULL) {
1108 ok = false;
1109 } else {
1110 keypair.public_exponent = *tmp;
1111 SMB_ASSERT(tmp->length <= 4);
1113 * The value is now in little endian but if can happen that the length is
1114 * less than 4 bytes.
1115 * So if we have less than 4 bytes we pad with zeros so that it correctly
1116 * fit into the structure.
1118 if (tmp->length < 4) {
1120 * We need the expo to fit 4 bytes
1122 keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1123 memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1124 keypair.public_exponent.length = 4;
1128 tmp = reverse_and_get_blob(ctx,rsa->d);
1129 if (tmp == NULL) {
1130 ok = false;
1131 } else {
1132 keypair.private_exponent = *tmp;
1135 tmp = reverse_and_get_blob(ctx,rsa->n);
1136 if (tmp == NULL) {
1137 ok = false;
1138 } else {
1139 keypair.modulus = *tmp;
1142 tmp = reverse_and_get_blob(ctx,rsa->p);
1143 if (tmp == NULL) {
1144 ok = false;
1145 } else {
1146 keypair.prime1 = *tmp;
1149 tmp = reverse_and_get_blob(ctx,rsa->q);
1150 if (tmp == NULL) {
1151 ok = false;
1152 } else {
1153 keypair.prime2 = *tmp;
1156 tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1157 if (tmp == NULL) {
1158 ok = false;
1159 } else {
1160 keypair.exponent1 = *tmp;
1163 tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1164 if (tmp == NULL) {
1165 ok = false;
1166 } else {
1167 keypair.exponent2 = *tmp;
1170 tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1171 if (tmp == NULL) {
1172 ok = false;
1173 } else {
1174 keypair.coefficient = *tmp;
1177 /* One of the keypair allocation was wrong */
1178 if (ok == false) {
1179 der_free_octet_string(&data);
1180 hx509_cert_free(cert);
1181 hx509_private_key_free(&pk);
1182 hx509_context_free(&hctx);
1183 RSA_free(rsa);
1184 return WERR_INVALID_DATA;
1186 keypair.certificate_len = keypair.cert.length;
1187 ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1188 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1189 der_free_octet_string(&data);
1190 hx509_cert_free(cert);
1191 hx509_private_key_free(&pk);
1192 hx509_context_free(&hctx);
1193 RSA_free(rsa);
1194 return WERR_INVALID_DATA;
1197 secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1198 if (secret_name == NULL) {
1199 der_free_octet_string(&data);
1200 hx509_cert_free(cert);
1201 hx509_private_key_free(&pk);
1202 hx509_context_free(&hctx);
1203 RSA_free(rsa);
1204 return WERR_OUTOFMEMORY;
1207 status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1208 if (!NT_STATUS_IS_OK(status)) {
1209 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1211 talloc_free(secret_name);
1213 GUID_to_ndr_blob(&guid, ctx, &blob);
1214 status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1215 if (!NT_STATUS_IS_OK(status)) {
1216 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1219 der_free_octet_string(&data);
1220 hx509_cert_free(cert);
1221 hx509_private_key_free(&pk);
1222 hx509_context_free(&hctx);
1223 RSA_free(rsa);
1224 return WERR_OK;
1227 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1228 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1230 struct GUID guid;
1231 char *guid_string;
1232 DATA_BLOB lsa_secret;
1233 enum ndr_err_code ndr_err;
1234 NTSTATUS status;
1237 * here we basicaly need to return our certificate
1238 * search for lsa secret BCKUPKEY_PREFERRED first
1241 status = get_lsa_secret(mem_ctx,
1242 ldb_ctx,
1243 "BCKUPKEY_PREFERRED",
1244 &lsa_secret);
1245 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1246 /* Ok we can be in this case if there was no certs */
1247 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1248 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1249 lpcfg_realm(lp_ctx));
1251 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1252 if (!W_ERROR_IS_OK(werr)) {
1253 return WERR_INVALID_PARAMETER;
1255 status = get_lsa_secret(mem_ctx,
1256 ldb_ctx,
1257 "BCKUPKEY_PREFERRED",
1258 &lsa_secret);
1260 if (!NT_STATUS_IS_OK(status)) {
1261 /* Ok we really don't manage to get this certs ...*/
1262 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1263 return WERR_FILE_NOT_FOUND;
1265 } else if (!NT_STATUS_IS_OK(status)) {
1266 return WERR_INTERNAL_ERROR;
1269 if (lsa_secret.length == 0) {
1270 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1271 return WERR_INTERNAL_ERROR;
1272 } else {
1273 char *cert_secret_name;
1275 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1276 if (!NT_STATUS_IS_OK(status)) {
1277 return WERR_FILE_NOT_FOUND;
1280 guid_string = GUID_string(mem_ctx, &guid);
1281 if (guid_string == NULL) {
1282 /* We return file not found because the client
1283 * expect this error
1285 return WERR_FILE_NOT_FOUND;
1288 cert_secret_name = talloc_asprintf(mem_ctx,
1289 "BCKUPKEY_%s",
1290 guid_string);
1291 status = get_lsa_secret(mem_ctx,
1292 ldb_ctx,
1293 cert_secret_name,
1294 &lsa_secret);
1295 if (!NT_STATUS_IS_OK(status)) {
1296 return WERR_FILE_NOT_FOUND;
1299 if (lsa_secret.length != 0) {
1300 struct bkrp_exported_RSA_key_pair keypair;
1301 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1302 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1303 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1304 return WERR_FILE_NOT_FOUND;
1306 *(r->out.data_out_len) = keypair.cert.length;
1307 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1308 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1309 return WERR_OK;
1310 } else {
1311 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1312 return WERR_INTERNAL_ERROR;
1316 return WERR_NOT_SUPPORTED;
1319 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1321 struct GUID guid = GUID_random();
1322 enum ndr_err_code ndr_err;
1323 DATA_BLOB blob_wrap_key, guid_blob;
1324 struct bkrp_dc_serverwrap_key wrap_key;
1325 NTSTATUS status;
1326 char *secret_name;
1327 TALLOC_CTX *frame = talloc_stackframe();
1329 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1331 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1332 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1333 TALLOC_FREE(frame);
1334 return WERR_INVALID_DATA;
1337 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1338 if (secret_name == NULL) {
1339 TALLOC_FREE(frame);
1340 return WERR_NOMEM;
1343 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1344 if (!NT_STATUS_IS_OK(status)) {
1345 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1346 TALLOC_FREE(frame);
1347 return WERR_INTERNAL_ERROR;
1350 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1351 if (!NT_STATUS_IS_OK(status)) {
1352 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1353 TALLOC_FREE(frame);
1356 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1357 if (!NT_STATUS_IS_OK(status)) {
1358 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1359 TALLOC_FREE(frame);
1360 return WERR_INTERNAL_ERROR;
1363 TALLOC_FREE(frame);
1365 return WERR_OK;
1369 * Find the specified decryption keys from the LSA secrets store as
1370 * G$BCKUPKEY_keyGuidString.
1373 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1374 struct bkrp_dc_serverwrap_key *server_key,
1375 struct GUID *guid)
1377 NTSTATUS status;
1378 DATA_BLOB guid_binary, lsa_secret;
1379 char *secret_name;
1380 char *guid_string;
1381 enum ndr_err_code ndr_err;
1383 guid_string = GUID_string(mem_ctx, guid);
1384 if (guid_string == NULL) {
1385 /* We return file not found because the client
1386 * expect this error
1388 return WERR_FILE_NOT_FOUND;
1391 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1392 if (secret_name == NULL) {
1393 return WERR_NOMEM;
1396 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1397 if (!NT_STATUS_IS_OK(status)) {
1398 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1399 return WERR_INVALID_DATA;
1400 } else if (guid_binary.length == 0) {
1401 /* RODC case, we do not have secrets locally */
1402 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1403 secret_name));
1404 return WERR_INTERNAL_ERROR;
1406 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1407 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1408 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1409 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1410 return WERR_INVALID_DATA;
1413 return WERR_OK;
1417 * Find the current, preferred ServerWrap Key by looking at
1418 * G$BCKUPKEY_P in the LSA secrets store.
1420 * Then find the current decryption keys from the LSA secrets store as
1421 * G$BCKUPKEY_keyGuidString.
1424 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1425 struct ldb_context *ldb_ctx,
1426 struct bkrp_dc_serverwrap_key *server_key,
1427 struct GUID *returned_guid)
1429 NTSTATUS status;
1430 DATA_BLOB guid_binary;
1432 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1433 if (!NT_STATUS_IS_OK(status)) {
1434 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1435 return WERR_FILE_NOT_FOUND;
1436 } else if (guid_binary.length == 0) {
1437 /* RODC case, we do not have secrets locally */
1438 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1439 return WERR_INTERNAL_ERROR;
1442 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1443 if (!NT_STATUS_IS_OK(status)) {
1444 return WERR_FILE_NOT_FOUND;
1447 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1448 server_key, returned_guid);
1451 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1452 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1454 WERROR werr;
1455 struct bkrp_server_side_wrapped decrypt_request;
1456 DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1457 DATA_BLOB blob;
1458 enum ndr_err_code ndr_err;
1459 struct bkrp_dc_serverwrap_key server_key;
1460 struct bkrp_rc4encryptedpayload rc4payload;
1461 struct dom_sid *caller_sid;
1462 uint8_t symkey[20]; /* SHA-1 hash len */
1463 uint8_t mackey[20]; /* SHA-1 hash len */
1464 uint8_t mac[20]; /* SHA-1 hash len */
1465 unsigned int hash_len;
1466 HMAC_CTX ctx;
1468 blob.data = r->in.data_in;
1469 blob.length = r->in.data_in_len;
1471 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1472 return WERR_INVALID_PARAM;
1475 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &decrypt_request,
1476 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1477 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1478 return WERR_INVALID_PARAM;
1481 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1482 return WERR_INVALID_PARAM;
1485 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1486 &decrypt_request.guid);
1487 if (!W_ERROR_IS_OK(werr)) {
1488 return werr;
1491 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1493 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1496 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1497 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1499 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1500 decrypt_request.r2, sizeof(decrypt_request.r2),
1501 symkey, &hash_len);
1503 dump_data_pw("symkey: \n", symkey, hash_len);
1505 /* rc4 decrypt sid and secret using sym key */
1506 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1508 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1509 decrypt_request.ciphertext_length);
1511 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1513 ndr_err = ndr_pull_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1514 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1515 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1516 return WERR_INVALID_PARAM;
1519 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1520 return WERR_INVALID_PARAM;
1523 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1526 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1527 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1529 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1530 rc4payload.r3, sizeof(rc4payload.r3),
1531 mackey, &hash_len);
1533 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1535 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1536 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1537 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1538 return WERR_INTERNAL_ERROR;
1541 HMAC_CTX_init(&ctx);
1542 HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1543 /* SID field */
1544 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1545 /* Secret field */
1546 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1547 HMAC_Final(&ctx, mac, &hash_len);
1548 HMAC_CTX_cleanup(&ctx);
1550 dump_data_pw("mac: \n", mac, sizeof(mac));
1551 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1553 if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1554 return WERR_INVALID_ACCESS;
1557 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1559 if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1560 return WERR_INVALID_ACCESS;
1563 *(r->out.data_out) = rc4payload.secret_data.data;
1564 *(r->out.data_out_len) = rc4payload.secret_data.length;
1566 return WERR_OK;
1570 * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1571 * determine what type of restore is wanted.
1573 * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1576 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1577 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1579 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1580 return WERR_INVALID_PARAM;
1583 if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1584 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1587 return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1591 * We have some data, such as saved website or IMAP passwords that the
1592 * client would like to put into the profile on-disk. This needs to
1593 * be encrypted. This version gives the server the data over the
1594 * network (protected only by the negotiated transport encryption),
1595 * and asks that it be encrypted and returned for long-term storage.
1597 * The data is NOT stored in the LSA, but a key to encrypt the data
1598 * will be stored. There is only one active encryption key per domain,
1599 * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1601 * The potentially multiple valid decryptiong keys (and the encryption
1602 * key) are in turn stored in the LSA secrets store as
1603 * G$BCKUPKEY_keyGuidString.
1607 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1608 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1610 DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1611 WERROR werr;
1612 struct dom_sid *caller_sid;
1613 uint8_t symkey[20]; /* SHA-1 hash len */
1614 uint8_t mackey[20]; /* SHA-1 hash len */
1615 unsigned int hash_len;
1616 struct bkrp_rc4encryptedpayload rc4payload;
1617 HMAC_CTX ctx;
1618 struct bkrp_dc_serverwrap_key server_key;
1619 enum ndr_err_code ndr_err;
1620 struct bkrp_server_side_wrapped server_side_wrapped;
1621 struct GUID guid;
1623 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1624 return WERR_INVALID_PARAM;
1627 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1628 ldb_ctx, &server_key,
1629 &guid);
1631 if (!W_ERROR_IS_OK(werr)) {
1632 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1633 /* Generate the server wrap key since one wasn't found */
1634 werr = generate_bkrp_server_wrap_key(mem_ctx,
1635 ldb_ctx);
1636 if (!W_ERROR_IS_OK(werr)) {
1637 return WERR_INVALID_PARAMETER;
1639 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1640 ldb_ctx,
1641 &server_key,
1642 &guid);
1644 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1645 /* Ok we really don't manage to get this secret ...*/
1646 return WERR_FILE_NOT_FOUND;
1648 } else {
1649 /* In theory we should NEVER reach this point as it
1650 should only appear in a rodc server */
1651 /* we do not have the real secret attribute */
1652 return WERR_INVALID_PARAMETER;
1656 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1658 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1661 * This is the key derivation step, so that the HMAC and RC4
1662 * operations over the user-supplied data are not able to
1663 * disclose the master key. By using random data, the symkey
1664 * and mackey values are unique for this operation, and
1665 * discovering these (by reversing the RC4 over the
1666 * attacker-controlled data) does not return something able to
1667 * be used to decyrpt the encrypted data of other users
1669 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1671 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1673 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1675 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1679 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1680 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1682 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1683 server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1684 symkey, &hash_len);
1686 dump_data_pw("symkey: \n", symkey, hash_len);
1689 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1690 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1692 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1693 rc4payload.r3, sizeof(rc4payload.r3),
1694 mackey, &hash_len);
1696 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1698 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1699 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1700 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1701 return WERR_INTERNAL_ERROR;
1704 rc4payload.secret_data.data = r->in.data_in;
1705 rc4payload.secret_data.length = r->in.data_in_len;
1708 HMAC_CTX_init(&ctx);
1709 HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1710 /* SID field */
1711 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1712 /* Secret field */
1713 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1714 HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1715 HMAC_CTX_cleanup(&ctx);
1717 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1719 rc4payload.sid = *caller_sid;
1721 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1722 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1723 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1724 return WERR_INTERNAL_ERROR;
1727 /* rc4 encrypt sid and secret using sym key */
1728 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1729 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1731 /* create server wrap structure */
1733 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1734 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1735 server_side_wrapped.guid = guid;
1736 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1738 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1739 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1740 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1741 return WERR_INTERNAL_ERROR;
1745 *(r->out.data_out) = server_wrapped_blob.data;
1746 *(r->out.data_out_len) = server_wrapped_blob.length;
1748 return WERR_OK;
1751 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1752 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1754 WERROR error = WERR_INVALID_PARAM;
1755 struct ldb_context *ldb_ctx;
1756 bool is_rodc;
1757 const char *addr = "unknown";
1758 /* At which level we start to add more debug of what is done in the protocol */
1759 const int debuglevel = 4;
1761 if (DEBUGLVL(debuglevel)) {
1762 const struct tsocket_address *remote_address;
1763 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1764 if (tsocket_address_is_inet(remote_address, "ip")) {
1765 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1766 W_ERROR_HAVE_NO_MEMORY(addr);
1770 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1771 return WERR_NOT_SUPPORTED;
1774 if (!dce_call->conn->auth_state.auth_info ||
1775 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1776 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1779 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1780 dce_call->conn->dce_ctx->lp_ctx,
1781 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1783 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1784 talloc_unlink(mem_ctx, ldb_ctx);
1785 return WERR_INVALID_PARAM;
1788 if (!is_rodc) {
1789 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1790 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1791 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1792 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1795 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1796 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1797 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1798 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1801 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1802 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1803 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1804 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1807 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1808 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1809 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1810 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1813 /*else: I am a RODC so I don't handle backup key protocol */
1815 talloc_unlink(mem_ctx, ldb_ctx);
1816 return error;
1819 /* include the generated boilerplate */
1820 #include "librpc/gen_ndr/ndr_backupkey_s.c"