lib:torture: Make variables const
[Samba.git] / source4 / rpc_server / backupkey / dcesrv_backupkey_heimdal.c
blob5985d52c99b2857f3f2cbe3c7107cd851c1200a7
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 "libds/common/roles.h"
45 #include <gnutls/gnutls.h>
46 #include <gnutls/x509.h>
47 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
48 #include <gcrypt.h>
49 #endif
51 #define DCESRV_INTERFACE_BACKUPKEY_BIND(call, iface) \
52 dcesrv_interface_backupkey_bind(call, iface)
53 static NTSTATUS dcesrv_interface_backupkey_bind(struct dcesrv_call_state *dce_call,
54 const struct dcesrv_interface *iface)
56 return dcesrv_interface_bind_require_privacy(dce_call, iface);
59 static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
60 /* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
61 static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
62 { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
65 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
66 struct ldb_context *ldb,
67 const char *name,
68 const DATA_BLOB *lsa_secret)
70 struct ldb_message *msg;
71 struct ldb_result *res;
72 struct ldb_dn *domain_dn;
73 struct ldb_dn *system_dn;
74 struct ldb_val val;
75 int ret;
76 char *name2;
77 struct timeval now = timeval_current();
78 NTTIME nt_now = timeval_to_nttime(&now);
79 const char *attrs[] = {
80 NULL
83 domain_dn = ldb_get_default_basedn(ldb);
84 if (!domain_dn) {
85 return NT_STATUS_INTERNAL_ERROR;
88 msg = ldb_msg_new(mem_ctx);
89 if (msg == NULL) {
90 return NT_STATUS_NO_MEMORY;
94 * This function is a lot like dcesrv_lsa_CreateSecret
95 * in the rpc_server/lsa directory
96 * The reason why we duplicate the effort here is that:
97 * * we want to keep the former function static
98 * * we want to avoid the burden of doing LSA calls
99 * when we can just manipulate the secrets directly
100 * * taillor the function to the particular needs of backup protocol
103 system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
104 if (system_dn == NULL) {
105 talloc_free(msg);
106 return NT_STATUS_NO_MEMORY;
109 name2 = talloc_asprintf(msg, "%s Secret", name);
110 if (name2 == NULL) {
111 talloc_free(msg);
112 return NT_STATUS_NO_MEMORY;
115 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
116 "(&(cn=%s)(objectclass=secret))",
117 ldb_binary_encode_string(mem_ctx, name2));
119 if (ret != LDB_SUCCESS || res->count != 0 ) {
120 DEBUG(2, ("Secret %s already exists !\n", name2));
121 talloc_free(msg);
122 return NT_STATUS_OBJECT_NAME_COLLISION;
126 * We don't care about previous value as we are
127 * here only if the key didn't exists before
130 msg->dn = ldb_dn_copy(mem_ctx, system_dn);
131 if (msg->dn == NULL) {
132 talloc_free(msg);
133 return NT_STATUS_NO_MEMORY;
135 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
136 talloc_free(msg);
137 return NT_STATUS_NO_MEMORY;
140 ret = ldb_msg_add_string(msg, "cn", name2);
141 if (ret != LDB_SUCCESS) {
142 talloc_free(msg);
143 return NT_STATUS_NO_MEMORY;
145 ret = ldb_msg_add_string(msg, "objectClass", "secret");
146 if (ret != LDB_SUCCESS) {
147 talloc_free(msg);
148 return NT_STATUS_NO_MEMORY;
150 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
151 if (ret != LDB_SUCCESS) {
152 talloc_free(msg);
153 return NT_STATUS_NO_MEMORY;
155 val.data = lsa_secret->data;
156 val.length = lsa_secret->length;
157 ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
158 if (ret != LDB_SUCCESS) {
159 talloc_free(msg);
160 return NT_STATUS_NO_MEMORY;
162 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
163 if (ret != LDB_SUCCESS) {
164 talloc_free(msg);
165 return NT_STATUS_NO_MEMORY;
169 * create the secret with DSDB_MODIFY_RELAX
170 * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
171 * the create of LSA secret object
173 ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
174 if (ret != LDB_SUCCESS) {
175 DEBUG(2,("Failed to create secret record %s: %s\n",
176 ldb_dn_get_linearized(msg->dn),
177 ldb_errstring(ldb)));
178 talloc_free(msg);
179 return NT_STATUS_ACCESS_DENIED;
182 talloc_free(msg);
183 return NT_STATUS_OK;
186 /* This function is pretty much like dcesrv_lsa_QuerySecret */
187 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
188 struct ldb_context *ldb,
189 const char *name,
190 DATA_BLOB *lsa_secret)
192 TALLOC_CTX *tmp_mem;
193 struct ldb_result *res;
194 struct ldb_dn *domain_dn;
195 struct ldb_dn *system_dn;
196 const struct ldb_val *val;
197 uint8_t *data;
198 const char *attrs[] = {
199 "currentValue",
200 NULL
202 int ret;
204 lsa_secret->data = NULL;
205 lsa_secret->length = 0;
207 domain_dn = ldb_get_default_basedn(ldb);
208 if (!domain_dn) {
209 return NT_STATUS_INTERNAL_ERROR;
212 tmp_mem = talloc_new(mem_ctx);
213 if (tmp_mem == NULL) {
214 return NT_STATUS_NO_MEMORY;
217 system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
218 if (system_dn == NULL) {
219 talloc_free(tmp_mem);
220 return NT_STATUS_NO_MEMORY;
223 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
224 "(&(cn=%s Secret)(objectclass=secret))",
225 ldb_binary_encode_string(tmp_mem, name));
227 if (ret != LDB_SUCCESS) {
228 talloc_free(tmp_mem);
229 return NT_STATUS_INTERNAL_DB_CORRUPTION;
231 if (res->count == 0) {
232 talloc_free(tmp_mem);
233 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
235 if (res->count > 1) {
236 DEBUG(2, ("Secret %s collision\n", name));
237 talloc_free(tmp_mem);
238 return NT_STATUS_INTERNAL_DB_CORRUPTION;
241 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
242 if (val == NULL) {
244 * The secret object is here but we don't have the secret value
245 * The most common case is a RODC
247 *lsa_secret = data_blob_null;
248 talloc_free(tmp_mem);
249 return NT_STATUS_OK;
252 data = val->data;
253 lsa_secret->data = talloc_move(mem_ctx, &data);
254 lsa_secret->length = val->length;
256 talloc_free(tmp_mem);
257 return NT_STATUS_OK;
260 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
262 DATA_BLOB blob;
263 DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
264 uint32_t i;
266 blob.length = BN_num_bytes(bn);
267 blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
269 if (blob.data == NULL) {
270 return NULL;
273 BN_bn2bin(bn, blob.data);
275 rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
276 if (rev->data == NULL) {
277 return NULL;
280 for(i=0; i < blob.length; i++) {
281 rev->data[i] = blob.data[blob.length - i -1];
283 rev->length = blob.length;
284 talloc_free(blob.data);
285 return rev;
288 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
290 BIGNUM *ret;
291 DATA_BLOB rev;
292 uint32_t i;
294 rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
295 if (rev.data == NULL) {
296 return NULL;
299 for(i=0; i < blob->length; i++) {
300 rev.data[i] = blob->data[blob->length - i -1];
302 rev.length = blob->length;
304 ret = BN_bin2bn(rev.data, rev.length, NULL);
305 talloc_free(rev.data);
307 return ret;
310 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
311 struct bkrp_exported_RSA_key_pair *keypair,
312 hx509_private_key *pk)
314 hx509_context hctx;
315 RSA *rsa;
316 struct hx509_private_key_ops *ops;
317 hx509_private_key privkey = NULL;
319 hx509_context_init(&hctx);
320 ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
321 if (ops == NULL) {
322 DEBUG(2, ("Not supported algorithm\n"));
323 hx509_context_free(&hctx);
324 return NT_STATUS_INTERNAL_ERROR;
327 if (hx509_private_key_init(&privkey, ops, NULL) != 0) {
328 hx509_context_free(&hctx);
329 return NT_STATUS_NO_MEMORY;
332 rsa = RSA_new();
333 if (rsa ==NULL) {
334 hx509_private_key_free(&privkey);
335 hx509_context_free(&hctx);
336 return NT_STATUS_INVALID_PARAMETER;
339 rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
340 if (rsa->n == NULL) {
341 RSA_free(rsa);
342 hx509_private_key_free(&privkey);
343 hx509_context_free(&hctx);
344 return NT_STATUS_INVALID_PARAMETER;
346 rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
347 if (rsa->d == NULL) {
348 RSA_free(rsa);
349 hx509_private_key_free(&privkey);
350 hx509_context_free(&hctx);
351 return NT_STATUS_INVALID_PARAMETER;
353 rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
354 if (rsa->p == NULL) {
355 RSA_free(rsa);
356 hx509_private_key_free(&privkey);
357 hx509_context_free(&hctx);
358 return NT_STATUS_INVALID_PARAMETER;
360 rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
361 if (rsa->q == NULL) {
362 RSA_free(rsa);
363 hx509_private_key_free(&privkey);
364 hx509_context_free(&hctx);
365 return NT_STATUS_INVALID_PARAMETER;
367 rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
368 if (rsa->dmp1 == NULL) {
369 RSA_free(rsa);
370 hx509_private_key_free(&privkey);
371 hx509_context_free(&hctx);
372 return NT_STATUS_INVALID_PARAMETER;
374 rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
375 if (rsa->dmq1 == NULL) {
376 RSA_free(rsa);
377 hx509_private_key_free(&privkey);
378 hx509_context_free(&hctx);
379 return NT_STATUS_INVALID_PARAMETER;
381 rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
382 if (rsa->iqmp == NULL) {
383 RSA_free(rsa);
384 hx509_private_key_free(&privkey);
385 hx509_context_free(&hctx);
386 return NT_STATUS_INVALID_PARAMETER;
388 rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
389 if (rsa->e == NULL) {
390 RSA_free(rsa);
391 hx509_private_key_free(&privkey);
392 hx509_context_free(&hctx);
393 return NT_STATUS_INVALID_PARAMETER;
396 *pk = privkey;
398 hx509_private_key_assign_rsa(*pk, rsa);
400 hx509_context_free(&hctx);
401 return NT_STATUS_OK;
404 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
405 uint32_t version,
406 uint8_t *key_and_iv,
407 uint8_t *access_check,
408 uint32_t access_check_len,
409 struct auth_session_info *session_info)
411 heim_octet_string iv;
412 heim_octet_string access_check_os;
413 hx509_crypto crypto;
415 DATA_BLOB blob_us;
416 uint32_t key_len;
417 uint32_t iv_len;
418 int res;
419 enum ndr_err_code ndr_err;
420 hx509_context hctx;
422 struct dom_sid *access_sid = NULL;
423 struct dom_sid *caller_sid = NULL;
425 /* This one should not be freed */
426 const AlgorithmIdentifier *alg;
428 switch (version) {
429 case 2:
430 key_len = 24;
431 iv_len = 8;
432 alg = hx509_crypto_des_rsdi_ede3_cbc();
433 break;
435 case 3:
436 key_len = 32;
437 iv_len = 16;
438 alg =hx509_crypto_aes256_cbc();
439 break;
441 default:
442 return WERR_INVALID_DATA;
445 hx509_context_init(&hctx);
446 res = hx509_crypto_init(hctx, NULL,
447 &(alg->algorithm),
448 &crypto);
449 hx509_context_free(&hctx);
451 if (res != 0) {
452 return WERR_INVALID_DATA;
455 res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
457 iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
458 iv.length = iv_len;
460 if (res != 0) {
461 hx509_crypto_destroy(crypto);
462 return WERR_INVALID_DATA;
465 hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
466 res = hx509_crypto_decrypt(crypto,
467 access_check,
468 access_check_len,
469 &iv,
470 &access_check_os);
472 if (res != 0) {
473 hx509_crypto_destroy(crypto);
474 return WERR_INVALID_DATA;
477 blob_us.data = access_check_os.data;
478 blob_us.length = access_check_os.length;
480 hx509_crypto_destroy(crypto);
482 switch (version) {
483 case 2:
485 uint32_t hash_size = 20;
486 uint8_t hash[hash_size];
487 struct sha sctx;
488 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
490 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
491 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
492 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
493 /* Unable to unmarshall */
494 der_free_octet_string(&access_check_os);
495 return WERR_INVALID_DATA;
497 if (uncrypted_accesscheckv2.magic != 0x1) {
498 /* wrong magic */
499 der_free_octet_string(&access_check_os);
500 return WERR_INVALID_DATA;
503 SHA1_Init(&sctx);
504 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
505 SHA1_Final(hash, &sctx);
506 der_free_octet_string(&access_check_os);
508 * We free it after the sha1 calculation because blob.data
509 * point to the same area
512 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
513 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
514 return WERR_INVALID_DATA;
516 access_sid = &(uncrypted_accesscheckv2.sid);
517 break;
519 case 3:
521 uint32_t hash_size = 64;
522 uint8_t hash[hash_size];
523 struct hc_sha512state sctx;
524 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
526 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
527 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
528 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
529 /* Unable to unmarshall */
530 der_free_octet_string(&access_check_os);
531 return WERR_INVALID_DATA;
533 if (uncrypted_accesscheckv3.magic != 0x1) {
534 /* wrong magic */
535 der_free_octet_string(&access_check_os);
536 return WERR_INVALID_DATA;
539 SHA512_Init(&sctx);
540 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
541 SHA512_Final(hash, &sctx);
542 der_free_octet_string(&access_check_os);
544 * We free it after the sha1 calculation because blob.data
545 * point to the same area
548 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
549 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
550 return WERR_INVALID_DATA;
552 access_sid = &(uncrypted_accesscheckv3.sid);
553 break;
555 default:
556 /* Never reached normally as we filtered at the switch / case level */
557 return WERR_INVALID_DATA;
560 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
562 if (!dom_sid_equal(caller_sid, access_sid)) {
563 return WERR_INVALID_ACCESS;
565 return WERR_OK;
569 * We have some data, such as saved website or IMAP passwords that the
570 * client has in profile on-disk. This needs to be decrypted. This
571 * version gives the server the data over the network (protected by
572 * the X.509 certificate and public key encryption, and asks that it
573 * be decrypted returned for short-term use, protected only by the
574 * negotiated transport encryption.
576 * The data is NOT stored in the LSA, but a X.509 certificate, public
577 * and private keys used to encrypt the data will be stored. There is
578 * only one active encryption key pair and certificate per domain, it
579 * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
581 * The potentially multiple valid decrypting key pairs are in turn
582 * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
585 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
586 TALLOC_CTX *mem_ctx,
587 struct bkrp_BackupKey *r,
588 struct ldb_context *ldb_ctx)
590 struct bkrp_client_side_wrapped uncrypt_request;
591 DATA_BLOB blob;
592 enum ndr_err_code ndr_err;
593 char *guid_string;
594 char *cert_secret_name;
595 DATA_BLOB lsa_secret;
596 DATA_BLOB *uncrypted_data = NULL;
597 NTSTATUS status;
598 uint32_t requested_version;
600 blob.data = r->in.data_in;
601 blob.length = r->in.data_in_len;
603 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
604 return WERR_INVALID_PARAMETER;
608 * We check for the version here, so we can actually print the
609 * message as we are unlikely to parse it with NDR.
611 requested_version = IVAL(r->in.data_in, 0);
612 if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
613 && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
614 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
615 return WERR_INVALID_PARAMETER;
618 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
619 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
620 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
621 return WERR_INVALID_PARAMETER;
624 if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
625 && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
626 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
627 return WERR_INVALID_PARAMETER;
630 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
631 if (guid_string == NULL) {
632 return WERR_NOT_ENOUGH_MEMORY;
635 cert_secret_name = talloc_asprintf(mem_ctx,
636 "BCKUPKEY_%s",
637 guid_string);
638 if (cert_secret_name == NULL) {
639 return WERR_NOT_ENOUGH_MEMORY;
642 status = get_lsa_secret(mem_ctx,
643 ldb_ctx,
644 cert_secret_name,
645 &lsa_secret);
646 if (!NT_STATUS_IS_OK(status)) {
647 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
648 return WERR_INVALID_DATA;
649 } else if (lsa_secret.length == 0) {
650 /* we do not have the real secret attribute, like if we are an RODC */
651 return WERR_INVALID_PARAMETER;
652 } else {
653 hx509_context hctx;
654 struct bkrp_exported_RSA_key_pair keypair;
655 hx509_private_key pk;
656 uint32_t i, res;
657 heim_octet_string reversed_secret;
658 heim_octet_string uncrypted_secret;
659 AlgorithmIdentifier alg;
660 DATA_BLOB blob_us;
661 WERROR werr;
663 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
664 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
665 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
666 return WERR_FILE_NOT_FOUND;
669 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
670 if (!NT_STATUS_IS_OK(status)) {
671 return WERR_INTERNAL_ERROR;
674 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
675 uncrypt_request.encrypted_secret_len);
676 if (reversed_secret.data == NULL) {
677 hx509_private_key_free(&pk);
678 return WERR_NOT_ENOUGH_MEMORY;
681 /* The secret has to be reversed ... */
682 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
683 uint8_t *reversed = (uint8_t *)reversed_secret.data;
684 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
685 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
687 reversed_secret.length = uncrypt_request.encrypted_secret_len;
690 * Let's try to decrypt the secret now that
691 * we have the private key ...
693 hx509_context_init(&hctx);
694 res = hx509_private_key_private_decrypt(hctx, &reversed_secret,
695 &alg.algorithm, pk,
696 &uncrypted_secret);
697 hx509_context_free(&hctx);
698 hx509_private_key_free(&pk);
699 if (res != 0) {
700 /* We are not able to decrypt the secret, looks like something is wrong */
701 return WERR_INVALID_PARAMETER;
703 blob_us.data = uncrypted_secret.data;
704 blob_us.length = uncrypted_secret.length;
706 if (uncrypt_request.version == 2) {
707 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
709 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
710 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
711 der_free_octet_string(&uncrypted_secret);
712 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
713 /* Unable to unmarshall */
714 return WERR_INVALID_DATA;
716 if (uncrypted_secretv2.magic != 0x20) {
717 /* wrong magic */
718 return WERR_INVALID_DATA;
721 werr = get_and_verify_access_check(mem_ctx, 2,
722 uncrypted_secretv2.payload_key,
723 uncrypt_request.access_check,
724 uncrypt_request.access_check_len,
725 dce_call->conn->auth_state.session_info);
726 if (!W_ERROR_IS_OK(werr)) {
727 return werr;
729 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
730 if (uncrypted_data == NULL) {
731 return WERR_INVALID_DATA;
734 uncrypted_data->data = uncrypted_secretv2.secret;
735 uncrypted_data->length = uncrypted_secretv2.secret_len;
737 if (uncrypt_request.version == 3) {
738 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
740 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
741 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
743 der_free_octet_string(&uncrypted_secret);
744 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
745 /* Unable to unmarshall */
746 return WERR_INVALID_DATA;
749 if (uncrypted_secretv3.magic1 != 0x30 ||
750 uncrypted_secretv3.magic2 != 0x6610 ||
751 uncrypted_secretv3.magic3 != 0x800e) {
752 /* wrong magic */
753 return WERR_INVALID_DATA;
757 * Confirm that the caller is permitted to
758 * read this particular data. Because one key
759 * pair is used per domain, the caller could
760 * have stolen the profile data on-disk and
761 * would otherwise be able to read the
762 * passwords.
765 werr = get_and_verify_access_check(mem_ctx, 3,
766 uncrypted_secretv3.payload_key,
767 uncrypt_request.access_check,
768 uncrypt_request.access_check_len,
769 dce_call->conn->auth_state.session_info);
770 if (!W_ERROR_IS_OK(werr)) {
771 return werr;
774 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
775 if (uncrypted_data == NULL) {
776 return WERR_INVALID_DATA;
779 uncrypted_data->data = uncrypted_secretv3.secret;
780 uncrypted_data->length = uncrypted_secretv3.secret_len;
784 * Yeah if we are here all looks pretty good:
785 * - hash is ok
786 * - user sid is the same as the one in access check
787 * - we were able to decrypt the whole stuff
791 if (uncrypted_data->data == NULL) {
792 return WERR_INVALID_DATA;
795 /* There is a magic value a the beginning of the data
796 * we can use an adhoc structure but as the
797 * parent structure is just an array of bytes it a lot of work
798 * work just prepending 4 bytes
800 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
801 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
802 memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
803 *(r->out.data_out_len) = uncrypted_data->length + 4;
805 return WERR_OK;
809 * Strictly, this function no longer uses Heimdal in order to generate an RSA
810 * key, but GnuTLS.
812 * The resulting key is then imported into Heimdal's RSA structure.
814 * We use GnuTLS because it can reliably generate 2048 bit keys every time.
815 * Windows clients strictly require 2048, no more since it won't fit and no
816 * less either. Heimdal would almost always generate a smaller key.
818 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
819 hx509_private_key *pk, RSA **rsa)
821 int ret;
822 uint8_t *p0 = NULL;
823 const uint8_t *p;
824 size_t len;
825 int bits = 2048;
826 int RSA_returned_bits;
827 gnutls_x509_privkey_t gtls_key;
828 WERROR werr;
830 *rsa = NULL;
832 ret = gnutls_global_init();
833 if (ret != GNUTLS_E_SUCCESS) {
834 DBG_ERR("TLS error: %s\n", gnutls_strerror(ret));
835 return WERR_INTERNAL_ERROR;
837 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
838 DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
839 gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
840 #endif
841 ret = gnutls_x509_privkey_init(&gtls_key);
842 if (ret != 0) {
843 gnutls_global_deinit();
844 return WERR_INTERNAL_ERROR;
848 * Unlike Heimdal's RSA_generate_key_ex(), this generates a
849 * 2048 bit key 100% of the time. The heimdal code had a ~1/8
850 * chance of doing so, chewing vast quantities of computation
851 * and entropy in the process.
854 ret = gnutls_x509_privkey_generate(gtls_key, GNUTLS_PK_RSA, bits, 0);
855 if (ret != 0) {
856 werr = WERR_INTERNAL_ERROR;
857 goto done;
860 /* No need to check error code, this SHOULD fail */
861 gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, NULL, &len);
863 if (len < 1) {
864 werr = WERR_INTERNAL_ERROR;
865 goto done;
868 p0 = talloc_size(ctx, len);
869 if (p0 == NULL) {
870 werr = WERR_NOT_ENOUGH_MEMORY;
871 goto done;
873 p = p0;
876 * Only this GnuTLS export function correctly exports the key,
877 * we can't use gnutls_rsa_params_export_raw() because while
878 * it appears to be fixed in more recent versions, in the
879 * Ubuntu 14.04 version 2.12.23 (at least) it incorrectly
880 * exports one of the key parameters (qInv). Additionally, we
881 * would have to work around subtle differences in big number
882 * representations.
884 * We need access to the RSA parameters directly (in the
885 * parameter RSA **rsa) as the caller has to manually encode
886 * them in a non-standard data structure.
888 ret = gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, p0, &len);
890 if (ret != 0) {
891 werr = WERR_INTERNAL_ERROR;
892 goto done;
896 * To dump the key we can use :
897 * rk_dumpdata("h5lkey", p0, len);
899 ret = hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
900 p0, len, HX509_KEY_FORMAT_DER, pk);
902 if (ret != 0) {
903 werr = WERR_INTERNAL_ERROR;
904 goto done;
907 *rsa = d2i_RSAPrivateKey(NULL, &p, len);
908 TALLOC_FREE(p0);
910 if (*rsa == NULL) {
911 hx509_private_key_free(pk);
912 werr = WERR_INTERNAL_ERROR;
913 goto done;
916 RSA_returned_bits = BN_num_bits((*rsa)->n);
917 DEBUG(6, ("GnuTLS returned an RSA private key with %d bits\n", RSA_returned_bits));
919 if (RSA_returned_bits != bits) {
920 DEBUG(0, ("GnuTLS unexpectedly returned an RSA private key with %d bits, needed %d\n", RSA_returned_bits, bits));
921 hx509_private_key_free(pk);
922 werr = WERR_INTERNAL_ERROR;
923 goto done;
926 werr = WERR_OK;
928 done:
929 if (p0 != NULL) {
930 memset(p0, 0, len);
931 TALLOC_FREE(p0);
934 gnutls_x509_privkey_deinit(gtls_key);
935 gnutls_global_deinit();
936 return werr;
939 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
940 time_t lifetime, hx509_private_key *private_key,
941 hx509_cert *cert, DATA_BLOB *guidblob)
943 SubjectPublicKeyInfo spki;
944 hx509_name subject = NULL;
945 hx509_ca_tbs tbs;
946 struct heim_bit_string uniqueid;
947 struct heim_integer serialnumber;
948 int ret, i;
950 uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
951 if (uniqueid.data == NULL) {
952 return WERR_NOT_ENOUGH_MEMORY;
954 /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
955 * so as 1 byte is 8 bits we need to provision 8 times more space as in the
956 * blob
958 uniqueid.length = 8 * guidblob->length;
960 serialnumber.data = talloc_array(ctx, uint8_t,
961 guidblob->length);
962 if (serialnumber.data == NULL) {
963 talloc_free(uniqueid.data);
964 return WERR_NOT_ENOUGH_MEMORY;
967 /* Native AD generates certificates with serialnumber in reversed notation */
968 for (i = 0; i < guidblob->length; i++) {
969 uint8_t *reversed = (uint8_t *)serialnumber.data;
970 uint8_t *uncrypt = guidblob->data;
971 reversed[i] = uncrypt[guidblob->length - 1 - i];
973 serialnumber.length = guidblob->length;
974 serialnumber.negative = 0;
976 memset(&spki, 0, sizeof(spki));
978 ret = hx509_request_get_name(*hctx, *req, &subject);
979 if (ret !=0) {
980 goto fail_subject;
982 ret = hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
983 if (ret !=0) {
984 goto fail_spki;
987 ret = hx509_ca_tbs_init(*hctx, &tbs);
988 if (ret !=0) {
989 goto fail_tbs;
992 ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
993 if (ret !=0) {
994 goto fail;
996 ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
997 if (ret !=0) {
998 goto fail;
1000 ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
1001 if (ret !=0) {
1002 goto fail;
1004 ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
1005 if (ret !=0) {
1006 goto fail;
1008 ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
1009 if (ret !=0) {
1010 goto fail;
1012 ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
1013 if (ret !=0) {
1014 goto fail;
1016 hx509_name_free(&subject);
1017 free_SubjectPublicKeyInfo(&spki);
1018 hx509_ca_tbs_free(&tbs);
1020 return WERR_OK;
1022 fail:
1023 hx509_ca_tbs_free(&tbs);
1024 fail_tbs:
1025 free_SubjectPublicKeyInfo(&spki);
1026 fail_spki:
1027 hx509_name_free(&subject);
1028 fail_subject:
1029 talloc_free(uniqueid.data);
1030 talloc_free(serialnumber.data);
1031 return WERR_INTERNAL_ERROR;
1034 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
1035 hx509_private_key *signer,RSA **rsa, const char *dn)
1037 int ret;
1038 SubjectPublicKeyInfo key;
1040 hx509_name name;
1041 WERROR werr;
1043 werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1044 if (!W_ERROR_IS_OK(werr)) {
1045 return werr;
1048 hx509_request_init(*hctx, req);
1049 ret = hx509_parse_name(*hctx, dn, &name);
1050 if (ret != 0) {
1051 RSA_free(*rsa);
1052 hx509_private_key_free(signer);
1053 hx509_request_free(req);
1054 hx509_name_free(&name);
1055 return WERR_INTERNAL_ERROR;
1058 ret = hx509_request_set_name(*hctx, *req, name);
1059 if (ret != 0) {
1060 RSA_free(*rsa);
1061 hx509_private_key_free(signer);
1062 hx509_request_free(req);
1063 hx509_name_free(&name);
1064 return WERR_INTERNAL_ERROR;
1066 hx509_name_free(&name);
1068 ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1069 if (ret != 0) {
1070 RSA_free(*rsa);
1071 hx509_private_key_free(signer);
1072 hx509_request_free(req);
1073 return WERR_INTERNAL_ERROR;
1075 ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1076 if (ret != 0) {
1077 RSA_free(*rsa);
1078 hx509_private_key_free(signer);
1079 free_SubjectPublicKeyInfo(&key);
1080 hx509_request_free(req);
1081 return WERR_INTERNAL_ERROR;
1084 free_SubjectPublicKeyInfo(&key);
1086 return WERR_OK;
1089 /* Return an error when we fail to generate a certificate */
1090 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1092 heim_octet_string data;
1093 WERROR werr;
1094 RSA *rsa;
1095 hx509_context hctx;
1096 hx509_private_key pk;
1097 hx509_request req;
1098 hx509_cert cert;
1099 DATA_BLOB blob;
1100 DATA_BLOB blobkeypair;
1101 DATA_BLOB *tmp;
1102 int ret;
1103 bool ok = true;
1104 struct GUID guid = GUID_random();
1105 NTSTATUS status;
1106 char *secret_name;
1107 struct bkrp_exported_RSA_key_pair keypair;
1108 enum ndr_err_code ndr_err;
1109 uint32_t nb_seconds_validity = 3600 * 24 * 365;
1111 DEBUG(6, ("Trying to generate a certificate\n"));
1112 hx509_context_init(&hctx);
1113 werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1114 if (!W_ERROR_IS_OK(werr)) {
1115 hx509_context_free(&hctx);
1116 return werr;
1119 status = GUID_to_ndr_blob(&guid, ctx, &blob);
1120 if (!NT_STATUS_IS_OK(status)) {
1121 hx509_context_free(&hctx);
1122 hx509_private_key_free(&pk);
1123 RSA_free(rsa);
1124 return WERR_INVALID_DATA;
1127 werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1128 if (!W_ERROR_IS_OK(werr)) {
1129 hx509_private_key_free(&pk);
1130 hx509_context_free(&hctx);
1131 return WERR_INVALID_DATA;
1134 ret = hx509_cert_binary(hctx, cert, &data);
1135 if (ret !=0) {
1136 hx509_cert_free(cert);
1137 hx509_private_key_free(&pk);
1138 hx509_context_free(&hctx);
1139 return WERR_INVALID_DATA;
1142 keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1143 keypair.cert.length = data.length;
1146 * Heimdal's bignum are big endian and the
1147 * structure expect it to be in little endian
1148 * so we reverse the buffer to make it work
1150 tmp = reverse_and_get_blob(ctx, rsa->e);
1151 if (tmp == NULL) {
1152 ok = false;
1153 } else {
1154 keypair.public_exponent = *tmp;
1155 SMB_ASSERT(tmp->length <= 4);
1157 * The value is now in little endian but if can happen that the length is
1158 * less than 4 bytes.
1159 * So if we have less than 4 bytes we pad with zeros so that it correctly
1160 * fit into the structure.
1162 if (tmp->length < 4) {
1164 * We need the expo to fit 4 bytes
1166 keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1167 memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1168 keypair.public_exponent.length = 4;
1172 tmp = reverse_and_get_blob(ctx,rsa->d);
1173 if (tmp == NULL) {
1174 ok = false;
1175 } else {
1176 keypair.private_exponent = *tmp;
1179 tmp = reverse_and_get_blob(ctx,rsa->n);
1180 if (tmp == NULL) {
1181 ok = false;
1182 } else {
1183 keypair.modulus = *tmp;
1186 tmp = reverse_and_get_blob(ctx,rsa->p);
1187 if (tmp == NULL) {
1188 ok = false;
1189 } else {
1190 keypair.prime1 = *tmp;
1193 tmp = reverse_and_get_blob(ctx,rsa->q);
1194 if (tmp == NULL) {
1195 ok = false;
1196 } else {
1197 keypair.prime2 = *tmp;
1200 tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1201 if (tmp == NULL) {
1202 ok = false;
1203 } else {
1204 keypair.exponent1 = *tmp;
1207 tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1208 if (tmp == NULL) {
1209 ok = false;
1210 } else {
1211 keypair.exponent2 = *tmp;
1214 tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1215 if (tmp == NULL) {
1216 ok = false;
1217 } else {
1218 keypair.coefficient = *tmp;
1221 /* One of the keypair allocation was wrong */
1222 if (ok == false) {
1223 der_free_octet_string(&data);
1224 hx509_cert_free(cert);
1225 hx509_private_key_free(&pk);
1226 hx509_context_free(&hctx);
1227 RSA_free(rsa);
1228 return WERR_INVALID_DATA;
1230 keypair.certificate_len = keypair.cert.length;
1231 ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1232 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1233 der_free_octet_string(&data);
1234 hx509_cert_free(cert);
1235 hx509_private_key_free(&pk);
1236 hx509_context_free(&hctx);
1237 RSA_free(rsa);
1238 return WERR_INVALID_DATA;
1241 secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1242 if (secret_name == NULL) {
1243 der_free_octet_string(&data);
1244 hx509_cert_free(cert);
1245 hx509_private_key_free(&pk);
1246 hx509_context_free(&hctx);
1247 RSA_free(rsa);
1248 return WERR_OUTOFMEMORY;
1251 status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1252 if (!NT_STATUS_IS_OK(status)) {
1253 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1255 talloc_free(secret_name);
1257 GUID_to_ndr_blob(&guid, ctx, &blob);
1258 status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1259 if (!NT_STATUS_IS_OK(status)) {
1260 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1263 der_free_octet_string(&data);
1264 hx509_cert_free(cert);
1265 hx509_private_key_free(&pk);
1266 hx509_context_free(&hctx);
1267 RSA_free(rsa);
1268 return WERR_OK;
1271 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1272 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1274 struct GUID guid;
1275 char *guid_string;
1276 DATA_BLOB lsa_secret;
1277 enum ndr_err_code ndr_err;
1278 NTSTATUS status;
1281 * here we basicaly need to return our certificate
1282 * search for lsa secret BCKUPKEY_PREFERRED first
1285 status = get_lsa_secret(mem_ctx,
1286 ldb_ctx,
1287 "BCKUPKEY_PREFERRED",
1288 &lsa_secret);
1289 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1290 /* Ok we can be in this case if there was no certs */
1291 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1292 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1293 lpcfg_realm(lp_ctx));
1295 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1296 if (!W_ERROR_IS_OK(werr)) {
1297 return WERR_INVALID_PARAMETER;
1299 status = get_lsa_secret(mem_ctx,
1300 ldb_ctx,
1301 "BCKUPKEY_PREFERRED",
1302 &lsa_secret);
1304 if (!NT_STATUS_IS_OK(status)) {
1305 /* Ok we really don't manage to get this certs ...*/
1306 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1307 return WERR_FILE_NOT_FOUND;
1309 } else if (!NT_STATUS_IS_OK(status)) {
1310 return WERR_INTERNAL_ERROR;
1313 if (lsa_secret.length == 0) {
1314 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1315 return WERR_INTERNAL_ERROR;
1316 } else {
1317 char *cert_secret_name;
1319 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1320 if (!NT_STATUS_IS_OK(status)) {
1321 return WERR_FILE_NOT_FOUND;
1324 guid_string = GUID_string(mem_ctx, &guid);
1325 if (guid_string == NULL) {
1326 /* We return file not found because the client
1327 * expect this error
1329 return WERR_FILE_NOT_FOUND;
1332 cert_secret_name = talloc_asprintf(mem_ctx,
1333 "BCKUPKEY_%s",
1334 guid_string);
1335 status = get_lsa_secret(mem_ctx,
1336 ldb_ctx,
1337 cert_secret_name,
1338 &lsa_secret);
1339 if (!NT_STATUS_IS_OK(status)) {
1340 return WERR_FILE_NOT_FOUND;
1343 if (lsa_secret.length != 0) {
1344 struct bkrp_exported_RSA_key_pair keypair;
1345 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1346 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1347 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1348 return WERR_FILE_NOT_FOUND;
1350 *(r->out.data_out_len) = keypair.cert.length;
1351 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1352 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1353 return WERR_OK;
1354 } else {
1355 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1356 return WERR_INTERNAL_ERROR;
1360 return WERR_NOT_SUPPORTED;
1363 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1365 struct GUID guid = GUID_random();
1366 enum ndr_err_code ndr_err;
1367 DATA_BLOB blob_wrap_key, guid_blob;
1368 struct bkrp_dc_serverwrap_key wrap_key;
1369 NTSTATUS status;
1370 char *secret_name;
1371 TALLOC_CTX *frame = talloc_stackframe();
1373 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1375 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1376 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1377 TALLOC_FREE(frame);
1378 return WERR_INVALID_DATA;
1381 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1382 if (secret_name == NULL) {
1383 TALLOC_FREE(frame);
1384 return WERR_NOT_ENOUGH_MEMORY;
1387 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1388 if (!NT_STATUS_IS_OK(status)) {
1389 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1390 TALLOC_FREE(frame);
1391 return WERR_INTERNAL_ERROR;
1394 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1395 if (!NT_STATUS_IS_OK(status)) {
1396 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1397 TALLOC_FREE(frame);
1400 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1401 if (!NT_STATUS_IS_OK(status)) {
1402 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1403 TALLOC_FREE(frame);
1404 return WERR_INTERNAL_ERROR;
1407 TALLOC_FREE(frame);
1409 return WERR_OK;
1413 * Find the specified decryption keys from the LSA secrets store as
1414 * G$BCKUPKEY_keyGuidString.
1417 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1418 struct bkrp_dc_serverwrap_key *server_key,
1419 struct GUID *guid)
1421 NTSTATUS status;
1422 DATA_BLOB lsa_secret;
1423 char *secret_name;
1424 char *guid_string;
1425 enum ndr_err_code ndr_err;
1427 guid_string = GUID_string(mem_ctx, guid);
1428 if (guid_string == NULL) {
1429 /* We return file not found because the client
1430 * expect this error
1432 return WERR_FILE_NOT_FOUND;
1435 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1436 if (secret_name == NULL) {
1437 return WERR_NOT_ENOUGH_MEMORY;
1440 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1441 if (!NT_STATUS_IS_OK(status)) {
1442 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1443 return WERR_INVALID_DATA;
1445 if (lsa_secret.length == 0) {
1446 /* RODC case, we do not have secrets locally */
1447 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1448 secret_name));
1449 return WERR_INTERNAL_ERROR;
1451 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1452 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1453 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1454 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1455 return WERR_INVALID_DATA;
1458 return WERR_OK;
1462 * Find the current, preferred ServerWrap Key by looking at
1463 * G$BCKUPKEY_P in the LSA secrets store.
1465 * Then find the current decryption keys from the LSA secrets store as
1466 * G$BCKUPKEY_keyGuidString.
1469 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1470 struct ldb_context *ldb_ctx,
1471 struct bkrp_dc_serverwrap_key *server_key,
1472 struct GUID *returned_guid)
1474 NTSTATUS status;
1475 DATA_BLOB guid_binary;
1477 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1478 if (!NT_STATUS_IS_OK(status)) {
1479 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1480 return WERR_FILE_NOT_FOUND;
1481 } else if (guid_binary.length == 0) {
1482 /* RODC case, we do not have secrets locally */
1483 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1484 return WERR_INTERNAL_ERROR;
1487 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1488 if (!NT_STATUS_IS_OK(status)) {
1489 return WERR_FILE_NOT_FOUND;
1492 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1493 server_key, returned_guid);
1496 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1497 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1499 WERROR werr;
1500 struct bkrp_server_side_wrapped decrypt_request;
1501 DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1502 DATA_BLOB blob;
1503 enum ndr_err_code ndr_err;
1504 struct bkrp_dc_serverwrap_key server_key;
1505 struct bkrp_rc4encryptedpayload rc4payload;
1506 struct dom_sid *caller_sid;
1507 uint8_t symkey[20]; /* SHA-1 hash len */
1508 uint8_t mackey[20]; /* SHA-1 hash len */
1509 uint8_t mac[20]; /* SHA-1 hash len */
1510 unsigned int hash_len;
1511 HMAC_CTX ctx;
1513 blob.data = r->in.data_in;
1514 blob.length = r->in.data_in_len;
1516 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1517 return WERR_INVALID_PARAMETER;
1520 ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1521 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1522 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1523 return WERR_INVALID_PARAMETER;
1526 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1527 return WERR_INVALID_PARAMETER;
1530 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1531 &decrypt_request.guid);
1532 if (!W_ERROR_IS_OK(werr)) {
1533 return werr;
1536 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1538 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1541 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1542 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1544 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1545 decrypt_request.r2, sizeof(decrypt_request.r2),
1546 symkey, &hash_len);
1548 dump_data_pw("symkey: \n", symkey, hash_len);
1550 /* rc4 decrypt sid and secret using sym key */
1551 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1553 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1554 decrypt_request.ciphertext_length);
1556 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1558 ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1559 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1560 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1561 return WERR_INVALID_PARAMETER;
1564 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1565 return WERR_INVALID_PARAMETER;
1568 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1571 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1572 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1574 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1575 rc4payload.r3, sizeof(rc4payload.r3),
1576 mackey, &hash_len);
1578 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1580 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1581 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1582 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1583 return WERR_INTERNAL_ERROR;
1586 HMAC_CTX_init(&ctx);
1587 HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1588 /* SID field */
1589 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1590 /* Secret field */
1591 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1592 HMAC_Final(&ctx, mac, &hash_len);
1593 HMAC_CTX_cleanup(&ctx);
1595 dump_data_pw("mac: \n", mac, sizeof(mac));
1596 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1598 if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1599 return WERR_INVALID_ACCESS;
1602 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1604 if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1605 return WERR_INVALID_ACCESS;
1608 *(r->out.data_out) = rc4payload.secret_data.data;
1609 *(r->out.data_out_len) = rc4payload.secret_data.length;
1611 return WERR_OK;
1615 * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1616 * determine what type of restore is wanted.
1618 * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1621 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1622 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1624 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1625 return WERR_INVALID_PARAMETER;
1628 if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1629 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1632 return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1636 * We have some data, such as saved website or IMAP passwords that the
1637 * client would like to put into the profile on-disk. This needs to
1638 * be encrypted. This version gives the server the data over the
1639 * network (protected only by the negotiated transport encryption),
1640 * and asks that it be encrypted and returned for long-term storage.
1642 * The data is NOT stored in the LSA, but a key to encrypt the data
1643 * will be stored. There is only one active encryption key per domain,
1644 * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1646 * The potentially multiple valid decryptiong keys (and the encryption
1647 * key) are in turn stored in the LSA secrets store as
1648 * G$BCKUPKEY_keyGuidString.
1652 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1653 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1655 DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1656 WERROR werr;
1657 struct dom_sid *caller_sid;
1658 uint8_t symkey[20]; /* SHA-1 hash len */
1659 uint8_t mackey[20]; /* SHA-1 hash len */
1660 unsigned int hash_len;
1661 struct bkrp_rc4encryptedpayload rc4payload;
1662 HMAC_CTX ctx;
1663 struct bkrp_dc_serverwrap_key server_key;
1664 enum ndr_err_code ndr_err;
1665 struct bkrp_server_side_wrapped server_side_wrapped;
1666 struct GUID guid;
1668 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1669 return WERR_INVALID_PARAMETER;
1672 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1673 ldb_ctx, &server_key,
1674 &guid);
1676 if (!W_ERROR_IS_OK(werr)) {
1677 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1678 /* Generate the server wrap key since one wasn't found */
1679 werr = generate_bkrp_server_wrap_key(mem_ctx,
1680 ldb_ctx);
1681 if (!W_ERROR_IS_OK(werr)) {
1682 return WERR_INVALID_PARAMETER;
1684 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1685 ldb_ctx,
1686 &server_key,
1687 &guid);
1689 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1690 /* Ok we really don't manage to get this secret ...*/
1691 return WERR_FILE_NOT_FOUND;
1693 } else {
1694 /* In theory we should NEVER reach this point as it
1695 should only appear in a rodc server */
1696 /* we do not have the real secret attribute */
1697 return WERR_INVALID_PARAMETER;
1701 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1703 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1706 * This is the key derivation step, so that the HMAC and RC4
1707 * operations over the user-supplied data are not able to
1708 * disclose the master key. By using random data, the symkey
1709 * and mackey values are unique for this operation, and
1710 * discovering these (by reversing the RC4 over the
1711 * attacker-controlled data) does not return something able to
1712 * be used to decyrpt the encrypted data of other users
1714 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1716 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1718 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1720 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1724 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1725 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1727 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1728 server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1729 symkey, &hash_len);
1731 dump_data_pw("symkey: \n", symkey, hash_len);
1734 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1735 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1737 HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1738 rc4payload.r3, sizeof(rc4payload.r3),
1739 mackey, &hash_len);
1741 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1743 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1744 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1745 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1746 return WERR_INTERNAL_ERROR;
1749 rc4payload.secret_data.data = r->in.data_in;
1750 rc4payload.secret_data.length = r->in.data_in_len;
1752 HMAC_CTX_init(&ctx);
1753 HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1754 /* SID field */
1755 HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1756 /* Secret field */
1757 HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1758 HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1759 HMAC_CTX_cleanup(&ctx);
1761 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1763 rc4payload.sid = *caller_sid;
1765 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1766 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1767 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1768 return WERR_INTERNAL_ERROR;
1771 /* rc4 encrypt sid and secret using sym key */
1772 symkey_blob = data_blob_const(symkey, sizeof(symkey));
1773 arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1775 /* create server wrap structure */
1777 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1778 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1779 server_side_wrapped.guid = guid;
1780 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1782 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1783 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1784 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1785 return WERR_INTERNAL_ERROR;
1788 *(r->out.data_out) = server_wrapped_blob.data;
1789 *(r->out.data_out_len) = server_wrapped_blob.length;
1791 return WERR_OK;
1794 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1795 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1797 WERROR error = WERR_INVALID_PARAMETER;
1798 struct ldb_context *ldb_ctx;
1799 bool is_rodc;
1800 const char *addr = "unknown";
1801 /* At which level we start to add more debug of what is done in the protocol */
1802 const int debuglevel = 4;
1804 if (DEBUGLVL(debuglevel)) {
1805 const struct tsocket_address *remote_address;
1806 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1807 if (tsocket_address_is_inet(remote_address, "ip")) {
1808 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1809 W_ERROR_HAVE_NO_MEMORY(addr);
1813 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1814 return WERR_NOT_SUPPORTED;
1817 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1818 dce_call->conn->dce_ctx->lp_ctx,
1819 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1821 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1822 talloc_unlink(mem_ctx, ldb_ctx);
1823 return WERR_INVALID_PARAMETER;
1826 if (!is_rodc) {
1827 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1828 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1829 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1830 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1833 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1834 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1835 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1836 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1839 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1840 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1841 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1842 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1845 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1846 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1847 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1848 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1851 /*else: I am a RODC so I don't handle backup key protocol */
1853 talloc_unlink(mem_ctx, ldb_ctx);
1854 return error;
1857 /* include the generated boilerplate */
1858 #include "librpc/gen_ndr/ndr_backupkey_s.c"