7e733b0b563dc199947201d104fde90ee31f98a2
[obnox/samba/samba-obnox.git] / source4 / rpc_server / backupkey / dcesrv_backupkey_heimdal.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    endpoint server for the backupkey interface
5
6    Copyright (C) Matthieu Patou <mat@samba.org> 2010
7
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.
12
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.
17
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/>.
20 */
21
22 #include "includes.h"
23 #include "rpc_server/dcerpc_server.h"
24 #include "librpc/gen_ndr/ndr_backupkey.h"
25 #include "dsdb/common/util.h"
26 #include "dsdb/samdb/samdb.h"
27 #include "lib/ldb/include/ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "param/param.h"
30 #include "auth/session.h"
31 #include "system/network.h"
32 #include <com_err.h>
33 #include <hx509.h>
34 #include <hcrypto/rsa.h>
35 #include <hcrypto/bn.h>
36 #include <hcrypto/sha.h>
37 #include <hcrypto/evp.h>
38 #include <hcrypto/hmac.h>
39 #include <der.h>
40 #include "../lib/tsocket/tsocket.h"
41 #include "../libcli/security/security.h"
42 #include "librpc/gen_ndr/ndr_security.h"
43 #include "lib/crypto/arcfour.h"
44 #include <gnutls/gnutls.h>
45 #include <gnutls/x509.h>
46 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
47 #include <gcrypt.h>
48 #endif
49
50
51 static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
52 /* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
53 static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
54         { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
55 };
56
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)
61 {
62         struct ldb_message *msg;
63         struct ldb_result *res;
64         struct ldb_dn *domain_dn;
65         struct ldb_dn *system_dn;
66         struct ldb_val val;
67         int ret;
68         char *name2;
69         struct timeval now = timeval_current();
70         NTTIME nt_now = timeval_to_nttime(&now);
71         const char *attrs[] = {
72                 NULL
73         };
74
75         domain_dn = ldb_get_default_basedn(ldb);
76         if (!domain_dn) {
77                 return NT_STATUS_INTERNAL_ERROR;
78         }
79
80         msg = ldb_msg_new(mem_ctx);
81         if (msg == NULL) {
82                 return NT_STATUS_NO_MEMORY;
83         }
84
85         /*
86          * This function is a lot like dcesrv_lsa_CreateSecret
87          * in the rpc_server/lsa directory
88          * The reason why we duplicate the effort here is that:
89          * * we want to keep the former function static
90          * * we want to avoid the burden of doing LSA calls
91          *   when we can just manipulate the secrets directly
92          * * taillor the function to the particular needs of backup protocol
93          */
94
95         system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
96         if (system_dn == NULL) {
97                 talloc_free(msg);
98                 return NT_STATUS_NO_MEMORY;
99         }
100
101         name2 = talloc_asprintf(msg, "%s Secret", name);
102         if (name2 == NULL) {
103                 talloc_free(msg);
104                 return NT_STATUS_NO_MEMORY;
105         }
106
107         ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
108                            "(&(cn=%s)(objectclass=secret))",
109                            ldb_binary_encode_string(mem_ctx, name2));
110
111         if (ret != LDB_SUCCESS ||  res->count != 0 ) {
112                 DEBUG(2, ("Secret %s already exists !\n", name2));
113                 talloc_free(msg);
114                 return NT_STATUS_OBJECT_NAME_COLLISION;
115         }
116
117         /*
118          * We don't care about previous value as we are
119          * here only if the key didn't exists before
120          */
121
122         msg->dn = ldb_dn_copy(mem_ctx, system_dn);
123         if (msg->dn == NULL) {
124                 talloc_free(msg);
125                 return NT_STATUS_NO_MEMORY;
126         }
127         if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
128                 talloc_free(msg);
129                 return NT_STATUS_NO_MEMORY;
130         }
131
132         ret = ldb_msg_add_string(msg, "cn", name2);
133         if (ret != LDB_SUCCESS) {
134                 talloc_free(msg);
135                 return NT_STATUS_NO_MEMORY;
136         }
137         ret = ldb_msg_add_string(msg, "objectClass", "secret");
138         if (ret != LDB_SUCCESS) {
139                 talloc_free(msg);
140                 return NT_STATUS_NO_MEMORY;
141         }
142         ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
143         if (ret != LDB_SUCCESS) {
144                 talloc_free(msg);
145                 return NT_STATUS_NO_MEMORY;
146         }
147         val.data = lsa_secret->data;
148         val.length = lsa_secret->length;
149         ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
150         if (ret != LDB_SUCCESS) {
151                 talloc_free(msg);
152                 return NT_STATUS_NO_MEMORY;
153         }
154         ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
155         if (ret != LDB_SUCCESS) {
156                 talloc_free(msg);
157                 return NT_STATUS_NO_MEMORY;
158         }
159
160         /*
161          * create the secret with DSDB_MODIFY_RELAX
162          * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
163          * the create of LSA secret object
164          */
165         ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
166         if (ret != LDB_SUCCESS) {
167                 DEBUG(2,("Failed to create secret record %s: %s\n",
168                         ldb_dn_get_linearized(msg->dn),
169                         ldb_errstring(ldb)));
170                 talloc_free(msg);
171                 return NT_STATUS_ACCESS_DENIED;
172         }
173
174         talloc_free(msg);
175         return NT_STATUS_OK;
176 }
177
178 /* This function is pretty much like dcesrv_lsa_QuerySecret */
179 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
180                                struct ldb_context *ldb,
181                                const char *name,
182                                DATA_BLOB *lsa_secret)
183 {
184         TALLOC_CTX *tmp_mem;
185         struct ldb_result *res;
186         struct ldb_dn *domain_dn;
187         struct ldb_dn *system_dn;
188         const struct ldb_val *val;
189         uint8_t *data;
190         const char *attrs[] = {
191                 "currentValue",
192                 NULL
193         };
194         int ret;
195
196         lsa_secret->data = NULL;
197         lsa_secret->length = 0;
198
199         domain_dn = ldb_get_default_basedn(ldb);
200         if (!domain_dn) {
201                 return NT_STATUS_INTERNAL_ERROR;
202         }
203
204         tmp_mem = talloc_new(mem_ctx);
205         if (tmp_mem == NULL) {
206                 return NT_STATUS_NO_MEMORY;
207         }
208
209         system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
210         if (system_dn == NULL) {
211                 talloc_free(tmp_mem);
212                 return NT_STATUS_NO_MEMORY;
213         }
214
215         ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
216                            "(&(cn=%s Secret)(objectclass=secret))",
217                            ldb_binary_encode_string(tmp_mem, name));
218
219         if (ret != LDB_SUCCESS) {
220                 talloc_free(tmp_mem);
221                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
222         }
223         if (res->count == 0) {
224                 talloc_free(tmp_mem);
225                 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
226         }
227         if (res->count > 1) {
228                 DEBUG(2, ("Secret %s collision\n", name));
229                 talloc_free(tmp_mem);
230                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
231         }
232
233         val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
234         if (val == NULL) {
235                 /*
236                  * The secret object is here but we don't have the secret value
237                  * The most common case is a RODC
238                  */
239                 *lsa_secret = data_blob_null;
240                 talloc_free(tmp_mem);
241                 return NT_STATUS_OK;
242         }
243
244         data = val->data;
245         lsa_secret->data = talloc_move(mem_ctx, &data);
246         lsa_secret->length = val->length;
247
248         talloc_free(tmp_mem);
249         return NT_STATUS_OK;
250 }
251
252 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
253 {
254         DATA_BLOB blob;
255         DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
256         uint32_t i;
257
258         blob.length = BN_num_bytes(bn);
259         blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
260
261         if (blob.data == NULL) {
262                 return NULL;
263         }
264
265         BN_bn2bin(bn, blob.data);
266
267         rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
268         if (rev->data == NULL) {
269                 return NULL;
270         }
271
272         for(i=0; i < blob.length; i++) {
273                 rev->data[i] = blob.data[blob.length - i -1];
274         }
275         rev->length = blob.length;
276         talloc_free(blob.data);
277         return rev;
278 }
279
280 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
281 {
282         BIGNUM *ret;
283         DATA_BLOB rev;
284         uint32_t i;
285
286         rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
287         if (rev.data == NULL) {
288                 return NULL;
289         }
290
291         for(i=0; i < blob->length; i++) {
292                 rev.data[i] = blob->data[blob->length - i -1];
293         }
294         rev.length = blob->length;
295
296         ret = BN_bin2bn(rev.data, rev.length, NULL);
297         talloc_free(rev.data);
298
299         return ret;
300 }
301
302 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
303                                 struct bkrp_exported_RSA_key_pair *keypair,
304                                 hx509_private_key *pk)
305 {
306         hx509_context hctx;
307         RSA *rsa;
308         struct hx509_private_key_ops *ops;
309         hx509_private_key privkey = NULL;
310
311         hx509_context_init(&hctx);
312         ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
313         if (ops == NULL) {
314                 DEBUG(2, ("Not supported algorithm\n"));
315                 hx509_context_free(&hctx);
316                 return NT_STATUS_INTERNAL_ERROR;
317         }
318
319         if (hx509_private_key_init(&privkey, ops, NULL) != 0) {
320                 hx509_context_free(&hctx);
321                 return NT_STATUS_NO_MEMORY;
322         }
323
324         rsa = RSA_new();
325         if (rsa ==NULL) {
326                 hx509_private_key_free(&privkey);
327                 hx509_context_free(&hctx);
328                 return NT_STATUS_INVALID_PARAMETER;
329         }
330
331         rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
332         if (rsa->n == NULL) {
333                 RSA_free(rsa);
334                 hx509_private_key_free(&privkey);
335                 hx509_context_free(&hctx);
336                 return NT_STATUS_INVALID_PARAMETER;
337         }
338         rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
339         if (rsa->d == NULL) {
340                 RSA_free(rsa);
341                 hx509_private_key_free(&privkey);
342                 hx509_context_free(&hctx);
343                 return NT_STATUS_INVALID_PARAMETER;
344         }
345         rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
346         if (rsa->p == NULL) {
347                 RSA_free(rsa);
348                 hx509_private_key_free(&privkey);
349                 hx509_context_free(&hctx);
350                 return NT_STATUS_INVALID_PARAMETER;
351         }
352         rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
353         if (rsa->q == NULL) {
354                 RSA_free(rsa);
355                 hx509_private_key_free(&privkey);
356                 hx509_context_free(&hctx);
357                 return NT_STATUS_INVALID_PARAMETER;
358         }
359         rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
360         if (rsa->dmp1 == NULL) {
361                 RSA_free(rsa);
362                 hx509_private_key_free(&privkey);
363                 hx509_context_free(&hctx);
364                 return NT_STATUS_INVALID_PARAMETER;
365         }
366         rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
367         if (rsa->dmq1 == NULL) {
368                 RSA_free(rsa);
369                 hx509_private_key_free(&privkey);
370                 hx509_context_free(&hctx);
371                 return NT_STATUS_INVALID_PARAMETER;
372         }
373         rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
374         if (rsa->iqmp == NULL) {
375                 RSA_free(rsa);
376                 hx509_private_key_free(&privkey);
377                 hx509_context_free(&hctx);
378                 return NT_STATUS_INVALID_PARAMETER;
379         }
380         rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
381         if (rsa->e == NULL) {
382                 RSA_free(rsa);
383                 hx509_private_key_free(&privkey);
384                 hx509_context_free(&hctx);
385                 return NT_STATUS_INVALID_PARAMETER;
386         }
387
388         *pk = privkey;
389
390         hx509_private_key_assign_rsa(*pk, rsa);
391
392         hx509_context_free(&hctx);
393         return NT_STATUS_OK;
394 }
395
396 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
397                                           uint32_t version,
398                                           uint8_t *key_and_iv,
399                                           uint8_t *access_check,
400                                           uint32_t access_check_len,
401                                           struct auth_session_info *session_info)
402 {
403         heim_octet_string iv;
404         heim_octet_string access_check_os;
405         hx509_crypto crypto;
406
407         DATA_BLOB blob_us;
408         uint32_t key_len;
409         uint32_t iv_len;
410         int res;
411         enum ndr_err_code ndr_err;
412         hx509_context hctx;
413
414         struct dom_sid *access_sid = NULL;
415         struct dom_sid *caller_sid = NULL;
416
417         /* This one should not be freed */
418         const AlgorithmIdentifier *alg;
419
420         switch (version) {
421         case 2:
422                 key_len = 24;
423                 iv_len = 8;
424                 alg = hx509_crypto_des_rsdi_ede3_cbc();
425                 break;
426
427         case 3:
428                 key_len = 32;
429                 iv_len = 16;
430                 alg =hx509_crypto_aes256_cbc();
431                 break;
432
433         default:
434                 return WERR_INVALID_DATA;
435         }
436
437         hx509_context_init(&hctx);
438         res = hx509_crypto_init(hctx, NULL,
439                                 &(alg->algorithm),
440                                 &crypto);
441         hx509_context_free(&hctx);
442
443         if (res != 0) {
444                 return WERR_INVALID_DATA;
445         }
446
447         res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
448
449         iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
450         iv.length = iv_len;
451
452         if (res != 0) {
453                 hx509_crypto_destroy(crypto);
454                 return WERR_INVALID_DATA;
455         }
456
457         hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
458         res = hx509_crypto_decrypt(crypto,
459                 access_check,
460                 access_check_len,
461                 &iv,
462                 &access_check_os);
463
464         if (res != 0) {
465                 hx509_crypto_destroy(crypto);
466                 return WERR_INVALID_DATA;
467         }
468
469         blob_us.data = access_check_os.data;
470         blob_us.length = access_check_os.length;
471
472         hx509_crypto_destroy(crypto);
473
474         switch (version) {
475         case 2:
476         {
477                 uint32_t hash_size = 20;
478                 uint8_t hash[hash_size];
479                 struct sha sctx;
480                 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
481
482                 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
483                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
484                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
485                         /* Unable to unmarshall */
486                         der_free_octet_string(&access_check_os);
487                         return WERR_INVALID_DATA;
488                 }
489                 if (uncrypted_accesscheckv2.magic != 0x1) {
490                         /* wrong magic */
491                         der_free_octet_string(&access_check_os);
492                         return WERR_INVALID_DATA;
493                 }
494
495                 SHA1_Init(&sctx);
496                 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
497                 SHA1_Final(hash, &sctx);
498                 der_free_octet_string(&access_check_os);
499                 /*
500                  * We free it after the sha1 calculation because blob.data
501                  * point to the same area
502                  */
503
504                 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
505                         DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
506                         return WERR_INVALID_DATA;
507                 }
508                 access_sid = &(uncrypted_accesscheckv2.sid);
509                 break;
510         }
511         case 3:
512         {
513                 uint32_t hash_size = 64;
514                 uint8_t hash[hash_size];
515                 struct hc_sha512state sctx;
516                 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
517
518                 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
519                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
520                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
521                         /* Unable to unmarshall */
522                         der_free_octet_string(&access_check_os);
523                         return WERR_INVALID_DATA;
524                 }
525                 if (uncrypted_accesscheckv3.magic != 0x1) {
526                         /* wrong magic */
527                         der_free_octet_string(&access_check_os);
528                         return WERR_INVALID_DATA;
529                 }
530
531                 SHA512_Init(&sctx);
532                 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
533                 SHA512_Final(hash, &sctx);
534                 der_free_octet_string(&access_check_os);
535                 /*
536                  * We free it after the sha1 calculation because blob.data
537                  * point to the same area
538                  */
539
540                 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
541                         DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
542                         return WERR_INVALID_DATA;
543                 }
544                 access_sid = &(uncrypted_accesscheckv3.sid);
545                 break;
546         }
547         default:
548                 /* Never reached normally as we filtered at the switch / case level */
549                 return WERR_INVALID_DATA;
550         }
551
552         caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
553
554         if (!dom_sid_equal(caller_sid, access_sid)) {
555                 return WERR_INVALID_ACCESS;
556         }
557         return WERR_OK;
558 }
559
560 /*
561  * We have some data, such as saved website or IMAP passwords that the
562  * client has in profile on-disk.  This needs to be decrypted.  This
563  * version gives the server the data over the network (protected by
564  * the X.509 certificate and public key encryption, and asks that it
565  * be decrypted returned for short-term use, protected only by the
566  * negotiated transport encryption.
567  *
568  * The data is NOT stored in the LSA, but a X.509 certificate, public
569  * and private keys used to encrypt the data will be stored.  There is
570  * only one active encryption key pair and certificate per domain, it
571  * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
572  *
573  * The potentially multiple valid decrypting key pairs are in turn
574  * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
575  *
576  */
577 static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
578                                             TALLOC_CTX *mem_ctx,
579                                             struct bkrp_BackupKey *r,
580                                             struct ldb_context *ldb_ctx)
581 {
582         struct bkrp_client_side_wrapped uncrypt_request;
583         DATA_BLOB blob;
584         enum ndr_err_code ndr_err;
585         char *guid_string;
586         char *cert_secret_name;
587         DATA_BLOB lsa_secret;
588         DATA_BLOB *uncrypted_data = NULL;
589         NTSTATUS status;
590         uint32_t requested_version;
591
592         blob.data = r->in.data_in;
593         blob.length = r->in.data_in_len;
594
595         if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
596                 return WERR_INVALID_PARAM;
597         }
598
599         /*
600          * We check for the version here, so we can actually print the
601          * message as we are unlikely to parse it with NDR.
602          */
603         requested_version = IVAL(r->in.data_in, 0);
604         if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
605             && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
606                 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
607                 return WERR_INVALID_PARAMETER;
608         }
609
610         ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
611                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
612         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
613                 return WERR_INVALID_PARAM;
614         }
615
616         if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
617             && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
618                 DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
619                 return WERR_INVALID_PARAMETER;
620         }
621
622         guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
623         if (guid_string == NULL) {
624                 return WERR_NOMEM;
625         }
626
627         cert_secret_name = talloc_asprintf(mem_ctx,
628                                            "BCKUPKEY_%s",
629                                            guid_string);
630         if (cert_secret_name == NULL) {
631                 return WERR_NOMEM;
632         }
633
634         status = get_lsa_secret(mem_ctx,
635                                 ldb_ctx,
636                                 cert_secret_name,
637                                 &lsa_secret);
638         if (!NT_STATUS_IS_OK(status)) {
639                 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
640                 return WERR_INVALID_DATA;
641         } else if (lsa_secret.length == 0) {
642                 /* we do not have the real secret attribute, like if we are an RODC */
643                 return WERR_INVALID_PARAMETER;
644         } else {
645                 hx509_context hctx;
646                 struct bkrp_exported_RSA_key_pair keypair;
647                 hx509_private_key pk;
648                 uint32_t i, res;
649                 heim_octet_string reversed_secret;
650                 heim_octet_string uncrypted_secret;
651                 AlgorithmIdentifier alg;
652                 DATA_BLOB blob_us;
653                 WERROR werr;
654
655                 ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
656                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
657                         DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
658                         return WERR_FILE_NOT_FOUND;
659                 }
660
661                 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
662                 if (!NT_STATUS_IS_OK(status)) {
663                         return WERR_INTERNAL_ERROR;
664                 }
665
666                 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
667                                                     uncrypt_request.encrypted_secret_len);
668                 if (reversed_secret.data == NULL) {
669                         hx509_private_key_free(&pk);
670                         return WERR_NOMEM;
671                 }
672
673                 /* The secret has to be reversed ... */
674                 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
675                         uint8_t *reversed = (uint8_t *)reversed_secret.data;
676                         uint8_t *uncrypt = uncrypt_request.encrypted_secret;
677                         reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
678                 }
679                 reversed_secret.length = uncrypt_request.encrypted_secret_len;
680
681                 /*
682                  * Let's try to decrypt the secret now that
683                  * we have the private key ...
684                  */
685                 hx509_context_init(&hctx);
686                 res = hx509_private_key_private_decrypt(hctx, &reversed_secret,
687                                                          &alg.algorithm, pk,
688                                                          &uncrypted_secret);
689                 hx509_context_free(&hctx);
690                 hx509_private_key_free(&pk);
691                 if (res != 0) {
692                         /* We are not able to decrypt the secret, looks like something is wrong */
693                         return WERR_INVALID_PARAMETER;
694                 }
695                 blob_us.data = uncrypted_secret.data;
696                 blob_us.length = uncrypted_secret.length;
697
698                 if (uncrypt_request.version == 2) {
699                         struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
700
701                         ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
702                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
703                         der_free_octet_string(&uncrypted_secret);
704                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
705                                 /* Unable to unmarshall */
706                                 return WERR_INVALID_DATA;
707                         }
708                         if (uncrypted_secretv2.magic != 0x20) {
709                                 /* wrong magic */
710                                 return WERR_INVALID_DATA;
711                         }
712
713                         werr = get_and_verify_access_check(mem_ctx, 2,
714                                                            uncrypted_secretv2.payload_key,
715                                                            uncrypt_request.access_check,
716                                                            uncrypt_request.access_check_len,
717                                                            dce_call->conn->auth_state.session_info);
718                         if (!W_ERROR_IS_OK(werr)) {
719                                 return werr;
720                         }
721                         uncrypted_data = talloc(mem_ctx, DATA_BLOB);
722                         if (uncrypted_data == NULL) {
723                                 return WERR_INVALID_DATA;
724                         }
725
726                         uncrypted_data->data = uncrypted_secretv2.secret;
727                         uncrypted_data->length = uncrypted_secretv2.secret_len;
728                 }
729                 if (uncrypt_request.version == 3) {
730                         struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
731
732                         ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
733                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
734
735                         der_free_octet_string(&uncrypted_secret);
736                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
737                                 /* Unable to unmarshall */
738                                 return WERR_INVALID_DATA;
739                         }
740
741                         if (uncrypted_secretv3.magic1 != 0x30  ||
742                             uncrypted_secretv3.magic2 != 0x6610 ||
743                             uncrypted_secretv3.magic3 != 0x800e) {
744                                 /* wrong magic */
745                                 return WERR_INVALID_DATA;
746                         }
747
748                         /*
749                          * Confirm that the caller is permitted to
750                          * read this particular data.  Because one key
751                          * pair is used per domain, the caller could
752                          * have stolen the profile data on-disk and
753                          * would otherwise be able to read the
754                          * passwords.
755                          */
756
757                         werr = get_and_verify_access_check(mem_ctx, 3,
758                                                            uncrypted_secretv3.payload_key,
759                                                            uncrypt_request.access_check,
760                                                            uncrypt_request.access_check_len,
761                                                            dce_call->conn->auth_state.session_info);
762                         if (!W_ERROR_IS_OK(werr)) {
763                                 return werr;
764                         }
765
766                         uncrypted_data = talloc(mem_ctx, DATA_BLOB);
767                         if (uncrypted_data == NULL) {
768                                 return WERR_INVALID_DATA;
769                         }
770
771                         uncrypted_data->data = uncrypted_secretv3.secret;
772                         uncrypted_data->length = uncrypted_secretv3.secret_len;
773                 }
774
775                 /*
776                  * Yeah if we are here all looks pretty good:
777                  * - hash is ok
778                  * - user sid is the same as the one in access check
779                  * - we were able to decrypt the whole stuff
780                  */
781         }
782
783         if (uncrypted_data->data == NULL) {
784                 return WERR_INVALID_DATA;
785         }
786
787         /* There is a magic value a the beginning of the data
788          * we can use an adhoc structure but as the
789          * parent structure is just an array of bytes it a lot of work
790          * work just prepending 4 bytes
791          */
792         *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
793         W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
794         memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
795         *(r->out.data_out_len) = uncrypted_data->length + 4;
796
797         return WERR_OK;
798 }
799
800 /*
801  * Strictly, this function no longer uses Heimdal in order to generate an RSA
802  * key, but GnuTLS.
803  *
804  * The resulting key is then imported into Heimdal's RSA structure.
805  *
806  * We use GnuTLS because it can reliably generate 2048 bit keys every time.
807  * Windows clients strictly require 2048, no more since it won't fit and no
808  * less either. Heimdal would almost always generate a smaller key.
809  */
810 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
811                                      hx509_private_key *pk, RSA **rsa)
812 {
813         int ret;
814         uint8_t *p0 = NULL;
815         const uint8_t *p;
816         size_t len;
817         int bits = 2048;
818         int RSA_returned_bits;
819         gnutls_x509_privkey_t gtls_key;
820         WERROR werr;
821
822         *rsa = NULL;
823
824         gnutls_global_init();
825 #if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
826         DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
827         gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
828 #endif
829         ret = gnutls_x509_privkey_init(&gtls_key);
830         if (ret != 0) {
831                 gnutls_global_deinit();
832                 return WERR_INTERNAL_ERROR;
833         }
834
835         /*
836          * Unlike Heimdal's RSA_generate_key_ex(), this generates a
837          * 2048 bit key 100% of the time.  The heimdal code had a ~1/8
838          * chance of doing so, chewing vast quantities of computation
839          * and entropy in the process.
840          */
841
842         ret = gnutls_x509_privkey_generate(gtls_key, GNUTLS_PK_RSA, bits, 0);
843         if (ret != 0) {
844                 werr = WERR_INTERNAL_ERROR;
845                 goto done;
846         }
847
848         /* No need to check error code, this SHOULD fail */
849         gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, NULL, &len);
850
851         if (len < 1) {
852                 werr = WERR_INTERNAL_ERROR;
853                 goto done;
854         }
855
856         p0 = talloc_size(ctx, len);
857         if (p0 == NULL) {
858                 werr = WERR_NOMEM;
859                 goto done;
860         }
861         p = p0;
862
863         /*
864          * Only this GnuTLS export function correctly exports the key,
865          * we can't use gnutls_rsa_params_export_raw() because while
866          * it appears to be fixed in more recent versions, in the
867          * Ubuntu 14.04 version 2.12.23 (at least) it incorrectly
868          * exports one of the key parameters (qInv).  Additionally, we
869          * would have to work around subtle differences in big number
870          * representations.
871          *
872          * We need access to the RSA parameters directly (in the
873          * parameter RSA **rsa) as the caller has to manually encode
874          * them in a non-standard data structure.
875          */
876         ret = gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, p0, &len);
877
878         if (ret != 0) {
879                 werr = WERR_INTERNAL_ERROR;
880                 goto done;
881         }
882
883         /*
884          * To dump the key we can use :
885          * rk_dumpdata("h5lkey", p0, len);
886          */
887         ret = hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
888                                        p0, len, HX509_KEY_FORMAT_DER, pk);
889
890         if (ret != 0) {
891                 werr = WERR_INTERNAL_ERROR;
892                 goto done;
893         }
894
895         *rsa = d2i_RSAPrivateKey(NULL, &p, len);
896         TALLOC_FREE(p0);
897
898         if (*rsa == NULL) {
899                 hx509_private_key_free(pk);
900                 werr = WERR_INTERNAL_ERROR;
901                 goto done;
902         }
903
904         RSA_returned_bits = BN_num_bits((*rsa)->n);
905         DEBUG(6, ("GnuTLS returned an RSA private key with %d bits\n", RSA_returned_bits));
906
907         if (RSA_returned_bits != bits) {
908                 DEBUG(0, ("GnuTLS unexpectedly returned an RSA private key with %d bits, needed %d\n", RSA_returned_bits, bits));
909                 hx509_private_key_free(pk);
910                 werr = WERR_INTERNAL_ERROR;
911                 goto done;
912         }
913
914         werr = WERR_OK;
915
916 done:
917         if (p0 != NULL) {
918                 memset(p0, 0, len);
919                 TALLOC_FREE(p0);
920         }
921
922         gnutls_x509_privkey_deinit(gtls_key);
923         gnutls_global_deinit();
924         return werr;
925 }
926
927 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
928                                 time_t lifetime, hx509_private_key *private_key,
929                                 hx509_cert *cert, DATA_BLOB *guidblob)
930 {
931         SubjectPublicKeyInfo spki;
932         hx509_name subject = NULL;
933         hx509_ca_tbs tbs;
934         struct heim_bit_string uniqueid;
935         struct heim_integer serialnumber;
936         int ret, i;
937
938         uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
939         if (uniqueid.data == NULL) {
940                 return WERR_NOMEM;
941         }
942         /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
943          * so as 1 byte is 8 bits we need to provision 8 times more space as in the
944          * blob
945          */
946         uniqueid.length = 8 * guidblob->length;
947
948         serialnumber.data = talloc_array(ctx, uint8_t,
949                                             guidblob->length);
950         if (serialnumber.data == NULL) {
951                 talloc_free(uniqueid.data);
952                 return WERR_NOMEM;
953         }
954
955         /* Native AD generates certificates with serialnumber in reversed notation */
956         for (i = 0; i < guidblob->length; i++) {
957                 uint8_t *reversed = (uint8_t *)serialnumber.data;
958                 uint8_t *uncrypt = guidblob->data;
959                 reversed[i] = uncrypt[guidblob->length - 1 - i];
960         }
961         serialnumber.length = guidblob->length;
962         serialnumber.negative = 0;
963
964         memset(&spki, 0, sizeof(spki));
965
966         ret = hx509_request_get_name(*hctx, *req, &subject);
967         if (ret !=0) {
968                 goto fail_subject;
969         }
970         ret = hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
971         if (ret !=0) {
972                 goto fail_spki;
973         }
974
975         ret = hx509_ca_tbs_init(*hctx, &tbs);
976         if (ret !=0) {
977                 goto fail_tbs;
978         }
979
980         ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
981         if (ret !=0) {
982                 goto fail;
983         }
984         ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
985         if (ret !=0) {
986                 goto fail;
987         }
988         ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
989         if (ret !=0) {
990                 goto fail;
991         }
992         ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
993         if (ret !=0) {
994                 goto fail;
995         }
996         ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
997         if (ret !=0) {
998                 goto fail;
999         }
1000         ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
1001         if (ret !=0) {
1002                 goto fail;
1003         }
1004         hx509_name_free(&subject);
1005         free_SubjectPublicKeyInfo(&spki);
1006         hx509_ca_tbs_free(&tbs);
1007
1008         return WERR_OK;
1009
1010 fail:
1011         hx509_ca_tbs_free(&tbs);
1012 fail_tbs:
1013         free_SubjectPublicKeyInfo(&spki);
1014 fail_spki:
1015         hx509_name_free(&subject);
1016 fail_subject:
1017         talloc_free(uniqueid.data);
1018         talloc_free(serialnumber.data);
1019         return WERR_INTERNAL_ERROR;
1020 }
1021
1022 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
1023                          hx509_private_key *signer,RSA **rsa, const char *dn)
1024 {
1025         int ret;
1026         SubjectPublicKeyInfo key;
1027
1028         hx509_name name;
1029         WERROR werr;
1030
1031         werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1032         if (!W_ERROR_IS_OK(werr)) {
1033                 return werr;
1034         }
1035
1036         hx509_request_init(*hctx, req);
1037         ret = hx509_parse_name(*hctx, dn, &name);
1038         if (ret != 0) {
1039                 RSA_free(*rsa);
1040                 hx509_private_key_free(signer);
1041                 hx509_request_free(req);
1042                 hx509_name_free(&name);
1043                 return WERR_INTERNAL_ERROR;
1044         }
1045
1046         ret = hx509_request_set_name(*hctx, *req, name);
1047         if (ret != 0) {
1048                 RSA_free(*rsa);
1049                 hx509_private_key_free(signer);
1050                 hx509_request_free(req);
1051                 hx509_name_free(&name);
1052                 return WERR_INTERNAL_ERROR;
1053         }
1054         hx509_name_free(&name);
1055
1056         ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1057         if (ret != 0) {
1058                 RSA_free(*rsa);
1059                 hx509_private_key_free(signer);
1060                 hx509_request_free(req);
1061                 return WERR_INTERNAL_ERROR;
1062         }
1063         ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1064         if (ret != 0) {
1065                 RSA_free(*rsa);
1066                 hx509_private_key_free(signer);
1067                 free_SubjectPublicKeyInfo(&key);
1068                 hx509_request_free(req);
1069                 return WERR_INTERNAL_ERROR;
1070         }
1071
1072         free_SubjectPublicKeyInfo(&key);
1073
1074         return WERR_OK;
1075 }
1076
1077 /* Return an error when we fail to generate a certificate */
1078 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1079 {
1080         heim_octet_string data;
1081         WERROR werr;
1082         RSA *rsa;
1083         hx509_context hctx;
1084         hx509_private_key pk;
1085         hx509_request req;
1086         hx509_cert cert;
1087         DATA_BLOB blob;
1088         DATA_BLOB blobkeypair;
1089         DATA_BLOB *tmp;
1090         int ret;
1091         bool ok = true;
1092         struct GUID guid = GUID_random();
1093         NTSTATUS status;
1094         char *secret_name;
1095         struct bkrp_exported_RSA_key_pair keypair;
1096         enum ndr_err_code ndr_err;
1097         uint32_t nb_seconds_validity = 3600 * 24 * 365;
1098
1099         DEBUG(6, ("Trying to generate a certificate\n"));
1100         hx509_context_init(&hctx);
1101         werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1102         if (!W_ERROR_IS_OK(werr)) {
1103                 hx509_context_free(&hctx);
1104                 return werr;
1105         }
1106
1107         status = GUID_to_ndr_blob(&guid, ctx, &blob);
1108         if (!NT_STATUS_IS_OK(status)) {
1109                 hx509_context_free(&hctx);
1110                 hx509_private_key_free(&pk);
1111                 RSA_free(rsa);
1112                 return WERR_INVALID_DATA;
1113         }
1114
1115         werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1116         if (!W_ERROR_IS_OK(werr)) {
1117                 hx509_private_key_free(&pk);
1118                 hx509_context_free(&hctx);
1119                 return WERR_INVALID_DATA;
1120         }
1121
1122         ret = hx509_cert_binary(hctx, cert, &data);
1123         if (ret !=0) {
1124                 hx509_cert_free(cert);
1125                 hx509_private_key_free(&pk);
1126                 hx509_context_free(&hctx);
1127                 return WERR_INVALID_DATA;
1128         }
1129
1130         keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1131         keypair.cert.length = data.length;
1132
1133         /*
1134          * Heimdal's bignum are big endian and the
1135          * structure expect it to be in little endian
1136          * so we reverse the buffer to make it work
1137          */
1138         tmp = reverse_and_get_blob(ctx, rsa->e);
1139         if (tmp == NULL) {
1140                 ok = false;
1141         } else {
1142                 keypair.public_exponent = *tmp;
1143                 SMB_ASSERT(tmp->length <= 4);
1144                 /*
1145                  * The value is now in little endian but if can happen that the length is
1146                  * less than 4 bytes.
1147                  * So if we have less than 4 bytes we pad with zeros so that it correctly
1148                  * fit into the structure.
1149                  */
1150                 if (tmp->length < 4) {
1151                         /*
1152                          * We need the expo to fit 4 bytes
1153                          */
1154                         keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1155                         memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1156                         keypair.public_exponent.length = 4;
1157                 }
1158         }
1159
1160         tmp = reverse_and_get_blob(ctx,rsa->d);
1161         if (tmp == NULL) {
1162                 ok = false;
1163         } else {
1164                 keypair.private_exponent = *tmp;
1165         }
1166
1167         tmp = reverse_and_get_blob(ctx,rsa->n);
1168         if (tmp == NULL) {
1169                 ok = false;
1170         } else {
1171                 keypair.modulus = *tmp;
1172         }
1173
1174         tmp = reverse_and_get_blob(ctx,rsa->p);
1175         if (tmp == NULL) {
1176                 ok = false;
1177         } else {
1178                 keypair.prime1 = *tmp;
1179         }
1180
1181         tmp = reverse_and_get_blob(ctx,rsa->q);
1182         if (tmp == NULL) {
1183                 ok = false;
1184         } else {
1185                 keypair.prime2 = *tmp;
1186         }
1187
1188         tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1189         if (tmp == NULL) {
1190                 ok = false;
1191         } else {
1192                 keypair.exponent1 = *tmp;
1193         }
1194
1195         tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1196         if (tmp == NULL) {
1197                 ok = false;
1198         } else {
1199                 keypair.exponent2 = *tmp;
1200         }
1201
1202         tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1203         if (tmp == NULL) {
1204                 ok = false;
1205         } else {
1206                 keypair.coefficient = *tmp;
1207         }
1208
1209         /* One of the keypair allocation was wrong */
1210         if (ok == false) {
1211                 der_free_octet_string(&data);
1212                 hx509_cert_free(cert);
1213                 hx509_private_key_free(&pk);
1214                 hx509_context_free(&hctx);
1215                 RSA_free(rsa);
1216                 return WERR_INVALID_DATA;
1217         }
1218         keypair.certificate_len = keypair.cert.length;
1219         ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1220         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1221                 der_free_octet_string(&data);
1222                 hx509_cert_free(cert);
1223                 hx509_private_key_free(&pk);
1224                 hx509_context_free(&hctx);
1225                 RSA_free(rsa);
1226                 return WERR_INVALID_DATA;
1227         }
1228
1229         secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1230         if (secret_name == NULL) {
1231                 der_free_octet_string(&data);
1232                 hx509_cert_free(cert);
1233                 hx509_private_key_free(&pk);
1234                 hx509_context_free(&hctx);
1235                 RSA_free(rsa);
1236                 return WERR_OUTOFMEMORY;
1237         }
1238
1239         status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1240         if (!NT_STATUS_IS_OK(status)) {
1241                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1242         }
1243         talloc_free(secret_name);
1244
1245         GUID_to_ndr_blob(&guid, ctx, &blob);
1246         status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1247         if (!NT_STATUS_IS_OK(status)) {
1248                 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1249         }
1250
1251         der_free_octet_string(&data);
1252         hx509_cert_free(cert);
1253         hx509_private_key_free(&pk);
1254         hx509_context_free(&hctx);
1255         RSA_free(rsa);
1256         return WERR_OK;
1257 }
1258
1259 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1260                                             struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1261 {
1262         struct GUID guid;
1263         char *guid_string;
1264         DATA_BLOB lsa_secret;
1265         enum ndr_err_code ndr_err;
1266         NTSTATUS status;
1267
1268         /*
1269          * here we basicaly need to return our certificate
1270          * search for lsa secret BCKUPKEY_PREFERRED first
1271          */
1272
1273         status = get_lsa_secret(mem_ctx,
1274                                 ldb_ctx,
1275                                 "BCKUPKEY_PREFERRED",
1276                                 &lsa_secret);
1277         if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1278                 /* Ok we can be in this case if there was no certs */
1279                 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1280                 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1281                                            lpcfg_realm(lp_ctx));
1282
1283                 WERROR werr =  generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1284                 if (!W_ERROR_IS_OK(werr)) {
1285                         return WERR_INVALID_PARAMETER;
1286                 }
1287                 status = get_lsa_secret(mem_ctx,
1288                                         ldb_ctx,
1289                                         "BCKUPKEY_PREFERRED",
1290                                         &lsa_secret);
1291
1292                 if (!NT_STATUS_IS_OK(status)) {
1293                         /* Ok we really don't manage to get this certs ...*/
1294                         DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1295                         return WERR_FILE_NOT_FOUND;
1296                 }
1297         } else if (!NT_STATUS_IS_OK(status)) {
1298                 return WERR_INTERNAL_ERROR;
1299         }
1300
1301         if (lsa_secret.length == 0) {
1302                 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1303                 return WERR_INTERNAL_ERROR;
1304         } else {
1305                 char *cert_secret_name;
1306
1307                 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1308                 if (!NT_STATUS_IS_OK(status)) {
1309                         return WERR_FILE_NOT_FOUND;
1310                 }
1311
1312                 guid_string = GUID_string(mem_ctx, &guid);
1313                 if (guid_string == NULL) {
1314                         /* We return file not found because the client
1315                          * expect this error
1316                          */
1317                         return WERR_FILE_NOT_FOUND;
1318                 }
1319
1320                 cert_secret_name = talloc_asprintf(mem_ctx,
1321                                                         "BCKUPKEY_%s",
1322                                                         guid_string);
1323                 status = get_lsa_secret(mem_ctx,
1324                                         ldb_ctx,
1325                                         cert_secret_name,
1326                                         &lsa_secret);
1327                 if (!NT_STATUS_IS_OK(status)) {
1328                         return WERR_FILE_NOT_FOUND;
1329                 }
1330
1331                 if (lsa_secret.length != 0) {
1332                         struct bkrp_exported_RSA_key_pair keypair;
1333                         ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1334                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1335                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1336                                 return WERR_FILE_NOT_FOUND;
1337                         }
1338                         *(r->out.data_out_len) = keypair.cert.length;
1339                         *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1340                         W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1341                         return WERR_OK;
1342                 } else {
1343                         DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1344                         return WERR_INTERNAL_ERROR;
1345                 }
1346         }
1347
1348         return WERR_NOT_SUPPORTED;
1349 }
1350
1351 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1352 {
1353         struct GUID guid = GUID_random();
1354         enum ndr_err_code ndr_err;
1355         DATA_BLOB blob_wrap_key, guid_blob;
1356         struct bkrp_dc_serverwrap_key wrap_key;
1357         NTSTATUS status;
1358         char *secret_name;
1359         TALLOC_CTX *frame = talloc_stackframe();
1360
1361         generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1362
1363         ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1364         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1365                 TALLOC_FREE(frame);
1366                 return WERR_INVALID_DATA;
1367         }
1368
1369         secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1370         if (secret_name == NULL) {
1371                 TALLOC_FREE(frame);
1372                 return WERR_NOMEM;
1373         }
1374
1375         status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1376         if (!NT_STATUS_IS_OK(status)) {
1377                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1378                 TALLOC_FREE(frame);
1379                 return WERR_INTERNAL_ERROR;
1380         }
1381
1382         status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1383         if (!NT_STATUS_IS_OK(status)) {
1384                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1385                 TALLOC_FREE(frame);
1386         }
1387
1388         status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1389         if (!NT_STATUS_IS_OK(status)) {
1390                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1391                 TALLOC_FREE(frame);
1392                 return WERR_INTERNAL_ERROR;
1393         }
1394
1395         TALLOC_FREE(frame);
1396
1397         return WERR_OK;
1398 }
1399
1400 /*
1401  * Find the specified decryption keys from the LSA secrets store as
1402  * G$BCKUPKEY_keyGuidString.
1403  */
1404
1405 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1406                                                struct bkrp_dc_serverwrap_key *server_key,
1407                                                struct GUID *guid)
1408 {
1409         NTSTATUS status;
1410         DATA_BLOB lsa_secret;
1411         char *secret_name;
1412         char *guid_string;
1413         enum ndr_err_code ndr_err;
1414
1415         guid_string = GUID_string(mem_ctx, guid);
1416         if (guid_string == NULL) {
1417                 /* We return file not found because the client
1418                  * expect this error
1419                  */
1420                 return WERR_FILE_NOT_FOUND;
1421         }
1422
1423         secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1424         if (secret_name == NULL) {
1425                 return WERR_NOMEM;
1426         }
1427
1428         status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1429         if (!NT_STATUS_IS_OK(status)) {
1430                 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1431                 return WERR_INVALID_DATA;
1432         }
1433         if (lsa_secret.length == 0) {
1434                 /* RODC case, we do not have secrets locally */
1435                 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1436                           secret_name));
1437                 return WERR_INTERNAL_ERROR;
1438         }
1439         ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1440                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1441         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1442                 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1443                 return WERR_INVALID_DATA;
1444         }
1445
1446         return WERR_OK;
1447 }
1448
1449 /*
1450  * Find the current, preferred ServerWrap Key by looking at
1451  * G$BCKUPKEY_P in the LSA secrets store.
1452  *
1453  * Then find the current decryption keys from the LSA secrets store as
1454  * G$BCKUPKEY_keyGuidString.
1455  */
1456
1457 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1458                                                        struct ldb_context *ldb_ctx,
1459                                                        struct bkrp_dc_serverwrap_key *server_key,
1460                                                        struct GUID *returned_guid)
1461 {
1462         NTSTATUS status;
1463         DATA_BLOB guid_binary;
1464
1465         status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1466         if (!NT_STATUS_IS_OK(status)) {
1467                 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1468                 return WERR_FILE_NOT_FOUND;
1469         } else if (guid_binary.length == 0) {
1470                 /* RODC case, we do not have secrets locally */
1471                 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1472                 return WERR_INTERNAL_ERROR;
1473         }
1474
1475         status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1476         if (!NT_STATUS_IS_OK(status)) {
1477                 return WERR_FILE_NOT_FOUND;
1478         }
1479
1480         return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1481                                                 server_key, returned_guid);
1482 }
1483
1484 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1485                                             struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1486 {
1487         WERROR werr;
1488         struct bkrp_server_side_wrapped decrypt_request;
1489         DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1490         DATA_BLOB blob;
1491         enum ndr_err_code ndr_err;
1492         struct bkrp_dc_serverwrap_key server_key;
1493         struct bkrp_rc4encryptedpayload rc4payload;
1494         struct dom_sid *caller_sid;
1495         uint8_t symkey[20]; /* SHA-1 hash len */
1496         uint8_t mackey[20]; /* SHA-1 hash len */
1497         uint8_t mac[20]; /* SHA-1 hash len */
1498         unsigned int hash_len;
1499         HMAC_CTX ctx;
1500
1501         blob.data = r->in.data_in;
1502         blob.length = r->in.data_in_len;
1503
1504         if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1505                 return WERR_INVALID_PARAM;
1506         }
1507
1508         ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1509                                            (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1510         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1511                 return WERR_INVALID_PARAM;
1512         }
1513
1514         if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1515                 return WERR_INVALID_PARAM;
1516         }
1517
1518         werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1519                                                 &decrypt_request.guid);
1520         if (!W_ERROR_IS_OK(werr)) {
1521                 return werr;
1522         }
1523
1524         dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1525
1526         dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1527
1528         /*
1529          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1530          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1531          */
1532         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1533              decrypt_request.r2, sizeof(decrypt_request.r2),
1534              symkey, &hash_len);
1535
1536         dump_data_pw("symkey: \n", symkey, hash_len);
1537
1538         /* rc4 decrypt sid and secret using sym key */
1539         symkey_blob = data_blob_const(symkey, sizeof(symkey));
1540
1541         encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1542                                          decrypt_request.ciphertext_length);
1543
1544         arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1545
1546         ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1547                                            (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1548         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1549                 return WERR_INVALID_PARAM;
1550         }
1551
1552         if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1553                 return WERR_INVALID_PARAM;
1554         }
1555
1556         dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1557
1558         /*
1559          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1560          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1561          */
1562         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1563              rc4payload.r3, sizeof(rc4payload.r3),
1564              mackey, &hash_len);
1565
1566         dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1567
1568         ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1569                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
1570         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1571                 return WERR_INTERNAL_ERROR;
1572         }
1573
1574         HMAC_CTX_init(&ctx);
1575         HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1576         /* SID field */
1577         HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1578         /* Secret field */
1579         HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1580         HMAC_Final(&ctx, mac, &hash_len);
1581         HMAC_CTX_cleanup(&ctx);
1582
1583         dump_data_pw("mac: \n", mac, sizeof(mac));
1584         dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1585
1586         if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1587                 return WERR_INVALID_ACCESS;
1588         }
1589
1590         caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1591
1592         if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1593                 return WERR_INVALID_ACCESS;
1594         }
1595
1596         *(r->out.data_out) = rc4payload.secret_data.data;
1597         *(r->out.data_out_len) = rc4payload.secret_data.length;
1598
1599         return WERR_OK;
1600 }
1601
1602 /*
1603  * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1604  * determine what type of restore is wanted.
1605  *
1606  * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1607  */
1608
1609 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1610                                         struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1611 {
1612         if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1613                 return WERR_INVALID_PARAM;
1614         }
1615
1616         if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1617                 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1618         }
1619
1620         return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1621 }
1622
1623 /*
1624  * We have some data, such as saved website or IMAP passwords that the
1625  * client would like to put into the profile on-disk.  This needs to
1626  * be encrypted.  This version gives the server the data over the
1627  * network (protected only by the negotiated transport encryption),
1628  * and asks that it be encrypted and returned for long-term storage.
1629  *
1630  * The data is NOT stored in the LSA, but a key to encrypt the data
1631  * will be stored.  There is only one active encryption key per domain,
1632  * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1633  *
1634  * The potentially multiple valid decryptiong keys (and the encryption
1635  * key) are in turn stored in the LSA secrets store as
1636  * G$BCKUPKEY_keyGuidString.
1637  *
1638  */
1639
1640 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1641                                             struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1642 {
1643         DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1644         WERROR werr;
1645         struct dom_sid *caller_sid;
1646         uint8_t symkey[20]; /* SHA-1 hash len */
1647         uint8_t mackey[20]; /* SHA-1 hash len */
1648         unsigned int hash_len;
1649         struct bkrp_rc4encryptedpayload rc4payload;
1650         HMAC_CTX ctx;
1651         struct bkrp_dc_serverwrap_key server_key;
1652         enum ndr_err_code ndr_err;
1653         struct bkrp_server_side_wrapped server_side_wrapped;
1654         struct GUID guid;
1655
1656         if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1657                 return WERR_INVALID_PARAM;
1658         }
1659
1660         werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1661                                                         ldb_ctx, &server_key,
1662                                                         &guid);
1663
1664         if (!W_ERROR_IS_OK(werr)) {
1665                 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1666                         /* Generate the server wrap key since one wasn't found */
1667                         werr =  generate_bkrp_server_wrap_key(mem_ctx,
1668                                                               ldb_ctx);
1669                         if (!W_ERROR_IS_OK(werr)) {
1670                                 return WERR_INVALID_PARAMETER;
1671                         }
1672                         werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1673                                                                         ldb_ctx,
1674                                                                         &server_key,
1675                                                                         &guid);
1676
1677                         if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1678                                 /* Ok we really don't manage to get this secret ...*/
1679                                 return WERR_FILE_NOT_FOUND;
1680                         }
1681                 } else {
1682                         /* In theory we should NEVER reach this point as it
1683                            should only appear in a rodc server */
1684                         /* we do not have the real secret attribute */
1685                         return WERR_INVALID_PARAMETER;
1686                 }
1687         }
1688
1689         caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1690
1691         dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1692
1693         /*
1694          * This is the key derivation step, so that the HMAC and RC4
1695          * operations over the user-supplied data are not able to
1696          * disclose the master key.  By using random data, the symkey
1697          * and mackey values are unique for this operation, and
1698          * discovering these (by reversing the RC4 over the
1699          * attacker-controlled data) does not return something able to
1700          * be used to decyrpt the encrypted data of other users
1701          */
1702         generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1703
1704         dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1705
1706         generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1707
1708         dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1709
1710
1711         /*
1712          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1713          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1714          */
1715         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1716              server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1717              symkey, &hash_len);
1718
1719         dump_data_pw("symkey: \n", symkey, hash_len);
1720
1721         /*
1722          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1723          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1724          */
1725         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1726              rc4payload.r3, sizeof(rc4payload.r3),
1727              mackey, &hash_len);
1728
1729         dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1730
1731         ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1732                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
1733         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1734                 return WERR_INTERNAL_ERROR;
1735         }
1736
1737         rc4payload.secret_data.data = r->in.data_in;
1738         rc4payload.secret_data.length = r->in.data_in_len;
1739
1740         HMAC_CTX_init(&ctx);
1741         HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1742         /* SID field */
1743         HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1744         /* Secret field */
1745         HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1746         HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1747         HMAC_CTX_cleanup(&ctx);
1748
1749         dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1750
1751         rc4payload.sid = *caller_sid;
1752
1753         ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1754                                        (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1755         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1756                 return WERR_INTERNAL_ERROR;
1757         }
1758
1759         /* rc4 encrypt sid and secret using sym key */
1760         symkey_blob = data_blob_const(symkey, sizeof(symkey));
1761         arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1762
1763         /* create server wrap structure */
1764
1765         server_side_wrapped.payload_length = rc4payload.secret_data.length;
1766         server_side_wrapped.ciphertext_length = encrypted_blob.length;
1767         server_side_wrapped.guid = guid;
1768         server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1769
1770         ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1771                                        (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1772         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1773                 return WERR_INTERNAL_ERROR;
1774         }
1775
1776         *(r->out.data_out) = server_wrapped_blob.data;
1777         *(r->out.data_out_len) = server_wrapped_blob.length;
1778
1779         return WERR_OK;
1780 }
1781
1782 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1783                                     TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1784 {
1785         WERROR error = WERR_INVALID_PARAM;
1786         struct ldb_context *ldb_ctx;
1787         bool is_rodc;
1788         const char *addr = "unknown";
1789         /* At which level we start to add more debug of what is done in the protocol */
1790         const int debuglevel = 4;
1791
1792         if (DEBUGLVL(debuglevel)) {
1793                 const struct tsocket_address *remote_address;
1794                 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1795                 if (tsocket_address_is_inet(remote_address, "ip")) {
1796                         addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1797                         W_ERROR_HAVE_NO_MEMORY(addr);
1798                 }
1799         }
1800
1801         if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1802                 return WERR_NOT_SUPPORTED;
1803         }
1804
1805         if (!dce_call->conn->auth_state.auth_info ||
1806                 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1807                 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1808         }
1809
1810         ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1811                                 dce_call->conn->dce_ctx->lp_ctx,
1812                                 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1813
1814         if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1815                 talloc_unlink(mem_ctx, ldb_ctx);
1816                 return WERR_INVALID_PARAM;
1817         }
1818
1819         if (!is_rodc) {
1820                 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1821                         BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1822                         DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1823                         error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1824                 }
1825
1826                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1827                         BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1828                         DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1829                         error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1830                 }
1831
1832                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1833                         BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1834                         DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1835                         error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1836                 }
1837
1838                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1839                         BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1840                         DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1841                         error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1842                 }
1843         }
1844         /*else: I am a RODC so I don't handle backup key protocol */
1845
1846         talloc_unlink(mem_ctx, ldb_ctx);
1847         return error;
1848 }
1849
1850 /* include the generated boilerplate */
1851 #include "librpc/gen_ndr/ndr_backupkey_s.c"