2 Unix SMB/CIFS implementation.
4 endpoint server for the backupkey interface
6 Copyright (C) Matthieu Patou <mat@samba.org> 2010
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "rpc_server/dcerpc_server.h"
24 #include "librpc/gen_ndr/ndr_backupkey.h"
25 #include "dsdb/common/util.h"
26 #include "dsdb/samdb/samdb.h"
27 #include "lib/ldb/include/ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "param/param.h"
30 #include "auth/session.h"
31 #include "heimdal/lib/hx509/hx_locl.h"
32 #include "heimdal/lib/hcrypto/rsa.h"
33 #include "heimdal/lib/hcrypto/bn.h"
34 #include "../lib/tsocket/tsocket.h"
35 #include "../libcli/security/security.h"
37 #define BACKUPKEY_MIN_VERSION 2
38 #define BACKUPKEY_MAX_VERSION 3
40 static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
41 /* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
42 static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
43 { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
46 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
47 struct ldb_context *ldb,
49 const DATA_BLOB *secret)
51 struct ldb_message *msg;
52 struct ldb_result *res;
53 struct ldb_dn *domain_dn;
54 struct ldb_dn *system_dn;
58 struct timeval now = timeval_current();
59 NTTIME nt_now = timeval_to_nttime(&now);
60 const char *attrs[] = {
64 domain_dn = ldb_get_default_basedn(ldb);
66 return NT_STATUS_INTERNAL_ERROR;
69 msg = ldb_msg_new(mem_ctx);
71 return NT_STATUS_NO_MEMORY;
75 * This function is a lot like dcesrv_lsa_CreateSecret
76 * in the rpc_server/lsa directory
77 * The reason why we duplicate the effort here is that:
78 * * we want to keep the former function static
79 * * we want to avoid the burden of doing LSA calls
80 * when we can just manipulate the secrets directly
81 * * taillor the function to the particular needs of backup protocol
84 system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
85 if (system_dn == NULL) {
87 return NT_STATUS_NO_MEMORY;
90 name2 = talloc_asprintf(msg, "%s Secret", name);
93 return NT_STATUS_NO_MEMORY;
96 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
97 "(&(cn=%s)(objectclass=secret))",
98 ldb_binary_encode_string(mem_ctx, name2));
100 if (ret != LDB_SUCCESS || res->count != 0 ) {
101 DEBUG(2, ("Secret %s already exists !\n", name2));
103 return NT_STATUS_OBJECT_NAME_COLLISION;
107 * We don't care about previous value as we are
108 * here only if the key didn't exists before
111 msg->dn = ldb_dn_copy(mem_ctx, system_dn);
112 if (msg->dn == NULL) {
114 return NT_STATUS_NO_MEMORY;
116 if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
118 return NT_STATUS_NO_MEMORY;
121 ret = ldb_msg_add_string(msg, "cn", name2);
122 if (ret != LDB_SUCCESS) {
124 return NT_STATUS_NO_MEMORY;
126 ret = ldb_msg_add_string(msg, "objectClass", "secret");
127 if (ret != LDB_SUCCESS) {
129 return NT_STATUS_NO_MEMORY;
131 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
132 if (ret != LDB_SUCCESS) {
134 return NT_STATUS_NO_MEMORY;
136 val.data = secret->data;
137 val.length = secret->length;
138 ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
139 if (ret != LDB_SUCCESS) {
141 return NT_STATUS_NO_MEMORY;
143 ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
144 if (ret != LDB_SUCCESS) {
146 return NT_STATUS_NO_MEMORY;
150 * create the secret with DSDB_MODIFY_RELAX
151 * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
152 * the create of LSA secret object
154 ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
155 if (ret != LDB_SUCCESS) {
156 DEBUG(2,("Failed to create secret record %s: %s\n",
157 ldb_dn_get_linearized(msg->dn),
158 ldb_errstring(ldb)));
160 return NT_STATUS_ACCESS_DENIED;
167 /* This function is pretty much like dcesrv_lsa_QuerySecret */
168 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
169 struct ldb_context *ldb,
174 struct ldb_result *res;
175 struct ldb_dn *domain_dn;
176 struct ldb_dn *system_dn;
177 const struct ldb_val *val;
179 const char *attrs[] = {
188 domain_dn = ldb_get_default_basedn(ldb);
190 return NT_STATUS_INTERNAL_ERROR;
193 tmp_mem = talloc_new(mem_ctx);
194 if (tmp_mem == NULL) {
195 return NT_STATUS_NO_MEMORY;
198 system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
199 if (system_dn == NULL) {
200 talloc_free(tmp_mem);
201 return NT_STATUS_NO_MEMORY;
204 ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
205 "(&(cn=%s Secret)(objectclass=secret))",
206 ldb_binary_encode_string(tmp_mem, name));
208 if (ret != LDB_SUCCESS || res->count == 0) {
209 talloc_free(tmp_mem);
211 * Important NOT to use NT_STATUS_OBJECT_NAME_NOT_FOUND
212 * as this return value is used to detect the case
213 * when we have the secret but without the currentValue
216 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
219 if (res->count > 1) {
220 DEBUG(2, ("Secret %s collision\n", name));
221 talloc_free(tmp_mem);
222 return NT_STATUS_INTERNAL_DB_CORRUPTION;
225 val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
228 * The secret object is here but we don't have the secret value
229 * The most common case is a RODC
231 talloc_free(tmp_mem);
232 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
236 secret->data = talloc_move(mem_ctx, &data);
237 secret->length = val->length;
239 talloc_free(tmp_mem);
243 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
246 DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
249 blob.length = BN_num_bytes(bn);
250 blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
252 if (blob.data == NULL) {
256 BN_bn2bin(bn, blob.data);
258 rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
259 if (rev->data == NULL) {
263 for(i=0; i < blob.length; i++) {
264 rev->data[i] = blob.data[blob.length - i -1];
266 rev->length = blob.length;
267 talloc_free(blob.data);
271 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
277 rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
278 if (rev.data == NULL) {
282 for(i=0; i < blob->length; i++) {
283 rev.data[i] = blob->data[blob->length - i -1];
285 rev.length = blob->length;
287 ret = BN_bin2bn(rev.data, rev.length, NULL);
288 talloc_free(rev.data);
293 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
294 struct bkrp_exported_RSA_key_pair *keypair,
295 hx509_private_key *pk)
299 struct hx509_private_key_ops *ops;
301 hx509_context_init(&hctx);
302 ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
304 DEBUG(2, ("Not supported algorithm\n"));
305 return NT_STATUS_INTERNAL_ERROR;
308 if (_hx509_private_key_init(pk, ops, NULL) != 0) {
309 hx509_context_free(&hctx);
310 return NT_STATUS_NO_MEMORY;
315 hx509_context_free(&hctx);
316 return NT_STATUS_INVALID_PARAMETER;
319 rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
320 if (rsa->n == NULL) {
322 hx509_context_free(&hctx);
323 return NT_STATUS_INVALID_PARAMETER;
325 rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
326 if (rsa->d == NULL) {
328 hx509_context_free(&hctx);
329 return NT_STATUS_INVALID_PARAMETER;
331 rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
332 if (rsa->p == NULL) {
334 hx509_context_free(&hctx);
335 return NT_STATUS_INVALID_PARAMETER;
337 rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
338 if (rsa->q == NULL) {
340 hx509_context_free(&hctx);
341 return NT_STATUS_INVALID_PARAMETER;
343 rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
344 if (rsa->dmp1 == NULL) {
346 hx509_context_free(&hctx);
347 return NT_STATUS_INVALID_PARAMETER;
349 rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
350 if (rsa->dmq1 == NULL) {
352 hx509_context_free(&hctx);
353 return NT_STATUS_INVALID_PARAMETER;
355 rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
356 if (rsa->iqmp == NULL) {
358 hx509_context_free(&hctx);
359 return NT_STATUS_INVALID_PARAMETER;
361 rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
362 if (rsa->e == NULL) {
364 hx509_context_free(&hctx);
365 return NT_STATUS_INVALID_PARAMETER;
368 _hx509_private_key_assign_rsa(*pk, rsa);
370 hx509_context_free(&hctx);
374 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
377 uint8_t *access_check,
378 uint32_t access_check_len,
379 struct dom_sid **access_sid)
381 heim_octet_string iv;
382 heim_octet_string access_check_os;
389 enum ndr_err_code ndr_err;
392 /* This one should not be freed */
393 const AlgorithmIdentifier *alg;
400 alg = hx509_crypto_des_rsdi_ede3_cbc();
406 alg =hx509_crypto_aes256_cbc();
410 return WERR_INVALID_DATA;
413 hx509_context_init(&hctx);
414 res = hx509_crypto_init(hctx, NULL,
417 hx509_context_free(&hctx);
420 return WERR_INVALID_DATA;
423 res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
425 iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
429 hx509_crypto_destroy(crypto);
430 return WERR_INVALID_DATA;
433 hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
434 res = hx509_crypto_decrypt(crypto,
441 hx509_crypto_destroy(crypto);
442 return WERR_INVALID_DATA;
445 blob_us.data = access_check_os.data;
446 blob_us.length = access_check_os.length;
448 hx509_crypto_destroy(crypto);
451 uint32_t hash_size = 20;
452 uint8_t hash[hash_size];
454 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
456 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
457 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
458 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
459 /* Unable to unmarshall */
460 der_free_octet_string(&access_check_os);
461 return WERR_INVALID_DATA;
463 if (uncrypted_accesscheckv2.magic != 0x1) {
465 der_free_octet_string(&access_check_os);
466 return WERR_INVALID_DATA;
470 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
471 SHA1_Final(hash, &sctx);
472 der_free_octet_string(&access_check_os);
474 * We free it after the sha1 calculation because blob.data
475 * point to the same area
478 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
479 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
480 return WERR_INVALID_DATA;
482 *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv2.sid));
483 if (*access_sid == NULL) {
490 uint32_t hash_size = 64;
491 uint8_t hash[hash_size];
492 struct hc_sha512state sctx;
493 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
495 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
496 (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
497 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
498 /* Unable to unmarshall */
499 der_free_octet_string(&access_check_os);
500 return WERR_INVALID_DATA;
502 if (uncrypted_accesscheckv3.magic != 0x1) {
504 der_free_octet_string(&access_check_os);
505 return WERR_INVALID_DATA;
509 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
510 SHA512_Final(hash, &sctx);
511 der_free_octet_string(&access_check_os);
513 * We free it after the sha1 calculation because blob.data
514 * point to the same area
517 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
518 DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
519 return WERR_INVALID_DATA;
521 *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv3.sid));
522 if (*access_sid == NULL) {
528 /* Never reached normally as we filtered at the switch / case level */
529 return WERR_INVALID_DATA;
532 static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call,
534 struct bkrp_BackupKey *r,
535 struct ldb_context *ldb_ctx)
537 struct bkrp_client_side_wrapped uncrypt_request;
539 enum ndr_err_code ndr_err;
541 char *cert_secret_name;
543 DATA_BLOB *uncrypted;
546 blob.data = r->in.data_in;
547 blob.length = r->in.data_in_len;
549 if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
550 return WERR_INVALID_PARAM;
553 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
554 (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
555 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
556 return WERR_INVALID_PARAM;
559 if (uncrypt_request.version < BACKUPKEY_MIN_VERSION) {
560 return WERR_INVALID_PARAMETER;
563 if (uncrypt_request.version > BACKUPKEY_MAX_VERSION) {
564 return WERR_INVALID_PARAMETER;
567 guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
568 if (guid_string == NULL) {
572 cert_secret_name = talloc_asprintf(mem_ctx,
575 if (cert_secret_name == NULL) {
579 status = get_lsa_secret(mem_ctx,
583 if (!NT_STATUS_IS_OK(status)) {
584 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
585 if (NT_STATUS_EQUAL(status,NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
586 /* we do not have the real secret attribute */
587 return WERR_INVALID_PARAMETER;
589 return WERR_FILE_NOT_FOUND;
593 if (secret.length != 0) {
595 struct bkrp_exported_RSA_key_pair keypair;
596 hx509_private_key pk;
598 struct dom_sid *access_sid = NULL;
599 heim_octet_string reversed_secret;
600 heim_octet_string uncrypted_secret;
601 AlgorithmIdentifier alg;
602 struct dom_sid *caller_sid;
606 ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
607 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
608 DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
609 return WERR_FILE_NOT_FOUND;
612 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
613 if (!NT_STATUS_IS_OK(status)) {
614 return WERR_INTERNAL_ERROR;
617 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
618 uncrypt_request.encrypted_secret_len);
619 if (reversed_secret.data == NULL) {
620 _hx509_private_key_free(&pk);
624 /* The secret has to be reversed ... */
625 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
626 uint8_t *reversed = (uint8_t *)reversed_secret.data;
627 uint8_t *uncrypt = uncrypt_request.encrypted_secret;
628 reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
630 reversed_secret.length = uncrypt_request.encrypted_secret_len;
633 * Let's try to decrypt the secret now that
634 * we have the private key ...
636 hx509_context_init(&hctx);
637 res = _hx509_private_key_private_decrypt(hctx, &reversed_secret,
640 hx509_context_free(&hctx);
641 _hx509_private_key_free(&pk);
643 /* We are not able to decrypt the secret, looks like something is wrong */
644 return WERR_INVALID_DATA;
646 blob_us.data = uncrypted_secret.data;
647 blob_us.length = uncrypted_secret.length;
649 if (uncrypt_request.version == 2) {
650 struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
652 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
653 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
654 der_free_octet_string(&uncrypted_secret);
655 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
656 /* Unable to unmarshall */
657 return WERR_INVALID_DATA;
659 if (uncrypted_secretv2.magic != 0x20) {
661 return WERR_INVALID_DATA;
664 werr = get_and_verify_access_check(mem_ctx, 2,
665 uncrypted_secretv2.payload_key,
666 uncrypt_request.access_check,
667 uncrypt_request.access_check_len,
669 if (!W_ERROR_IS_OK(werr)) {
672 uncrypted = talloc(mem_ctx, DATA_BLOB);
673 if (uncrypted == NULL) {
674 return WERR_INVALID_DATA;
677 uncrypted->data = uncrypted_secretv2.secret;
678 uncrypted->length = uncrypted_secretv2.secret_len;
680 if (uncrypt_request.version == 3) {
681 struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
683 ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
684 (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
686 der_free_octet_string(&uncrypted_secret);
687 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
688 /* Unable to unmarshall */
689 return WERR_INVALID_DATA;
692 if (uncrypted_secretv3.magic1 != 0x30 ||
693 uncrypted_secretv3.magic2 != 0x6610 ||
694 uncrypted_secretv3.magic3 != 0x800e) {
696 return WERR_INVALID_DATA;
699 werr = get_and_verify_access_check(mem_ctx, 3,
700 uncrypted_secretv3.payload_key,
701 uncrypt_request.access_check,
702 uncrypt_request.access_check_len,
704 if (!W_ERROR_IS_OK(werr)) {
708 uncrypted = talloc(mem_ctx, DATA_BLOB);
709 if (uncrypted == NULL) {
710 return WERR_INVALID_DATA;
713 uncrypted->data = uncrypted_secretv3.secret;
714 uncrypted->length = uncrypted_secretv3.secret_len;
717 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
719 if (!dom_sid_equal(caller_sid, access_sid)) {
720 talloc_free(uncrypted);
721 return WERR_INVALID_ACCESS;
725 * Yeah if we are here all looks pretty good:
727 * - user sid is the same as the one in access check
728 * - we were able to decrypt the whole stuff
732 if (uncrypted->data == NULL) {
733 return WERR_INVALID_DATA;
736 /* There is a magic value a the beginning of the data
737 * we can use an adhoc structure but as the
738 * parent structure is just an array of bytes it a lot of work
739 * work just prepending 4 bytes
741 *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted->length + 4);
742 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
743 memcpy(4+*(r->out.data_out), uncrypted->data, uncrypted->length);
744 *(r->out.data_out_len) = uncrypted->length + 4;
749 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
750 hx509_private_key *pk, RSA **_rsa)
762 if(pub_expo == NULL) {
763 return WERR_INTERNAL_ERROR;
766 /* set the public expo to 65537 like everyone */
767 BN_set_word(pub_expo, 0x10001);
772 return WERR_INTERNAL_ERROR;
775 ret = RSA_generate_key_ex(rsa, bits, pub_expo, NULL);
779 return WERR_INTERNAL_ERROR;
783 len = i2d_RSAPrivateKey(rsa, NULL);
786 return WERR_INTERNAL_ERROR;
789 p0 = p = talloc_array(ctx, uint8_t, len);
792 return WERR_INTERNAL_ERROR;
795 len = i2d_RSAPrivateKey(rsa, &p);
799 return WERR_INTERNAL_ERROR;
803 * To dump the key we can use :
804 * rk_dumpdata("h5lkey", p0, len);
806 ret = _hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
807 p0, len, HX509_KEY_FORMAT_DER, pk);
812 return WERR_INTERNAL_ERROR;
819 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
820 time_t lifetime, hx509_private_key *private_key,
821 hx509_cert *cert, DATA_BLOB *guidblob)
823 SubjectPublicKeyInfo spki;
824 hx509_name subject = NULL;
826 struct heim_bit_string uniqueid;
829 uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
830 /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
831 * so as 1 byte is 8 bits we need to provision 8 times more space as in the
834 uniqueid.length = 8 * guidblob->length;
836 memset(&spki, 0, sizeof(spki));
838 ret = _hx509_request_get_name(*hctx, *req, &subject);
840 talloc_free(uniqueid.data);
841 return WERR_INTERNAL_ERROR;
843 ret = _hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
845 talloc_free(uniqueid.data);
846 hx509_name_free(&subject);
847 return WERR_INTERNAL_ERROR;
850 ret = hx509_ca_tbs_init(*hctx, &tbs);
852 talloc_free(uniqueid.data);
853 hx509_name_free(&subject);
854 free_SubjectPublicKeyInfo(&spki);
855 return WERR_INTERNAL_ERROR;
858 ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
860 talloc_free(uniqueid.data);
861 hx509_name_free(&subject);
862 free_SubjectPublicKeyInfo(&spki);
863 return WERR_INTERNAL_ERROR;
865 ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
867 talloc_free(uniqueid.data);
868 hx509_name_free(&subject);
869 free_SubjectPublicKeyInfo(&spki);
870 hx509_ca_tbs_free(&tbs);
871 return WERR_INTERNAL_ERROR;
873 ret = hx509_ca_tbs_set_ca(*hctx, tbs, 1);
875 talloc_free(uniqueid.data);
876 hx509_name_free(&subject);
877 free_SubjectPublicKeyInfo(&spki);
878 hx509_ca_tbs_free(&tbs);
879 return WERR_INTERNAL_ERROR;
881 ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
883 talloc_free(uniqueid.data);
884 hx509_name_free(&subject);
885 free_SubjectPublicKeyInfo(&spki);
886 hx509_ca_tbs_free(&tbs);
887 return WERR_INTERNAL_ERROR;
889 ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
891 talloc_free(uniqueid.data);
892 hx509_name_free(&subject);
893 free_SubjectPublicKeyInfo(&spki);
894 hx509_ca_tbs_free(&tbs);
895 return WERR_INTERNAL_ERROR;
897 ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
899 talloc_free(uniqueid.data);
900 hx509_name_free(&subject);
901 free_SubjectPublicKeyInfo(&spki);
902 hx509_ca_tbs_free(&tbs);
903 return WERR_INTERNAL_ERROR;
905 hx509_name_free(&subject);
906 free_SubjectPublicKeyInfo(&spki);
907 hx509_ca_tbs_free(&tbs);
912 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
913 hx509_private_key *signer,RSA **rsa, const char *dn)
916 SubjectPublicKeyInfo key;
921 w_err = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
922 if (!W_ERROR_IS_OK(w_err)) {
926 _hx509_request_init(*hctx, req);
927 ret = hx509_parse_name(*hctx, dn, &name);
930 _hx509_private_key_free(signer);
931 _hx509_request_free(req);
932 hx509_name_free(&name);
933 return WERR_INTERNAL_ERROR;
936 ret = _hx509_request_set_name(*hctx, *req, name);
939 _hx509_private_key_free(signer);
940 _hx509_request_free(req);
941 hx509_name_free(&name);
942 return WERR_INTERNAL_ERROR;
944 hx509_name_free(&name);
946 ret = _hx509_private_key2SPKI(*hctx, *signer, &key);
949 _hx509_private_key_free(signer);
950 _hx509_request_free(req);
951 return WERR_INTERNAL_ERROR;
953 ret = _hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
956 _hx509_private_key_free(signer);
957 free_SubjectPublicKeyInfo(&key);
958 _hx509_request_free(req);
959 return WERR_INTERNAL_ERROR;
962 free_SubjectPublicKeyInfo(&key);
967 /* Return an error when we fail to generate a certificate */
968 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
971 struct heim_octet_string data;
975 hx509_private_key pk;
979 DATA_BLOB blobkeypair;
983 struct GUID guid = GUID_random();
986 struct bkrp_exported_RSA_key_pair keypair;
987 enum ndr_err_code ndr_err;
988 uint32_t nb_days_validity = 365;
990 DEBUG(6, ("Trying to generate a certificate\n"));
991 hx509_context_init(&hctx);
992 w_err = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
993 if (!W_ERROR_IS_OK(w_err)) {
994 hx509_context_free(&hctx);
998 status = GUID_to_ndr_blob(&guid, ctx, &blob);
999 if (!NT_STATUS_IS_OK(status)) {
1000 hx509_context_free(&hctx);
1001 _hx509_private_key_free(&pk);
1003 return WERR_INVALID_DATA;
1006 w_err = self_sign_cert(ctx, &hctx, &req, nb_days_validity, &pk, &cert, &blob);
1007 if (!W_ERROR_IS_OK(w_err)) {
1008 _hx509_private_key_free(&pk);
1009 hx509_context_free(&hctx);
1010 return WERR_INVALID_DATA;
1013 ret = hx509_cert_binary(hctx, cert, &data);
1015 hx509_cert_free(cert);
1016 _hx509_private_key_free(&pk);
1017 hx509_context_free(&hctx);
1018 return WERR_INVALID_DATA;
1021 keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1022 keypair.cert.length = data.length;
1025 * Heimdal's bignum are big endian and the
1026 * structure expect it to be in little endian
1027 * so we reverse the buffer to make it work
1029 tmp = reverse_and_get_blob(ctx, rsa->e);
1033 keypair.public_exponent = *tmp;
1034 SMB_ASSERT(tmp->length <= 4);
1036 * The value is now in little endian but if can happen that the length is
1037 * less than 4 bytes.
1038 * So if we have less than 4 bytes we pad with zeros so that it correctly
1039 * fit into the structure.
1041 if (tmp->length < 4) {
1043 * We need the expo to fit 4 bytes
1045 keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1046 memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1047 keypair.public_exponent.length = 4;
1051 tmp = reverse_and_get_blob(ctx,rsa->d);
1055 keypair.private_exponent = *tmp;
1058 tmp = reverse_and_get_blob(ctx,rsa->n);
1062 keypair.modulus = *tmp;
1065 tmp = reverse_and_get_blob(ctx,rsa->p);
1069 keypair.prime1 = *tmp;
1072 tmp = reverse_and_get_blob(ctx,rsa->q);
1076 keypair.prime2 = *tmp;
1079 tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1083 keypair.exponent1 = *tmp;
1086 tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1090 keypair.exponent2 = *tmp;
1093 tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1097 keypair.coefficient = *tmp;
1100 /* One of the keypair allocation was wrong */
1102 der_free_octet_string(&data);
1103 hx509_cert_free(cert);
1104 _hx509_private_key_free(&pk);
1105 hx509_context_free(&hctx);
1107 return WERR_INVALID_DATA;
1109 keypair.certificate_len = keypair.cert.length;
1110 ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1111 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1112 der_free_octet_string(&data);
1113 hx509_cert_free(cert);
1114 _hx509_private_key_free(&pk);
1115 hx509_context_free(&hctx);
1117 return WERR_INVALID_DATA;
1120 secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1121 if (secret_name == NULL) {
1122 der_free_octet_string(&data);
1123 hx509_cert_free(cert);
1124 _hx509_private_key_free(&pk);
1125 hx509_context_free(&hctx);
1127 return WERR_OUTOFMEMORY;
1130 status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1131 if (!NT_STATUS_IS_OK(status)) {
1132 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1134 talloc_free(secret_name);
1136 GUID_to_ndr_blob(&guid, ctx, &blob);
1137 status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1138 if (!NT_STATUS_IS_OK(status)) {
1139 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1142 der_free_octet_string(&data);
1143 hx509_cert_free(cert);
1144 _hx509_private_key_free(&pk);
1145 hx509_context_free(&hctx);
1150 static WERROR bkrp_do_retreive_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1151 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1156 enum ndr_err_code ndr_err;
1160 * here we basicaly need to return our certificate
1161 * search for lsa secret BCKUPKEY_PREFERRED first
1164 status = get_lsa_secret(mem_ctx,
1166 "BCKUPKEY_PREFERRED",
1168 if (!NT_STATUS_IS_OK(status)) {
1169 DEBUG(10, ("Error while fetching secret BCKUPKEY_PREFERRED\n"));
1170 if (!NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1171 /* Ok we can be in this case if there was no certs */
1172 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1173 char *dn = talloc_asprintf(mem_ctx, "CN=%s.%s",
1174 lpcfg_netbios_name(lp_ctx),
1175 lpcfg_realm(lp_ctx));
1177 WERROR werr = generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1178 if (!W_ERROR_IS_OK(werr)) {
1179 return WERR_INVALID_PARAMETER;
1181 status = get_lsa_secret(mem_ctx,
1183 "BCKUPKEY_PREFERRED",
1186 if (!NT_STATUS_IS_OK(status)) {
1187 /* Ok we really don't manage to get this certs ...*/
1188 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1189 return WERR_FILE_NOT_FOUND;
1192 /* In theory we should NEVER reach this point as it
1193 should only appear in a rodc server */
1194 /* we do not have the real secret attribute */
1195 return WERR_INVALID_PARAMETER;
1199 if (secret.length != 0) {
1200 char *cert_secret_name;
1202 status = GUID_from_ndr_blob(&secret, &guid);
1203 if (!NT_STATUS_IS_OK(status)) {
1204 return WERR_FILE_NOT_FOUND;
1207 guid_string = GUID_string(mem_ctx, &guid);
1208 if (guid_string == NULL) {
1209 /* We return file not found because the client
1212 return WERR_FILE_NOT_FOUND;
1215 cert_secret_name = talloc_asprintf(mem_ctx,
1218 status = get_lsa_secret(mem_ctx,
1222 if (!NT_STATUS_IS_OK(status)) {
1223 return WERR_FILE_NOT_FOUND;
1226 if (secret.length != 0) {
1227 struct bkrp_exported_RSA_key_pair keypair;
1228 ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair,
1229 (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1230 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1231 return WERR_FILE_NOT_FOUND;
1233 *(r->out.data_out_len) = keypair.cert.length;
1234 *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1235 W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1238 DEBUG(10, ("No or broken secret called %s\n", cert_secret_name));
1239 return WERR_FILE_NOT_FOUND;
1242 DEBUG(10, ("No secret BCKUPKEY_PREFERRED\n"));
1243 return WERR_FILE_NOT_FOUND;
1246 return WERR_NOT_SUPPORTED;
1249 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1250 TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1252 WERROR error = WERR_INVALID_PARAM;
1253 struct ldb_context *ldb_ctx;
1255 const char *addr = "unknown";
1256 /* At which level we start to add more debug of what is done in the protocol */
1257 const int debuglevel = 4;
1259 if (DEBUGLVL(debuglevel)) {
1260 const struct tsocket_address *remote_address;
1261 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1262 if (tsocket_address_is_inet(remote_address, "ip")) {
1263 addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1264 W_ERROR_HAVE_NO_MEMORY(addr);
1268 if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_DOMAIN_CONTROLLER) {
1269 return WERR_NOT_SUPPORTED;
1272 if (!dce_call->conn->auth_state.auth_info ||
1273 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1274 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1277 ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1278 dce_call->conn->dce_ctx->lp_ctx,
1279 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1281 if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1282 talloc_unlink(mem_ctx, ldb_ctx);
1283 return WERR_INVALID_PARAM;
1287 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1288 BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1289 DEBUG(debuglevel, ("Client %s requested to decrypt a client side wrapped secret\n", addr));
1290 error = bkrp_do_uncrypt_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1293 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1294 BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1295 DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1296 error = bkrp_do_retreive_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1299 /*else: I am a RODC so I don't handle backup key protocol */
1301 talloc_unlink(mem_ctx, ldb_ctx);
1305 /* include the generated boilerplate */
1306 #include "librpc/gen_ndr/ndr_backupkey_s.c"