ctdb-failover: Split statd_callout add-client/del-client
[Samba.git] / source4 / rpc_server / backupkey / dcesrv_backupkey.c
blob77b8b8c4bf4bd41cd1321d80e6fe73ccabd79815
1 /*
2 Unix SMB/CIFS implementation.
4 endpoint server for the backupkey interface
6 Copyright (C) Matthieu Patou <mat@samba.org> 2010
7 Copyright (C) Andreas Schneider <asn@samba.org> 2015
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
24 #include "rpc_server/dcerpc_server.h"
25 #include "rpc_server/common/common.h"
26 #include "librpc/gen_ndr/ndr_backupkey.h"
27 #include "dsdb/common/util.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "lib/ldb/include/ldb_errors.h"
30 #include "../lib/util/util_ldb.h"
31 #include "param/param.h"
32 #include "auth/session.h"
33 #include "system/network.h"
35 #include "../lib/tsocket/tsocket.h"
36 #include "../libcli/security/security.h"
37 #include "librpc/gen_ndr/ndr_security.h"
38 #include "libds/common/roles.h"
40 #include <gnutls/gnutls.h>
41 #include <gnutls/x509.h>
42 #include <gnutls/crypto.h>
43 #include <gnutls/abstract.h>
45 #include "lib/crypto/gnutls_helpers.h"
47 #undef strncasecmp
49 #define DCESRV_INTERFACE_BACKUPKEY_BIND(context, iface) \
50 dcesrv_interface_backupkey_bind(context, iface)
51 static NTSTATUS dcesrv_interface_backupkey_bind(struct dcesrv_connection_context *context,
52 const struct dcesrv_interface *iface)
54 return dcesrv_interface_bind_require_privacy(context, iface);
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 TALLOC_CTX *frame = talloc_stackframe();
63 struct ldb_message *msg;
64 struct ldb_result *res;
65 struct ldb_dn *system_dn = NULL;
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 msg = ldb_msg_new(frame);
76 if (msg == NULL) {
77 talloc_free(frame);
78 return NT_STATUS_NO_MEMORY;
82 * This function is a lot like dcesrv_lsa_CreateSecret
83 * in the rpc_server/lsa directory
84 * The reason why we duplicate the effort here is that:
85 * * we want to keep the former function static
86 * * we want to avoid the burden of doing LSA calls
87 * when we can just manipulate the secrets directly
88 * * taillor the function to the particular needs of backup protocol
91 system_dn = samdb_system_container_dn(ldb, frame);
92 if (system_dn == NULL) {
93 talloc_free(frame);
94 return NT_STATUS_NO_MEMORY;
97 name2 = talloc_asprintf(msg, "%s Secret", name);
98 if (name2 == NULL) {
99 talloc_free(frame);
100 return NT_STATUS_NO_MEMORY;
103 ret = ldb_search(ldb, frame, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
104 "(&(cn=%s)(objectclass=secret))",
105 ldb_binary_encode_string(frame, name2));
107 if (ret != LDB_SUCCESS || res->count != 0 ) {
108 DEBUG(2, ("Secret %s already exists !\n", name2));
109 talloc_free(frame);
110 return NT_STATUS_OBJECT_NAME_COLLISION;
114 * We don't care about previous value as we are
115 * here only if the key didn't exists before
118 msg->dn = ldb_dn_copy(frame, system_dn);
119 if (msg->dn == NULL) {
120 talloc_free(frame);
121 return NT_STATUS_NO_MEMORY;
123 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
124 talloc_free(frame);
125 return NT_STATUS_NO_MEMORY;
128 ret = ldb_msg_add_string(msg, "cn", name2);
129 if (ret != LDB_SUCCESS) {
130 talloc_free(frame);
131 return NT_STATUS_NO_MEMORY;
133 ret = ldb_msg_add_string(msg, "objectClass", "secret");
134 if (ret != LDB_SUCCESS) {
135 talloc_free(frame);
136 return NT_STATUS_NO_MEMORY;
138 ret = samdb_msg_add_uint64(ldb, frame, msg, "priorSetTime", nt_now);
139 if (ret != LDB_SUCCESS) {
140 talloc_free(frame);
141 return NT_STATUS_NO_MEMORY;
143 val.data = lsa_secret->data;
144 val.length = lsa_secret->length;
145 ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
146 if (ret != LDB_SUCCESS) {
147 talloc_free(frame);
148 return NT_STATUS_NO_MEMORY;
150 ret = samdb_msg_add_uint64(ldb, frame, msg, "lastSetTime", nt_now);
151 if (ret != LDB_SUCCESS) {
152 talloc_free(frame);
153 return NT_STATUS_NO_MEMORY;
157 * create the secret with DSDB_MODIFY_RELAX
158 * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
159 * the create of LSA secret object
161 ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
162 if (ret != LDB_SUCCESS) {
163 DEBUG(2,("Failed to create secret record %s: %s\n",
164 ldb_dn_get_linearized(msg->dn),
165 ldb_errstring(ldb)));
166 talloc_free(frame);
167 return NT_STATUS_ACCESS_DENIED;
170 talloc_free(frame);
171 return NT_STATUS_OK;
174 /* This function is pretty much like dcesrv_lsa_QuerySecret */
175 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
176 struct ldb_context *ldb,
177 const char *name,
178 DATA_BLOB *lsa_secret)
180 TALLOC_CTX *tmp_mem;
181 struct ldb_result *res;
182 struct ldb_dn *system_dn = NULL;
183 const struct ldb_val *val;
184 uint8_t *data;
185 const char *attrs[] = {
186 "currentValue",
187 NULL
189 int ret;
191 lsa_secret->data = NULL;
192 lsa_secret->length = 0;
194 tmp_mem = talloc_new(mem_ctx);
195 if (tmp_mem == NULL) {
196 return NT_STATUS_NO_MEMORY;
199 system_dn = samdb_system_container_dn(ldb, tmp_mem);
200 if (system_dn == NULL) {
201 talloc_free(tmp_mem);
202 return NT_STATUS_NO_MEMORY;
205 ret = ldb_search(ldb, tmp_mem, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
206 "(&(cn=%s Secret)(objectclass=secret))",
207 ldb_binary_encode_string(tmp_mem, name));
209 if (ret != LDB_SUCCESS) {
210 talloc_free(tmp_mem);
211 return NT_STATUS_INTERNAL_DB_CORRUPTION;
213 if (res->count == 0) {
214 talloc_free(tmp_mem);
215 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
217 if (res->count > 1) {
218 DEBUG(2, ("Secret %s collision\n", name));
219 talloc_free(tmp_mem);
220 return NT_STATUS_INTERNAL_DB_CORRUPTION;
223 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
224 if (val == NULL) {
226 * The secret object is here but we don't have the secret value
227 * The most common case is a RODC
229 *lsa_secret = data_blob_null;
230 talloc_free(tmp_mem);
231 return NT_STATUS_OK;
234 data = val->data;
235 lsa_secret->data = talloc_move(mem_ctx, &data);
236 lsa_secret->length = val->length;
238 talloc_free(tmp_mem);
239 return NT_STATUS_OK;
242 static int reverse_and_get_bignum(TALLOC_CTX *mem_ctx,
243 DATA_BLOB blob,
244 gnutls_datum_t *datum)
246 uint32_t i;
248 datum->data = talloc_array(mem_ctx, uint8_t, blob.length);
249 if (datum->data == NULL) {
250 return -1;
253 for(i = 0; i < blob.length; i++) {
254 datum->data[i] = blob.data[blob.length - i - 1];
256 datum->size = blob.length;
258 return 0;
261 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
262 struct bkrp_exported_RSA_key_pair *keypair,
263 gnutls_privkey_t *pk)
265 gnutls_x509_privkey_t x509_privkey = NULL;
266 gnutls_privkey_t privkey = NULL;
267 gnutls_datum_t m, e, d, p, q, u, e1, e2;
268 int rc;
270 rc = reverse_and_get_bignum(ctx, keypair->modulus, &m);
271 if (rc != 0) {
272 return NT_STATUS_INVALID_PARAMETER;
274 rc = reverse_and_get_bignum(ctx, keypair->public_exponent, &e);
275 if (rc != 0) {
276 return NT_STATUS_INVALID_PARAMETER;
278 rc = reverse_and_get_bignum(ctx, keypair->private_exponent, &d);
279 if (rc != 0) {
280 return NT_STATUS_INVALID_PARAMETER;
283 rc = reverse_and_get_bignum(ctx, keypair->prime1, &p);
284 if (rc != 0) {
285 return NT_STATUS_INVALID_PARAMETER;
287 rc = reverse_and_get_bignum(ctx, keypair->prime2, &q);
288 if (rc != 0) {
289 return NT_STATUS_INVALID_PARAMETER;
292 rc = reverse_and_get_bignum(ctx, keypair->coefficient, &u);
293 if (rc != 0) {
294 return NT_STATUS_INVALID_PARAMETER;
297 rc = reverse_and_get_bignum(ctx, keypair->exponent1, &e1);
298 if (rc != 0) {
299 return NT_STATUS_INVALID_PARAMETER;
301 rc = reverse_and_get_bignum(ctx, keypair->exponent2, &e2);
302 if (rc != 0) {
303 return NT_STATUS_INVALID_PARAMETER;
306 rc = gnutls_x509_privkey_init(&x509_privkey);
307 if (rc != GNUTLS_E_SUCCESS) {
308 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
309 gnutls_strerror(rc));
310 return NT_STATUS_INTERNAL_ERROR;
313 rc = gnutls_x509_privkey_import_rsa_raw2(x509_privkey,
320 &e1,
321 &e2);
322 if (rc != GNUTLS_E_SUCCESS) {
323 DBG_ERR("gnutls_x509_privkey_import_rsa_raw2 failed - %s\n",
324 gnutls_strerror(rc));
325 return NT_STATUS_INTERNAL_ERROR;
328 rc = gnutls_privkey_init(&privkey);
329 if (rc != GNUTLS_E_SUCCESS) {
330 DBG_ERR("gnutls_privkey_init failed - %s\n",
331 gnutls_strerror(rc));
332 gnutls_x509_privkey_deinit(x509_privkey);
333 return NT_STATUS_INTERNAL_ERROR;
336 rc = gnutls_privkey_import_x509(privkey,
337 x509_privkey,
338 GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
339 if (rc != GNUTLS_E_SUCCESS) {
340 DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
341 gnutls_strerror(rc));
342 gnutls_x509_privkey_deinit(x509_privkey);
343 return NT_STATUS_INTERNAL_ERROR;
346 *pk = privkey;
348 return NT_STATUS_OK;
351 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
352 uint32_t version,
353 uint8_t *key_and_iv,
354 uint8_t *access_check,
355 uint32_t access_check_len,
356 struct auth_session_info *session_info)
358 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
359 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
360 gnutls_cipher_hd_t cipher_handle = { 0 };
361 gnutls_cipher_algorithm_t cipher_algo;
362 DATA_BLOB blob_us;
363 enum ndr_err_code ndr_err;
364 gnutls_datum_t key;
365 gnutls_datum_t iv;
367 struct dom_sid *access_sid = NULL;
368 struct dom_sid *caller_sid = NULL;
369 int rc;
371 switch (version) {
372 case 2:
373 cipher_algo = GNUTLS_CIPHER_3DES_CBC;
374 break;
375 case 3:
376 cipher_algo = GNUTLS_CIPHER_AES_256_CBC;
377 break;
378 default:
379 return WERR_INVALID_DATA;
382 key.data = key_and_iv;
383 key.size = gnutls_cipher_get_key_size(cipher_algo);
385 iv.data = key_and_iv + key.size;
386 iv.size = gnutls_cipher_get_iv_size(cipher_algo);
388 /* Allocate data structure for the plaintext */
389 blob_us = data_blob_talloc_zero(sub_ctx, access_check_len);
390 if (blob_us.data == NULL) {
391 return WERR_INVALID_DATA;
394 rc = gnutls_cipher_init(&cipher_handle,
395 cipher_algo,
396 &key,
397 &iv);
398 if (rc < 0) {
399 DBG_ERR("gnutls_cipher_init failed: %s\n",
400 gnutls_strerror(rc));
401 return WERR_INVALID_DATA;
404 rc = gnutls_cipher_decrypt2(cipher_handle,
405 access_check,
406 access_check_len,
407 blob_us.data,
408 blob_us.length);
409 gnutls_cipher_deinit(cipher_handle);
410 if (rc < 0) {
411 DBG_ERR("gnutls_cipher_decrypt2 failed: %s\n",
412 gnutls_strerror(rc));
413 return WERR_INVALID_DATA;
416 switch (version) {
417 case 2:
419 uint32_t hash_size = 20;
420 uint8_t hash[hash_size];
421 gnutls_hash_hd_t dig_ctx;
423 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
424 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
425 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
426 /* Unable to unmarshall */
427 return WERR_INVALID_DATA;
429 if (uncrypted_accesscheckv2.magic != 0x1) {
430 /* wrong magic */
431 return WERR_INVALID_DATA;
434 rc = gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA1);
435 if (rc != GNUTLS_E_SUCCESS) {
436 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
438 rc = gnutls_hash(dig_ctx,
439 blob_us.data,
440 blob_us.length - hash_size);
441 gnutls_hash_deinit(dig_ctx, hash);
442 if (rc != GNUTLS_E_SUCCESS) {
443 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
447 * We free it after the sha1 calculation because blob.data
448 * points to the same area
451 if (!mem_equal_const_time(hash, uncrypted_accesscheckv2.hash, hash_size)) {
452 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
453 return WERR_INVALID_DATA;
455 access_sid = &(uncrypted_accesscheckv2.sid);
456 break;
458 case 3:
460 uint32_t hash_size = 64;
461 uint8_t hash[hash_size];
462 gnutls_hash_hd_t dig_ctx;
464 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
465 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
466 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
467 /* Unable to unmarshall */
468 return WERR_INVALID_DATA;
470 if (uncrypted_accesscheckv3.magic != 0x1) {
471 /* wrong magic */
472 return WERR_INVALID_DATA;
475 rc = gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA512);
476 if (rc != GNUTLS_E_SUCCESS) {
477 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
479 rc = gnutls_hash(dig_ctx,
480 blob_us.data,
481 blob_us.length - hash_size);
482 gnutls_hash_deinit(dig_ctx, hash);
483 if (rc != GNUTLS_E_SUCCESS) {
484 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
488 * We free it after the sha1 calculation because blob.data
489 * points to the same area
492 if (!mem_equal_const_time(hash, uncrypted_accesscheckv3.hash, hash_size)) {
493 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
494 return WERR_INVALID_DATA;
496 access_sid = &(uncrypted_accesscheckv3.sid);
497 break;
499 default:
500 /* Never reached normally as we filtered at the switch / case level */
501 return WERR_INVALID_DATA;
504 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
506 if (!dom_sid_equal(caller_sid, access_sid)) {
507 return WERR_INVALID_ACCESS;
509 return WERR_OK;
513 * We have some data, such as saved website or IMAP passwords that the
514 * client has in profile on-disk. This needs to be decrypted. This
515 * version gives the server the data over the network (protected by
516 * the X.509 certificate and public key encryption, and asks that it
517 * be decrypted returned for short-term use, protected only by the
518 * negotiated transport encryption.
520 * The data is NOT stored in the LSA, but a X.509 certificate, public
521 * and private keys used to encrypt the data will be stored. There is
522 * only one active encryption key pair and certificate per domain, it
523 * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
525 * The potentially multiple valid decrypting key pairs are in turn
526 * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
529 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
530 TALLOC_CTX *mem_ctx,
531 struct bkrp_BackupKey *r,
532 struct ldb_context *ldb_ctx)
534 struct auth_session_info *session_info =
535 dcesrv_call_session_info(dce_call);
536 struct bkrp_client_side_wrapped uncrypt_request;
537 DATA_BLOB blob;
538 enum ndr_err_code ndr_err;
539 char *guid_string;
540 char *cert_secret_name;
541 DATA_BLOB lsa_secret;
542 DATA_BLOB *uncrypted_data = NULL;
543 NTSTATUS status;
544 uint32_t requested_version;
546 blob.data = r->in.data_in;
547 blob.length = r->in.data_in_len;
549 if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
550 return WERR_INVALID_PARAMETER;
554 * We check for the version here, so we can actually print the
555 * message as we are unlikely to parse it with NDR.
557 requested_version = IVAL(r->in.data_in, 0);
558 if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
559 && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
560 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
561 return WERR_INVALID_PARAMETER;
564 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
565 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
566 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
567 return WERR_INVALID_PARAMETER;
570 if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
571 && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
572 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
573 return WERR_INVALID_PARAMETER;
576 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
577 if (guid_string == NULL) {
578 return WERR_NOT_ENOUGH_MEMORY;
581 cert_secret_name = talloc_asprintf(mem_ctx,
582 "BCKUPKEY_%s",
583 guid_string);
584 if (cert_secret_name == NULL) {
585 return WERR_NOT_ENOUGH_MEMORY;
588 status = get_lsa_secret(mem_ctx,
589 ldb_ctx,
590 cert_secret_name,
591 &lsa_secret);
592 if (!NT_STATUS_IS_OK(status)) {
593 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
594 return WERR_INVALID_DATA;
595 } else if (lsa_secret.length == 0) {
596 /* we do not have the real secret attribute, like if we are an RODC */
597 return WERR_INVALID_PARAMETER;
598 } else {
599 struct bkrp_exported_RSA_key_pair keypair;
600 gnutls_privkey_t privkey = NULL;
601 gnutls_datum_t reversed_secret;
602 gnutls_datum_t uncrypted_secret;
603 uint32_t i;
604 DATA_BLOB blob_us;
605 WERROR werr;
606 int rc;
608 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
609 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
610 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
611 return WERR_FILE_NOT_FOUND;
614 status = get_pk_from_raw_keypair_params(mem_ctx,
615 &keypair,
616 &privkey);
617 if (!NT_STATUS_IS_OK(status)) {
618 return WERR_INTERNAL_ERROR;
621 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
622 uncrypt_request.encrypted_secret_len);
623 if (reversed_secret.data == NULL) {
624 gnutls_privkey_deinit(privkey);
625 return WERR_NOT_ENOUGH_MEMORY;
628 /* The secret has to be reversed ... */
629 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
630 uint8_t *reversed = (uint8_t *)reversed_secret.data;
631 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
632 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
634 reversed_secret.size = uncrypt_request.encrypted_secret_len;
637 * Let's try to decrypt the secret now that
638 * we have the private key ...
640 rc = gnutls_privkey_decrypt_data(privkey,
642 &reversed_secret,
643 &uncrypted_secret);
644 gnutls_privkey_deinit(privkey);
645 if (rc != GNUTLS_E_SUCCESS) {
646 /* We are not able to decrypt the secret, looks like something is wrong */
647 return WERR_INVALID_PARAMETER;
649 blob_us.data = uncrypted_secret.data;
650 blob_us.length = uncrypted_secret.size;
652 if (uncrypt_request.version == 2) {
653 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
655 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
656 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
657 gnutls_free(uncrypted_secret.data);
658 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
659 /* Unable to unmarshall */
660 return WERR_INVALID_DATA;
662 if (uncrypted_secretv2.magic != 0x20) {
663 /* wrong magic */
664 return WERR_INVALID_DATA;
667 werr = get_and_verify_access_check(mem_ctx, 2,
668 uncrypted_secretv2.payload_key,
669 uncrypt_request.access_check,
670 uncrypt_request.access_check_len,
671 session_info);
672 if (!W_ERROR_IS_OK(werr)) {
673 return werr;
675 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
676 if (uncrypted_data == NULL) {
677 return WERR_INVALID_DATA;
680 uncrypted_data->data = uncrypted_secretv2.secret;
681 uncrypted_data->length = uncrypted_secretv2.secret_len;
683 if (uncrypt_request.version == 3) {
684 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
686 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
687 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
688 gnutls_free(uncrypted_secret.data);
689 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
690 /* Unable to unmarshall */
691 return WERR_INVALID_DATA;
694 if (uncrypted_secretv3.magic1 != 0x30 ||
695 uncrypted_secretv3.magic2 != 0x6610 ||
696 uncrypted_secretv3.magic3 != 0x800e) {
697 /* wrong magic */
698 return WERR_INVALID_DATA;
702 * Confirm that the caller is permitted to
703 * read this particular data. Because one key
704 * pair is used per domain, the caller could
705 * have stolen the profile data on-disk and
706 * would otherwise be able to read the
707 * passwords.
710 werr = get_and_verify_access_check(mem_ctx, 3,
711 uncrypted_secretv3.payload_key,
712 uncrypt_request.access_check,
713 uncrypt_request.access_check_len,
714 session_info);
715 if (!W_ERROR_IS_OK(werr)) {
716 return werr;
719 uncrypted_data = talloc(mem_ctx, DATA_BLOB);
720 if (uncrypted_data == NULL) {
721 return WERR_INVALID_DATA;
724 uncrypted_data->data = uncrypted_secretv3.secret;
725 uncrypted_data->length = uncrypted_secretv3.secret_len;
729 * Yeah if we are here all looks pretty good:
730 * - hash is ok
731 * - user sid is the same as the one in access check
732 * - we were able to decrypt the whole stuff
736 if (uncrypted_data->data == NULL) {
737 return WERR_INVALID_DATA;
740 /* There is a magic value at the beginning of the data
741 * we can use an ad hoc structure but as the
742 * parent structure is just an array of bytes it is a lot of
743 * work just prepending 4 bytes
745 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
746 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
747 memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
748 *(r->out.data_out_len) = uncrypted_data->length + 4;
750 return WERR_OK;
753 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx,
754 gnutls_datum_t *datum)
756 DATA_BLOB *blob;
757 size_t i;
759 blob = talloc(mem_ctx, DATA_BLOB);
760 if (blob == NULL) {
761 return NULL;
764 blob->length = datum->size;
765 if (datum->data[0] == '\0') {
766 /* The datum has a leading byte zero, skip it */
767 blob->length = datum->size - 1;
769 blob->data = talloc_zero_array(mem_ctx, uint8_t, blob->length);
770 if (blob->data == NULL) {
771 talloc_free(blob);
772 return NULL;
775 for (i = 0; i < blob->length; i++) {
776 blob->data[i] = datum->data[datum->size - i - 1];
779 return blob;
782 static WERROR create_privkey_rsa(gnutls_privkey_t *pk)
784 int bits = 2048;
785 gnutls_x509_privkey_t x509_privkey = NULL;
786 gnutls_privkey_t privkey = NULL;
787 int rc;
789 rc = gnutls_x509_privkey_init(&x509_privkey);
790 if (rc != GNUTLS_E_SUCCESS) {
791 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
792 gnutls_strerror(rc));
793 return WERR_INTERNAL_ERROR;
796 rc = gnutls_x509_privkey_generate(x509_privkey,
797 GNUTLS_PK_RSA,
798 bits,
800 if (rc != GNUTLS_E_SUCCESS) {
801 DBG_ERR("gnutls_x509_privkey_generate failed - %s\n",
802 gnutls_strerror(rc));
803 gnutls_x509_privkey_deinit(x509_privkey);
804 return WERR_INTERNAL_ERROR;
807 rc = gnutls_privkey_init(&privkey);
808 if (rc != GNUTLS_E_SUCCESS) {
809 DBG_ERR("gnutls_privkey_init failed - %s\n",
810 gnutls_strerror(rc));
811 gnutls_x509_privkey_deinit(x509_privkey);
812 return WERR_INTERNAL_ERROR;
815 rc = gnutls_privkey_import_x509(privkey,
816 x509_privkey,
817 GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
818 if (rc != GNUTLS_E_SUCCESS) {
819 DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
820 gnutls_strerror(rc));
821 gnutls_x509_privkey_deinit(x509_privkey);
822 return WERR_INTERNAL_ERROR;
825 *pk = privkey;
827 return WERR_OK;
830 static WERROR self_sign_cert(TALLOC_CTX *mem_ctx,
831 time_t lifetime,
832 const char *dn,
833 gnutls_privkey_t issuer_privkey,
834 gnutls_x509_crt_t *certificate,
835 DATA_BLOB *guidblob)
837 gnutls_datum_t unique_id;
838 gnutls_datum_t serial_number;
839 gnutls_x509_crt_t issuer_cert;
840 gnutls_x509_privkey_t x509_issuer_privkey;
841 time_t activation = time(NULL);
842 time_t expiry = activation + lifetime;
843 const char *error_string;
844 uint8_t *reversed;
845 size_t i;
846 int rc;
848 unique_id.size = guidblob->length;
849 unique_id.data = talloc_memdup(mem_ctx,
850 guidblob->data,
851 guidblob->length);
852 if (unique_id.data == NULL) {
853 return WERR_NOT_ENOUGH_MEMORY;
856 reversed = talloc_array(mem_ctx, uint8_t, guidblob->length);
857 if (reversed == NULL) {
858 talloc_free(unique_id.data);
859 return WERR_NOT_ENOUGH_MEMORY;
862 /* Native AD generates certificates with serialnumber in reversed notation */
863 for (i = 0; i < guidblob->length; i++) {
864 uint8_t *uncrypt = guidblob->data;
865 reversed[i] = uncrypt[guidblob->length - i - 1];
867 serial_number.size = guidblob->length;
868 serial_number.data = reversed;
870 /* Create certificate to sign */
871 rc = gnutls_x509_crt_init(&issuer_cert);
872 if (rc != GNUTLS_E_SUCCESS) {
873 DBG_ERR("gnutls_x509_crt_init failed - %s\n",
874 gnutls_strerror(rc));
875 return WERR_NOT_ENOUGH_MEMORY;
878 rc = gnutls_x509_crt_set_dn(issuer_cert, dn, &error_string);
879 if (rc != GNUTLS_E_SUCCESS) {
880 DBG_ERR("gnutls_x509_crt_set_dn failed - %s (%s)\n",
881 gnutls_strerror(rc),
882 error_string);
883 gnutls_x509_crt_deinit(issuer_cert);
884 return WERR_INVALID_PARAMETER;
887 rc = gnutls_x509_crt_set_issuer_dn(issuer_cert, dn, &error_string);
888 if (rc != GNUTLS_E_SUCCESS) {
889 DBG_ERR("gnutls_x509_crt_set_issuer_dn failed - %s (%s)\n",
890 gnutls_strerror(rc),
891 error_string);
892 gnutls_x509_crt_deinit(issuer_cert);
893 return WERR_INVALID_PARAMETER;
896 /* Get x509 privkey for subjectPublicKeyInfo */
897 rc = gnutls_x509_privkey_init(&x509_issuer_privkey);
898 if (rc != GNUTLS_E_SUCCESS) {
899 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
900 gnutls_strerror(rc));
901 gnutls_x509_crt_deinit(issuer_cert);
902 return WERR_INVALID_PARAMETER;
905 rc = gnutls_privkey_export_x509(issuer_privkey,
906 &x509_issuer_privkey);
907 if (rc != GNUTLS_E_SUCCESS) {
908 DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
909 gnutls_strerror(rc));
910 gnutls_x509_privkey_deinit(x509_issuer_privkey);
911 gnutls_x509_crt_deinit(issuer_cert);
912 return WERR_INVALID_PARAMETER;
915 /* Set subjectPublicKeyInfo */
916 rc = gnutls_x509_crt_set_key(issuer_cert, x509_issuer_privkey);
917 gnutls_x509_privkey_deinit(x509_issuer_privkey);
918 if (rc != GNUTLS_E_SUCCESS) {
919 DBG_ERR("gnutls_x509_crt_set_pubkey failed - %s\n",
920 gnutls_strerror(rc));
921 gnutls_x509_crt_deinit(issuer_cert);
922 return WERR_INVALID_PARAMETER;
925 rc = gnutls_x509_crt_set_activation_time(issuer_cert, activation);
926 if (rc != GNUTLS_E_SUCCESS) {
927 DBG_ERR("gnutls_x509_crt_set_activation_time failed - %s\n",
928 gnutls_strerror(rc));
929 gnutls_x509_crt_deinit(issuer_cert);
930 return WERR_INVALID_PARAMETER;
933 rc = gnutls_x509_crt_set_expiration_time(issuer_cert, expiry);
934 if (rc != GNUTLS_E_SUCCESS) {
935 DBG_ERR("gnutls_x509_crt_set_expiration_time failed - %s\n",
936 gnutls_strerror(rc));
937 gnutls_x509_crt_deinit(issuer_cert);
938 return WERR_INVALID_PARAMETER;
941 rc = gnutls_x509_crt_set_version(issuer_cert, 3);
942 if (rc != GNUTLS_E_SUCCESS) {
943 DBG_ERR("gnutls_x509_crt_set_version failed - %s\n",
944 gnutls_strerror(rc));
945 gnutls_x509_crt_deinit(issuer_cert);
946 return WERR_INVALID_PARAMETER;
949 rc = gnutls_x509_crt_set_subject_unique_id(issuer_cert,
950 unique_id.data,
951 unique_id.size);
952 if (rc != GNUTLS_E_SUCCESS) {
953 DBG_ERR("gnutls_x509_crt_set_subject_key_id failed - %s\n",
954 gnutls_strerror(rc));
955 gnutls_x509_crt_deinit(issuer_cert);
956 return WERR_INVALID_PARAMETER;
959 rc = gnutls_x509_crt_set_issuer_unique_id(issuer_cert,
960 unique_id.data,
961 unique_id.size);
962 if (rc != GNUTLS_E_SUCCESS) {
963 DBG_ERR("gnutls_x509_crt_set_issuer_unique_id failed - %s\n",
964 gnutls_strerror(rc));
965 gnutls_x509_crt_deinit(issuer_cert);
966 return WERR_INVALID_PARAMETER;
969 rc = gnutls_x509_crt_set_serial(issuer_cert,
970 serial_number.data,
971 serial_number.size);
972 if (rc != GNUTLS_E_SUCCESS) {
973 DBG_ERR("gnutls_x509_crt_set_serial failed - %s\n",
974 gnutls_strerror(rc));
975 gnutls_x509_crt_deinit(issuer_cert);
976 return WERR_INVALID_PARAMETER;
979 rc = gnutls_x509_crt_privkey_sign(issuer_cert,
980 issuer_cert,
981 issuer_privkey,
982 GNUTLS_DIG_SHA1,
984 if (rc != GNUTLS_E_SUCCESS) {
985 DBG_ERR("gnutls_x509_crt_privkey_sign failed - %s\n",
986 gnutls_strerror(rc));
987 return WERR_INVALID_PARAMETER;
990 *certificate = issuer_cert;
992 return WERR_OK;
995 /* Return an error when we fail to generate a certificate */
996 static WERROR generate_bkrp_cert(TALLOC_CTX *mem_ctx,
997 struct dcesrv_call_state *dce_call,
998 struct ldb_context *ldb_ctx,
999 const char *dn)
1001 WERROR werr;
1002 gnutls_privkey_t issuer_privkey = NULL;
1003 gnutls_x509_crt_t cert = NULL;
1004 gnutls_datum_t cert_blob;
1005 gnutls_datum_t m, e, d, p, q, u, e1, e2;
1006 DATA_BLOB blob;
1007 DATA_BLOB blobkeypair;
1008 DATA_BLOB *tmp;
1009 bool ok = true;
1010 struct GUID guid = GUID_random();
1011 NTSTATUS status;
1012 char *secret_name;
1013 struct bkrp_exported_RSA_key_pair keypair;
1014 enum ndr_err_code ndr_err;
1015 time_t nb_seconds_validity = 3600 * 24 * 365;
1016 int rc;
1018 DEBUG(6, ("Trying to generate a certificate\n"));
1019 werr = create_privkey_rsa(&issuer_privkey);
1020 if (!W_ERROR_IS_OK(werr)) {
1021 return werr;
1024 status = GUID_to_ndr_blob(&guid, mem_ctx, &blob);
1025 if (!NT_STATUS_IS_OK(status)) {
1026 gnutls_privkey_deinit(issuer_privkey);
1027 return WERR_INVALID_DATA;
1030 werr = self_sign_cert(mem_ctx,
1031 nb_seconds_validity,
1033 issuer_privkey,
1034 &cert,
1035 &blob);
1036 if (!W_ERROR_IS_OK(werr)) {
1037 gnutls_privkey_deinit(issuer_privkey);
1038 return WERR_INVALID_DATA;
1041 rc = gnutls_x509_crt_export2(cert, GNUTLS_X509_FMT_DER, &cert_blob);
1042 if (rc != GNUTLS_E_SUCCESS) {
1043 DBG_ERR("gnutls_x509_crt_export2 failed - %s\n",
1044 gnutls_strerror(rc));
1045 gnutls_privkey_deinit(issuer_privkey);
1046 gnutls_x509_crt_deinit(cert);
1047 return WERR_INVALID_DATA;
1050 keypair.cert.length = cert_blob.size;
1051 keypair.cert.data = talloc_memdup(mem_ctx, cert_blob.data, cert_blob.size);
1052 gnutls_x509_crt_deinit(cert);
1053 gnutls_free(cert_blob.data);
1054 if (keypair.cert.data == NULL) {
1055 gnutls_privkey_deinit(issuer_privkey);
1056 return WERR_NOT_ENOUGH_MEMORY;
1059 rc = gnutls_privkey_export_rsa_raw(issuer_privkey,
1066 &e1,
1067 &e2);
1068 if (rc != GNUTLS_E_SUCCESS) {
1069 gnutls_privkey_deinit(issuer_privkey);
1070 return WERR_INVALID_DATA;
1074 * Heimdal's bignum are big endian and the
1075 * structure expect it to be in little endian
1076 * so we reverse the buffer to make it work
1078 tmp = reverse_and_get_blob(mem_ctx, &e);
1079 if (tmp == NULL) {
1080 ok = false;
1081 } else {
1082 SMB_ASSERT(tmp->length <= 4);
1083 keypair.public_exponent = *tmp;
1086 tmp = reverse_and_get_blob(mem_ctx, &d);
1087 if (tmp == NULL) {
1088 ok = false;
1089 } else {
1090 keypair.private_exponent = *tmp;
1093 tmp = reverse_and_get_blob(mem_ctx, &m);
1094 if (tmp == NULL) {
1095 ok = false;
1096 } else {
1097 keypair.modulus = *tmp;
1100 tmp = reverse_and_get_blob(mem_ctx, &p);
1101 if (tmp == NULL) {
1102 ok = false;
1103 } else {
1104 keypair.prime1 = *tmp;
1107 tmp = reverse_and_get_blob(mem_ctx, &q);
1108 if (tmp == NULL) {
1109 ok = false;
1110 } else {
1111 keypair.prime2 = *tmp;
1114 tmp = reverse_and_get_blob(mem_ctx, &e1);
1115 if (tmp == NULL) {
1116 ok = false;
1117 } else {
1118 keypair.exponent1 = *tmp;
1121 tmp = reverse_and_get_blob(mem_ctx, &e2);
1122 if (tmp == NULL) {
1123 ok = false;
1124 } else {
1125 keypair.exponent2 = *tmp;
1128 tmp = reverse_and_get_blob(mem_ctx, &u);
1129 if (tmp == NULL) {
1130 ok = false;
1131 } else {
1132 keypair.coefficient = *tmp;
1135 /* One of the keypair allocation was wrong */
1136 if (ok == false) {
1137 gnutls_privkey_deinit(issuer_privkey);
1138 return WERR_INVALID_DATA;
1141 keypair.certificate_len = keypair.cert.length;
1142 ndr_err = ndr_push_struct_blob(&blobkeypair,
1143 mem_ctx,
1144 &keypair,
1145 (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1146 gnutls_privkey_deinit(issuer_privkey);
1147 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1148 return WERR_INVALID_DATA;
1151 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", GUID_string(mem_ctx, &guid));
1152 if (secret_name == NULL) {
1153 return WERR_OUTOFMEMORY;
1156 status = set_lsa_secret(mem_ctx, ldb_ctx, secret_name, &blobkeypair);
1157 if (!NT_STATUS_IS_OK(status)) {
1158 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1160 talloc_free(secret_name);
1162 GUID_to_ndr_blob(&guid, mem_ctx, &blob);
1163 status = set_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1164 if (!NT_STATUS_IS_OK(status)) {
1165 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1168 return WERR_OK;
1171 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1172 struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1174 struct GUID guid;
1175 char *guid_string;
1176 DATA_BLOB lsa_secret;
1177 enum ndr_err_code ndr_err;
1178 NTSTATUS status;
1181 * here we basically need to return our certificate
1182 * search for lsa secret BCKUPKEY_PREFERRED first
1185 status = get_lsa_secret(mem_ctx,
1186 ldb_ctx,
1187 "BCKUPKEY_PREFERRED",
1188 &lsa_secret);
1189 if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1190 /* Ok we can be in this case if there was no certs */
1191 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1192 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1193 lpcfg_realm(lp_ctx));
1195 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1196 if (!W_ERROR_IS_OK(werr)) {
1197 return WERR_INVALID_PARAMETER;
1199 status = get_lsa_secret(mem_ctx,
1200 ldb_ctx,
1201 "BCKUPKEY_PREFERRED",
1202 &lsa_secret);
1204 if (!NT_STATUS_IS_OK(status)) {
1205 /* Ok we really don't manage to get this certs ...*/
1206 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1207 return WERR_FILE_NOT_FOUND;
1209 } else if (!NT_STATUS_IS_OK(status)) {
1210 return WERR_INTERNAL_ERROR;
1213 if (lsa_secret.length == 0) {
1214 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1215 return WERR_INTERNAL_ERROR;
1216 } else {
1217 char *cert_secret_name;
1219 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1220 if (!NT_STATUS_IS_OK(status)) {
1221 return WERR_FILE_NOT_FOUND;
1224 guid_string = GUID_string(mem_ctx, &guid);
1225 if (guid_string == NULL) {
1226 /* We return file not found because the client
1227 * expect this error
1229 return WERR_FILE_NOT_FOUND;
1232 cert_secret_name = talloc_asprintf(mem_ctx,
1233 "BCKUPKEY_%s",
1234 guid_string);
1235 status = get_lsa_secret(mem_ctx,
1236 ldb_ctx,
1237 cert_secret_name,
1238 &lsa_secret);
1239 if (!NT_STATUS_IS_OK(status)) {
1240 return WERR_FILE_NOT_FOUND;
1243 if (lsa_secret.length != 0) {
1244 struct bkrp_exported_RSA_key_pair keypair;
1245 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1246 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1247 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1248 return WERR_FILE_NOT_FOUND;
1250 *(r->out.data_out_len) = keypair.cert.length;
1251 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1252 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1253 return WERR_OK;
1254 } else {
1255 DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1256 return WERR_INTERNAL_ERROR;
1260 return WERR_NOT_SUPPORTED;
1263 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1265 struct GUID guid = GUID_random();
1266 enum ndr_err_code ndr_err;
1267 DATA_BLOB blob_wrap_key, guid_blob;
1268 struct bkrp_dc_serverwrap_key wrap_key;
1269 NTSTATUS status;
1270 char *secret_name;
1271 TALLOC_CTX *frame = talloc_stackframe();
1273 generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1275 ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1276 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1277 TALLOC_FREE(frame);
1278 return WERR_INVALID_DATA;
1281 secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1282 if (secret_name == NULL) {
1283 TALLOC_FREE(frame);
1284 return WERR_NOT_ENOUGH_MEMORY;
1287 status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1288 if (!NT_STATUS_IS_OK(status)) {
1289 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1290 TALLOC_FREE(frame);
1291 return WERR_INTERNAL_ERROR;
1294 status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1295 if (!NT_STATUS_IS_OK(status)) {
1296 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1297 TALLOC_FREE(frame);
1300 status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1301 if (!NT_STATUS_IS_OK(status)) {
1302 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1303 TALLOC_FREE(frame);
1304 return WERR_INTERNAL_ERROR;
1307 TALLOC_FREE(frame);
1309 return WERR_OK;
1313 * Find the specified decryption keys from the LSA secrets store as
1314 * G$BCKUPKEY_keyGuidString.
1317 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1318 struct bkrp_dc_serverwrap_key *server_key,
1319 struct GUID *guid)
1321 NTSTATUS status;
1322 DATA_BLOB lsa_secret;
1323 char *secret_name;
1324 char *guid_string;
1325 enum ndr_err_code ndr_err;
1327 guid_string = GUID_string(mem_ctx, guid);
1328 if (guid_string == NULL) {
1329 /* We return file not found because the client
1330 * expect this error
1332 return WERR_FILE_NOT_FOUND;
1335 secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1336 if (secret_name == NULL) {
1337 return WERR_NOT_ENOUGH_MEMORY;
1340 status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1341 if (!NT_STATUS_IS_OK(status)) {
1342 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1343 return WERR_INVALID_DATA;
1345 if (lsa_secret.length == 0) {
1346 /* RODC case, we do not have secrets locally */
1347 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1348 secret_name));
1349 return WERR_INTERNAL_ERROR;
1351 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1352 (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1353 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1354 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1355 return WERR_INVALID_DATA;
1358 return WERR_OK;
1362 * Find the current, preferred ServerWrap Key by looking at
1363 * G$BCKUPKEY_P in the LSA secrets store.
1365 * Then find the current decryption keys from the LSA secrets store as
1366 * G$BCKUPKEY_keyGuidString.
1369 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1370 struct ldb_context *ldb_ctx,
1371 struct bkrp_dc_serverwrap_key *server_key,
1372 struct GUID *returned_guid)
1374 NTSTATUS status;
1375 DATA_BLOB guid_binary;
1377 status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1378 if (!NT_STATUS_IS_OK(status)) {
1379 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1380 return WERR_FILE_NOT_FOUND;
1381 } else if (guid_binary.length == 0) {
1382 /* RODC case, we do not have secrets locally */
1383 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1384 return WERR_INTERNAL_ERROR;
1387 status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1388 if (!NT_STATUS_IS_OK(status)) {
1389 return WERR_FILE_NOT_FOUND;
1392 return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1393 server_key, returned_guid);
1396 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1397 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1399 struct auth_session_info *session_info =
1400 dcesrv_call_session_info(dce_call);
1401 WERROR werr;
1402 struct bkrp_server_side_wrapped decrypt_request;
1403 DATA_BLOB sid_blob, encrypted_blob;
1404 DATA_BLOB blob;
1405 enum ndr_err_code ndr_err;
1406 struct bkrp_dc_serverwrap_key server_key;
1407 struct bkrp_rc4encryptedpayload rc4payload;
1408 struct dom_sid *caller_sid;
1409 uint8_t symkey[20]; /* SHA-1 hash len */
1410 uint8_t mackey[20]; /* SHA-1 hash len */
1411 uint8_t mac[20]; /* SHA-1 hash len */
1412 gnutls_hmac_hd_t hmac_hnd;
1413 gnutls_cipher_hd_t cipher_hnd;
1414 gnutls_datum_t cipher_key;
1415 int rc;
1417 blob.data = r->in.data_in;
1418 blob.length = r->in.data_in_len;
1420 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1421 return WERR_INVALID_PARAMETER;
1424 ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1425 (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1426 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1427 return WERR_INVALID_PARAMETER;
1430 if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1431 return WERR_INVALID_PARAMETER;
1434 werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1435 &decrypt_request.guid);
1436 if (!W_ERROR_IS_OK(werr)) {
1437 return werr;
1440 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1442 dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1445 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1446 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1449 rc = gnutls_hmac_init(&hmac_hnd,
1450 GNUTLS_MAC_SHA1,
1451 server_key.key,
1452 sizeof(server_key.key));
1453 if (rc != GNUTLS_E_SUCCESS) {
1454 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1457 rc = gnutls_hmac(hmac_hnd,
1458 decrypt_request.r2,
1459 sizeof(decrypt_request.r2));
1461 if (rc != GNUTLS_E_SUCCESS) {
1462 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1465 gnutls_hmac_output(hmac_hnd, symkey);
1466 dump_data_pw("symkey: \n", symkey, sizeof(symkey));
1468 /* rc4 decrypt sid and secret using sym key */
1469 cipher_key.data = symkey;
1470 cipher_key.size = sizeof(symkey);
1472 encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1473 decrypt_request.ciphertext_length);
1475 rc = gnutls_cipher_init(&cipher_hnd,
1476 GNUTLS_CIPHER_ARCFOUR_128,
1477 &cipher_key,
1478 NULL);
1479 if (rc != GNUTLS_E_SUCCESS) {
1480 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1482 rc = gnutls_cipher_encrypt2(cipher_hnd,
1483 encrypted_blob.data,
1484 encrypted_blob.length,
1485 encrypted_blob.data,
1486 encrypted_blob.length);
1487 gnutls_cipher_deinit(cipher_hnd);
1488 if (rc != GNUTLS_E_SUCCESS) {
1489 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1492 ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1493 (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1494 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1495 return WERR_INVALID_PARAMETER;
1498 if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1499 return WERR_INVALID_PARAMETER;
1502 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1505 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1506 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1508 rc = gnutls_hmac(hmac_hnd,
1509 rc4payload.r3,
1510 sizeof(rc4payload.r3));
1511 if (rc != GNUTLS_E_SUCCESS) {
1512 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1515 gnutls_hmac_deinit(hmac_hnd, mackey);
1517 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1519 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1520 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1521 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1522 return WERR_INTERNAL_ERROR;
1525 rc = gnutls_hmac_init(&hmac_hnd,
1526 GNUTLS_MAC_SHA1,
1527 mackey,
1528 sizeof(mackey));
1529 if (rc != GNUTLS_E_SUCCESS) {
1530 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1533 /* SID field */
1534 rc = gnutls_hmac(hmac_hnd,
1535 sid_blob.data,
1536 sid_blob.length);
1537 if (rc != GNUTLS_E_SUCCESS) {
1538 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1541 /* Secret field */
1542 rc = gnutls_hmac(hmac_hnd,
1543 rc4payload.secret_data.data,
1544 rc4payload.secret_data.length);
1545 if (rc != GNUTLS_E_SUCCESS) {
1546 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1549 gnutls_hmac_deinit(hmac_hnd, mac);
1550 dump_data_pw("mac: \n", mac, sizeof(mac));
1551 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1553 if (!mem_equal_const_time(mac, rc4payload.mac, sizeof(mac))) {
1554 return WERR_INVALID_ACCESS;
1557 caller_sid = &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_PARAMETER;
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 decryption 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 struct auth_session_info *session_info =
1611 dcesrv_call_session_info(dce_call);
1612 DATA_BLOB sid_blob, encrypted_blob, server_wrapped_blob;
1613 WERROR werr;
1614 struct dom_sid *caller_sid;
1615 uint8_t symkey[20]; /* SHA-1 hash len */
1616 uint8_t mackey[20]; /* SHA-1 hash len */
1617 struct bkrp_rc4encryptedpayload rc4payload;
1618 gnutls_hmac_hd_t hmac_hnd;
1619 struct bkrp_dc_serverwrap_key server_key;
1620 enum ndr_err_code ndr_err;
1621 struct bkrp_server_side_wrapped server_side_wrapped;
1622 struct GUID guid;
1623 gnutls_cipher_hd_t cipher_hnd;
1624 gnutls_datum_t cipher_key;
1625 int rc;
1627 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1628 return WERR_INVALID_PARAMETER;
1631 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1632 ldb_ctx, &server_key,
1633 &guid);
1635 if (!W_ERROR_IS_OK(werr)) {
1636 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1637 /* Generate the server wrap key since one wasn't found */
1638 werr = generate_bkrp_server_wrap_key(mem_ctx,
1639 ldb_ctx);
1640 if (!W_ERROR_IS_OK(werr)) {
1641 return WERR_INVALID_PARAMETER;
1643 werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1644 ldb_ctx,
1645 &server_key,
1646 &guid);
1648 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1649 /* Ok we really don't manage to get this secret ...*/
1650 return WERR_FILE_NOT_FOUND;
1652 } else {
1653 /* In theory we should NEVER reach this point as it
1654 should only appear in a rodc server */
1655 /* we do not have the real secret attribute */
1656 return WERR_INVALID_PARAMETER;
1660 caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1662 dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1665 * This is the key derivation step, so that the HMAC and RC4
1666 * operations over the user-supplied data are not able to
1667 * disclose the master key. By using random data, the symkey
1668 * and mackey values are unique for this operation, and
1669 * discovering these (by reversing the RC4 over the
1670 * attacker-controlled data) does not return something able to
1671 * be used to decrypt the encrypted data of other users
1673 generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1675 dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1677 generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1679 dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1683 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1684 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1686 rc = gnutls_hmac_init(&hmac_hnd,
1687 GNUTLS_MAC_SHA1,
1688 server_key.key,
1689 sizeof(server_key.key));
1690 if (rc != GNUTLS_E_SUCCESS) {
1691 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1694 rc = gnutls_hmac(hmac_hnd,
1695 server_side_wrapped.r2,
1696 sizeof(server_side_wrapped.r2));
1697 if (rc != GNUTLS_E_SUCCESS) {
1698 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1700 gnutls_hmac_output(hmac_hnd, symkey);
1701 dump_data_pw("symkey: \n", symkey, sizeof(symkey));
1704 * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1705 * BACKUPKEY_BACKUP_GUID, it really is the whole key
1707 rc = gnutls_hmac(hmac_hnd,
1708 rc4payload.r3,
1709 sizeof(rc4payload.r3));
1710 if (rc != GNUTLS_E_SUCCESS) {
1711 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1713 gnutls_hmac_deinit(hmac_hnd, mackey);
1714 dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1716 ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1717 (ndr_push_flags_fn_t)ndr_push_dom_sid);
1718 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1719 return WERR_INTERNAL_ERROR;
1722 rc4payload.secret_data.data = r->in.data_in;
1723 rc4payload.secret_data.length = r->in.data_in_len;
1725 rc = gnutls_hmac_init(&hmac_hnd,
1726 GNUTLS_MAC_SHA1,
1727 mackey,
1728 sizeof(mackey));
1729 if (rc != GNUTLS_E_SUCCESS) {
1730 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1733 /* SID field */
1734 rc = gnutls_hmac(hmac_hnd,
1735 sid_blob.data,
1736 sid_blob.length);
1737 if (rc != GNUTLS_E_SUCCESS) {
1738 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1741 /* Secret field */
1742 rc = gnutls_hmac(hmac_hnd,
1743 rc4payload.secret_data.data,
1744 rc4payload.secret_data.length);
1745 if (rc != GNUTLS_E_SUCCESS) {
1746 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1749 gnutls_hmac_deinit(hmac_hnd, rc4payload.mac);
1750 dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1752 rc4payload.sid = *caller_sid;
1754 ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1755 (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1756 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1757 return WERR_INTERNAL_ERROR;
1760 /* rc4 encrypt sid and secret using sym key */
1761 cipher_key.data = symkey;
1762 cipher_key.size = sizeof(symkey);
1764 rc = gnutls_cipher_init(&cipher_hnd,
1765 GNUTLS_CIPHER_ARCFOUR_128,
1766 &cipher_key,
1767 NULL);
1768 if (rc != GNUTLS_E_SUCCESS) {
1769 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1771 rc = gnutls_cipher_encrypt2(cipher_hnd,
1772 encrypted_blob.data,
1773 encrypted_blob.length,
1774 encrypted_blob.data,
1775 encrypted_blob.length);
1776 gnutls_cipher_deinit(cipher_hnd);
1777 if (rc != GNUTLS_E_SUCCESS) {
1778 return gnutls_error_to_werror(rc, WERR_INTERNAL_ERROR);
1781 /* create server wrap structure */
1783 server_side_wrapped.payload_length = rc4payload.secret_data.length;
1784 server_side_wrapped.ciphertext_length = encrypted_blob.length;
1785 server_side_wrapped.guid = guid;
1786 server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1788 ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1789 (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1790 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1791 return WERR_INTERNAL_ERROR;
1794 *(r->out.data_out) = server_wrapped_blob.data;
1795 *(r->out.data_out_len) = server_wrapped_blob.length;
1797 return WERR_OK;
1800 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1801 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1803 WERROR error = WERR_INVALID_PARAMETER;
1804 struct ldb_context *ldb_ctx;
1805 bool is_rodc;
1806 const char *addr = "unknown";
1807 /* At which level we start to add more debug of what is done in the protocol */
1808 const int debuglevel = 4;
1810 if (DEBUGLVL(debuglevel)) {
1811 const struct tsocket_address *remote_address;
1812 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1813 if (tsocket_address_is_inet(remote_address, "ip")) {
1814 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1815 W_ERROR_HAVE_NO_MEMORY(addr);
1819 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1820 return WERR_NOT_SUPPORTED;
1824 * Save the current remote session details so they can used by the
1825 * audit logging module. This allows the audit logging to report the
1826 * remote users details, rather than the system users details.
1828 ldb_ctx = dcesrv_samdb_connect_as_system(mem_ctx, dce_call);
1830 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1831 talloc_unlink(mem_ctx, ldb_ctx);
1832 return WERR_INVALID_PARAMETER;
1835 if (!is_rodc) {
1836 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1837 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1838 DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1839 error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1842 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1843 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1844 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1845 error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1848 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1849 BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1850 DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1851 error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1854 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1855 BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1856 DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1857 error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1860 /*else: I am a RODC so I don't handle backup key protocol */
1862 talloc_unlink(mem_ctx, ldb_ctx);
1863 return error;
1866 /* include the generated boilerplate */
1867 #include "librpc/gen_ndr/ndr_backupkey_s.c"