backupkey: Fix CID 1338078 (RESOURCE_LEAK)
[samba.git] / source4 / rpc_server / backupkey / dcesrv_backupkey.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 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_ca(*hctx, tbs, 1);
989         if (ret !=0) {
990                 goto fail;
991         }
992         ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
993         if (ret !=0) {
994                 goto fail;
995         }
996         ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
997         if (ret !=0) {
998                 goto fail;
999         }
1000         ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
1001         if (ret !=0) {
1002                 goto fail;
1003         }
1004         ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
1005         if (ret !=0) {
1006                 goto fail;
1007         }
1008         hx509_name_free(&subject);
1009         free_SubjectPublicKeyInfo(&spki);
1010         hx509_ca_tbs_free(&tbs);
1011
1012         return WERR_OK;
1013
1014 fail:
1015         hx509_ca_tbs_free(&tbs);
1016 fail_tbs:
1017         free_SubjectPublicKeyInfo(&spki);
1018 fail_spki:
1019         hx509_name_free(&subject);
1020 fail_subject:
1021         talloc_free(uniqueid.data);
1022         talloc_free(serialnumber.data);
1023         return WERR_INTERNAL_ERROR;
1024 }
1025
1026 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
1027                          hx509_private_key *signer,RSA **rsa, const char *dn)
1028 {
1029         int ret;
1030         SubjectPublicKeyInfo key;
1031
1032         hx509_name name;
1033         WERROR werr;
1034
1035         werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
1036         if (!W_ERROR_IS_OK(werr)) {
1037                 return werr;
1038         }
1039
1040         hx509_request_init(*hctx, req);
1041         ret = hx509_parse_name(*hctx, dn, &name);
1042         if (ret != 0) {
1043                 RSA_free(*rsa);
1044                 hx509_private_key_free(signer);
1045                 hx509_request_free(req);
1046                 hx509_name_free(&name);
1047                 return WERR_INTERNAL_ERROR;
1048         }
1049
1050         ret = hx509_request_set_name(*hctx, *req, name);
1051         if (ret != 0) {
1052                 RSA_free(*rsa);
1053                 hx509_private_key_free(signer);
1054                 hx509_request_free(req);
1055                 hx509_name_free(&name);
1056                 return WERR_INTERNAL_ERROR;
1057         }
1058         hx509_name_free(&name);
1059
1060         ret = hx509_private_key2SPKI(*hctx, *signer, &key);
1061         if (ret != 0) {
1062                 RSA_free(*rsa);
1063                 hx509_private_key_free(signer);
1064                 hx509_request_free(req);
1065                 return WERR_INTERNAL_ERROR;
1066         }
1067         ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
1068         if (ret != 0) {
1069                 RSA_free(*rsa);
1070                 hx509_private_key_free(signer);
1071                 free_SubjectPublicKeyInfo(&key);
1072                 hx509_request_free(req);
1073                 return WERR_INTERNAL_ERROR;
1074         }
1075
1076         free_SubjectPublicKeyInfo(&key);
1077
1078         return WERR_OK;
1079 }
1080
1081 /* Return an error when we fail to generate a certificate */
1082 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
1083 {
1084         heim_octet_string data;
1085         WERROR werr;
1086         RSA *rsa;
1087         hx509_context hctx;
1088         hx509_private_key pk;
1089         hx509_request req;
1090         hx509_cert cert;
1091         DATA_BLOB blob;
1092         DATA_BLOB blobkeypair;
1093         DATA_BLOB *tmp;
1094         int ret;
1095         bool ok = true;
1096         struct GUID guid = GUID_random();
1097         NTSTATUS status;
1098         char *secret_name;
1099         struct bkrp_exported_RSA_key_pair keypair;
1100         enum ndr_err_code ndr_err;
1101         uint32_t nb_seconds_validity = 3600 * 24 * 365;
1102
1103         DEBUG(6, ("Trying to generate a certificate\n"));
1104         hx509_context_init(&hctx);
1105         werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
1106         if (!W_ERROR_IS_OK(werr)) {
1107                 hx509_context_free(&hctx);
1108                 return werr;
1109         }
1110
1111         status = GUID_to_ndr_blob(&guid, ctx, &blob);
1112         if (!NT_STATUS_IS_OK(status)) {
1113                 hx509_context_free(&hctx);
1114                 hx509_private_key_free(&pk);
1115                 RSA_free(rsa);
1116                 return WERR_INVALID_DATA;
1117         }
1118
1119         werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
1120         if (!W_ERROR_IS_OK(werr)) {
1121                 hx509_private_key_free(&pk);
1122                 hx509_context_free(&hctx);
1123                 return WERR_INVALID_DATA;
1124         }
1125
1126         ret = hx509_cert_binary(hctx, cert, &data);
1127         if (ret !=0) {
1128                 hx509_cert_free(cert);
1129                 hx509_private_key_free(&pk);
1130                 hx509_context_free(&hctx);
1131                 return WERR_INVALID_DATA;
1132         }
1133
1134         keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1135         keypair.cert.length = data.length;
1136
1137         /*
1138          * Heimdal's bignum are big endian and the
1139          * structure expect it to be in little endian
1140          * so we reverse the buffer to make it work
1141          */
1142         tmp = reverse_and_get_blob(ctx, rsa->e);
1143         if (tmp == NULL) {
1144                 ok = false;
1145         } else {
1146                 keypair.public_exponent = *tmp;
1147                 SMB_ASSERT(tmp->length <= 4);
1148                 /*
1149                  * The value is now in little endian but if can happen that the length is
1150                  * less than 4 bytes.
1151                  * So if we have less than 4 bytes we pad with zeros so that it correctly
1152                  * fit into the structure.
1153                  */
1154                 if (tmp->length < 4) {
1155                         /*
1156                          * We need the expo to fit 4 bytes
1157                          */
1158                         keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1159                         memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1160                         keypair.public_exponent.length = 4;
1161                 }
1162         }
1163
1164         tmp = reverse_and_get_blob(ctx,rsa->d);
1165         if (tmp == NULL) {
1166                 ok = false;
1167         } else {
1168                 keypair.private_exponent = *tmp;
1169         }
1170
1171         tmp = reverse_and_get_blob(ctx,rsa->n);
1172         if (tmp == NULL) {
1173                 ok = false;
1174         } else {
1175                 keypair.modulus = *tmp;
1176         }
1177
1178         tmp = reverse_and_get_blob(ctx,rsa->p);
1179         if (tmp == NULL) {
1180                 ok = false;
1181         } else {
1182                 keypair.prime1 = *tmp;
1183         }
1184
1185         tmp = reverse_and_get_blob(ctx,rsa->q);
1186         if (tmp == NULL) {
1187                 ok = false;
1188         } else {
1189                 keypair.prime2 = *tmp;
1190         }
1191
1192         tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1193         if (tmp == NULL) {
1194                 ok = false;
1195         } else {
1196                 keypair.exponent1 = *tmp;
1197         }
1198
1199         tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1200         if (tmp == NULL) {
1201                 ok = false;
1202         } else {
1203                 keypair.exponent2 = *tmp;
1204         }
1205
1206         tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1207         if (tmp == NULL) {
1208                 ok = false;
1209         } else {
1210                 keypair.coefficient = *tmp;
1211         }
1212
1213         /* One of the keypair allocation was wrong */
1214         if (ok == false) {
1215                 der_free_octet_string(&data);
1216                 hx509_cert_free(cert);
1217                 hx509_private_key_free(&pk);
1218                 hx509_context_free(&hctx);
1219                 RSA_free(rsa);
1220                 return WERR_INVALID_DATA;
1221         }
1222         keypair.certificate_len = keypair.cert.length;
1223         ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1224         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1225                 der_free_octet_string(&data);
1226                 hx509_cert_free(cert);
1227                 hx509_private_key_free(&pk);
1228                 hx509_context_free(&hctx);
1229                 RSA_free(rsa);
1230                 return WERR_INVALID_DATA;
1231         }
1232
1233         secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1234         if (secret_name == NULL) {
1235                 der_free_octet_string(&data);
1236                 hx509_cert_free(cert);
1237                 hx509_private_key_free(&pk);
1238                 hx509_context_free(&hctx);
1239                 RSA_free(rsa);
1240                 return WERR_OUTOFMEMORY;
1241         }
1242
1243         status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1244         if (!NT_STATUS_IS_OK(status)) {
1245                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1246         }
1247         talloc_free(secret_name);
1248
1249         GUID_to_ndr_blob(&guid, ctx, &blob);
1250         status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1251         if (!NT_STATUS_IS_OK(status)) {
1252                 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1253         }
1254
1255         der_free_octet_string(&data);
1256         hx509_cert_free(cert);
1257         hx509_private_key_free(&pk);
1258         hx509_context_free(&hctx);
1259         RSA_free(rsa);
1260         return WERR_OK;
1261 }
1262
1263 static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1264                                             struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1265 {
1266         struct GUID guid;
1267         char *guid_string;
1268         DATA_BLOB lsa_secret;
1269         enum ndr_err_code ndr_err;
1270         NTSTATUS status;
1271
1272         /*
1273          * here we basicaly need to return our certificate
1274          * search for lsa secret BCKUPKEY_PREFERRED first
1275          */
1276
1277         status = get_lsa_secret(mem_ctx,
1278                                 ldb_ctx,
1279                                 "BCKUPKEY_PREFERRED",
1280                                 &lsa_secret);
1281         if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
1282                 /* Ok we can be in this case if there was no certs */
1283                 struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1284                 char *dn = talloc_asprintf(mem_ctx, "CN=%s",
1285                                            lpcfg_realm(lp_ctx));
1286
1287                 WERROR werr =  generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1288                 if (!W_ERROR_IS_OK(werr)) {
1289                         return WERR_INVALID_PARAMETER;
1290                 }
1291                 status = get_lsa_secret(mem_ctx,
1292                                         ldb_ctx,
1293                                         "BCKUPKEY_PREFERRED",
1294                                         &lsa_secret);
1295
1296                 if (!NT_STATUS_IS_OK(status)) {
1297                         /* Ok we really don't manage to get this certs ...*/
1298                         DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1299                         return WERR_FILE_NOT_FOUND;
1300                 }
1301         } else if (!NT_STATUS_IS_OK(status)) {
1302                 return WERR_INTERNAL_ERROR;
1303         }
1304
1305         if (lsa_secret.length == 0) {
1306                 DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
1307                 return WERR_INTERNAL_ERROR;
1308         } else {
1309                 char *cert_secret_name;
1310
1311                 status = GUID_from_ndr_blob(&lsa_secret, &guid);
1312                 if (!NT_STATUS_IS_OK(status)) {
1313                         return WERR_FILE_NOT_FOUND;
1314                 }
1315
1316                 guid_string = GUID_string(mem_ctx, &guid);
1317                 if (guid_string == NULL) {
1318                         /* We return file not found because the client
1319                          * expect this error
1320                          */
1321                         return WERR_FILE_NOT_FOUND;
1322                 }
1323
1324                 cert_secret_name = talloc_asprintf(mem_ctx,
1325                                                         "BCKUPKEY_%s",
1326                                                         guid_string);
1327                 status = get_lsa_secret(mem_ctx,
1328                                         ldb_ctx,
1329                                         cert_secret_name,
1330                                         &lsa_secret);
1331                 if (!NT_STATUS_IS_OK(status)) {
1332                         return WERR_FILE_NOT_FOUND;
1333                 }
1334
1335                 if (lsa_secret.length != 0) {
1336                         struct bkrp_exported_RSA_key_pair keypair;
1337                         ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
1338                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1339                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1340                                 return WERR_FILE_NOT_FOUND;
1341                         }
1342                         *(r->out.data_out_len) = keypair.cert.length;
1343                         *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1344                         W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1345                         return WERR_OK;
1346                 } else {
1347                         DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
1348                         return WERR_INTERNAL_ERROR;
1349                 }
1350         }
1351
1352         return WERR_NOT_SUPPORTED;
1353 }
1354
1355 static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
1356 {
1357         struct GUID guid = GUID_random();
1358         enum ndr_err_code ndr_err;
1359         DATA_BLOB blob_wrap_key, guid_blob;
1360         struct bkrp_dc_serverwrap_key wrap_key;
1361         NTSTATUS status;
1362         char *secret_name;
1363         TALLOC_CTX *frame = talloc_stackframe();
1364
1365         generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
1366
1367         ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
1368         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1369                 TALLOC_FREE(frame);
1370                 return WERR_INVALID_DATA;
1371         }
1372
1373         secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1374         if (secret_name == NULL) {
1375                 TALLOC_FREE(frame);
1376                 return WERR_NOMEM;
1377         }
1378
1379         status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
1380         if (!NT_STATUS_IS_OK(status)) {
1381                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1382                 TALLOC_FREE(frame);
1383                 return WERR_INTERNAL_ERROR;
1384         }
1385
1386         status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
1387         if (!NT_STATUS_IS_OK(status)) {
1388                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1389                 TALLOC_FREE(frame);
1390         }
1391
1392         status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
1393         if (!NT_STATUS_IS_OK(status)) {
1394                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1395                 TALLOC_FREE(frame);
1396                 return WERR_INTERNAL_ERROR;
1397         }
1398
1399         TALLOC_FREE(frame);
1400
1401         return WERR_OK;
1402 }
1403
1404 /*
1405  * Find the specified decryption keys from the LSA secrets store as
1406  * G$BCKUPKEY_keyGuidString.
1407  */
1408
1409 static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
1410                                                struct bkrp_dc_serverwrap_key *server_key,
1411                                                struct GUID *guid)
1412 {
1413         NTSTATUS status;
1414         DATA_BLOB lsa_secret;
1415         char *secret_name;
1416         char *guid_string;
1417         enum ndr_err_code ndr_err;
1418
1419         guid_string = GUID_string(mem_ctx, guid);
1420         if (guid_string == NULL) {
1421                 /* We return file not found because the client
1422                  * expect this error
1423                  */
1424                 return WERR_FILE_NOT_FOUND;
1425         }
1426
1427         secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
1428         if (secret_name == NULL) {
1429                 return WERR_NOMEM;
1430         }
1431
1432         status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
1433         if (!NT_STATUS_IS_OK(status)) {
1434                 DEBUG(10, ("Error while fetching secret %s\n", secret_name));
1435                 return WERR_INVALID_DATA;
1436         }
1437         if (lsa_secret.length == 0) {
1438                 /* RODC case, we do not have secrets locally */
1439                 DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
1440                           secret_name));
1441                 return WERR_INTERNAL_ERROR;
1442         }
1443         ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
1444                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
1445         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1446                 DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
1447                 return WERR_INVALID_DATA;
1448         }
1449
1450         return WERR_OK;
1451 }
1452
1453 /*
1454  * Find the current, preferred ServerWrap Key by looking at
1455  * G$BCKUPKEY_P in the LSA secrets store.
1456  *
1457  * Then find the current decryption keys from the LSA secrets store as
1458  * G$BCKUPKEY_keyGuidString.
1459  */
1460
1461 static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
1462                                                        struct ldb_context *ldb_ctx,
1463                                                        struct bkrp_dc_serverwrap_key *server_key,
1464                                                        struct GUID *returned_guid)
1465 {
1466         NTSTATUS status;
1467         DATA_BLOB guid_binary;
1468
1469         status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
1470         if (!NT_STATUS_IS_OK(status)) {
1471                 DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
1472                 return WERR_FILE_NOT_FOUND;
1473         } else if (guid_binary.length == 0) {
1474                 /* RODC case, we do not have secrets locally */
1475                 DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
1476                 return WERR_INTERNAL_ERROR;
1477         }
1478
1479         status = GUID_from_ndr_blob(&guid_binary, returned_guid);
1480         if (!NT_STATUS_IS_OK(status)) {
1481                 return WERR_FILE_NOT_FOUND;
1482         }
1483
1484         return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
1485                                                 server_key, returned_guid);
1486 }
1487
1488 static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1489                                             struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1490 {
1491         WERROR werr;
1492         struct bkrp_server_side_wrapped decrypt_request;
1493         DATA_BLOB sid_blob, encrypted_blob, symkey_blob;
1494         DATA_BLOB blob;
1495         enum ndr_err_code ndr_err;
1496         struct bkrp_dc_serverwrap_key server_key;
1497         struct bkrp_rc4encryptedpayload rc4payload;
1498         struct dom_sid *caller_sid;
1499         uint8_t symkey[20]; /* SHA-1 hash len */
1500         uint8_t mackey[20]; /* SHA-1 hash len */
1501         uint8_t mac[20]; /* SHA-1 hash len */
1502         unsigned int hash_len;
1503         HMAC_CTX ctx;
1504
1505         blob.data = r->in.data_in;
1506         blob.length = r->in.data_in_len;
1507
1508         if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1509                 return WERR_INVALID_PARAM;
1510         }
1511
1512         ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
1513                                            (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
1514         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1515                 return WERR_INVALID_PARAM;
1516         }
1517
1518         if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
1519                 return WERR_INVALID_PARAM;
1520         }
1521
1522         werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
1523                                                 &decrypt_request.guid);
1524         if (!W_ERROR_IS_OK(werr)) {
1525                 return werr;
1526         }
1527
1528         dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1529
1530         dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
1531
1532         /*
1533          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1534          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1535          */
1536         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1537              decrypt_request.r2, sizeof(decrypt_request.r2),
1538              symkey, &hash_len);
1539
1540         dump_data_pw("symkey: \n", symkey, hash_len);
1541
1542         /* rc4 decrypt sid and secret using sym key */
1543         symkey_blob = data_blob_const(symkey, sizeof(symkey));
1544
1545         encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
1546                                          decrypt_request.ciphertext_length);
1547
1548         arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1549
1550         ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
1551                                            (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
1552         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1553                 return WERR_INVALID_PARAM;
1554         }
1555
1556         if (decrypt_request.payload_length != rc4payload.secret_data.length) {
1557                 return WERR_INVALID_PARAM;
1558         }
1559
1560         dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1561
1562         /*
1563          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1564          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1565          */
1566         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1567              rc4payload.r3, sizeof(rc4payload.r3),
1568              mackey, &hash_len);
1569
1570         dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1571
1572         ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
1573                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
1574         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1575                 return WERR_INTERNAL_ERROR;
1576         }
1577
1578         HMAC_CTX_init(&ctx);
1579         HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
1580         /* SID field */
1581         HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1582         /* Secret field */
1583         HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1584         HMAC_Final(&ctx, mac, &hash_len);
1585         HMAC_CTX_cleanup(&ctx);
1586
1587         dump_data_pw("mac: \n", mac, sizeof(mac));
1588         dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1589
1590         if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
1591                 return WERR_INVALID_ACCESS;
1592         }
1593
1594         caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1595
1596         if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
1597                 return WERR_INVALID_ACCESS;
1598         }
1599
1600         *(r->out.data_out) = rc4payload.secret_data.data;
1601         *(r->out.data_out_len) = rc4payload.secret_data.length;
1602
1603         return WERR_OK;
1604 }
1605
1606 /*
1607  * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
1608  * determine what type of restore is wanted.
1609  *
1610  * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
1611  */
1612
1613 static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1614                                         struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
1615 {
1616         if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
1617                 return WERR_INVALID_PARAM;
1618         }
1619
1620         if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
1621                 return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1622         }
1623
1624         return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1625 }
1626
1627 /*
1628  * We have some data, such as saved website or IMAP passwords that the
1629  * client would like to put into the profile on-disk.  This needs to
1630  * be encrypted.  This version gives the server the data over the
1631  * network (protected only by the negotiated transport encryption),
1632  * and asks that it be encrypted and returned for long-term storage.
1633  *
1634  * The data is NOT stored in the LSA, but a key to encrypt the data
1635  * will be stored.  There is only one active encryption key per domain,
1636  * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
1637  *
1638  * The potentially multiple valid decryptiong keys (and the encryption
1639  * key) are in turn stored in the LSA secrets store as
1640  * G$BCKUPKEY_keyGuidString.
1641  *
1642  */
1643
1644 static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1645                                             struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1646 {
1647         DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
1648         WERROR werr;
1649         struct dom_sid *caller_sid;
1650         uint8_t symkey[20]; /* SHA-1 hash len */
1651         uint8_t mackey[20]; /* SHA-1 hash len */
1652         unsigned int hash_len;
1653         struct bkrp_rc4encryptedpayload rc4payload;
1654         HMAC_CTX ctx;
1655         struct bkrp_dc_serverwrap_key server_key;
1656         enum ndr_err_code ndr_err;
1657         struct bkrp_server_side_wrapped server_side_wrapped;
1658         struct GUID guid;
1659
1660         if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
1661                 return WERR_INVALID_PARAM;
1662         }
1663
1664         werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1665                                                         ldb_ctx, &server_key,
1666                                                         &guid);
1667
1668         if (!W_ERROR_IS_OK(werr)) {
1669                 if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1670                         /* Generate the server wrap key since one wasn't found */
1671                         werr =  generate_bkrp_server_wrap_key(mem_ctx,
1672                                                               ldb_ctx);
1673                         if (!W_ERROR_IS_OK(werr)) {
1674                                 return WERR_INVALID_PARAMETER;
1675                         }
1676                         werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
1677                                                                         ldb_ctx,
1678                                                                         &server_key,
1679                                                                         &guid);
1680
1681                         if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
1682                                 /* Ok we really don't manage to get this secret ...*/
1683                                 return WERR_FILE_NOT_FOUND;
1684                         }
1685                 } else {
1686                         /* In theory we should NEVER reach this point as it
1687                            should only appear in a rodc server */
1688                         /* we do not have the real secret attribute */
1689                         return WERR_INVALID_PARAMETER;
1690                 }
1691         }
1692
1693         caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1694
1695         dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
1696
1697         /*
1698          * This is the key derivation step, so that the HMAC and RC4
1699          * operations over the user-supplied data are not able to
1700          * disclose the master key.  By using random data, the symkey
1701          * and mackey values are unique for this operation, and
1702          * discovering these (by reversing the RC4 over the
1703          * attacker-controlled data) does not return something able to
1704          * be used to decyrpt the encrypted data of other users
1705          */
1706         generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1707
1708         dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
1709
1710         generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
1711
1712         dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
1713
1714
1715         /*
1716          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1717          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1718          */
1719         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1720              server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
1721              symkey, &hash_len);
1722
1723         dump_data_pw("symkey: \n", symkey, hash_len);
1724
1725         /*
1726          * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
1727          * BACKUPKEY_BACKUP_GUID, it really is the whole key
1728          */
1729         HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
1730              rc4payload.r3, sizeof(rc4payload.r3),
1731              mackey, &hash_len);
1732
1733         dump_data_pw("mackey: \n", mackey, sizeof(mackey));
1734
1735         ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
1736                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
1737         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1738                 return WERR_INTERNAL_ERROR;
1739         }
1740
1741         rc4payload.secret_data.data = r->in.data_in;
1742         rc4payload.secret_data.length = r->in.data_in_len;
1743
1744         HMAC_CTX_init(&ctx);
1745         HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
1746         /* SID field */
1747         HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
1748         /* Secret field */
1749         HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
1750         HMAC_Final(&ctx, rc4payload.mac, &hash_len);
1751         HMAC_CTX_cleanup(&ctx);
1752
1753         dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
1754
1755         rc4payload.sid = *caller_sid;
1756
1757         ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
1758                                        (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
1759         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1760                 return WERR_INTERNAL_ERROR;
1761         }
1762
1763         /* rc4 encrypt sid and secret using sym key */
1764         symkey_blob = data_blob_const(symkey, sizeof(symkey));
1765         arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
1766
1767         /* create server wrap structure */
1768
1769         server_side_wrapped.payload_length = rc4payload.secret_data.length;
1770         server_side_wrapped.ciphertext_length = encrypted_blob.length;
1771         server_side_wrapped.guid = guid;
1772         server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
1773
1774         ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
1775                                        (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
1776         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1777                 return WERR_INTERNAL_ERROR;
1778         }
1779
1780         *(r->out.data_out) = server_wrapped_blob.data;
1781         *(r->out.data_out_len) = server_wrapped_blob.length;
1782
1783         return WERR_OK;
1784 }
1785
1786 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1787                                     TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1788 {
1789         WERROR error = WERR_INVALID_PARAM;
1790         struct ldb_context *ldb_ctx;
1791         bool is_rodc;
1792         const char *addr = "unknown";
1793         /* At which level we start to add more debug of what is done in the protocol */
1794         const int debuglevel = 4;
1795
1796         if (DEBUGLVL(debuglevel)) {
1797                 const struct tsocket_address *remote_address;
1798                 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1799                 if (tsocket_address_is_inet(remote_address, "ip")) {
1800                         addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1801                         W_ERROR_HAVE_NO_MEMORY(addr);
1802                 }
1803         }
1804
1805         if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC) {
1806                 return WERR_NOT_SUPPORTED;
1807         }
1808
1809         if (!dce_call->conn->auth_state.auth_info ||
1810                 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1811                 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1812         }
1813
1814         ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1815                                 dce_call->conn->dce_ctx->lp_ctx,
1816                                 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1817
1818         if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1819                 talloc_unlink(mem_ctx, ldb_ctx);
1820                 return WERR_INVALID_PARAM;
1821         }
1822
1823         if (!is_rodc) {
1824                 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1825                         BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1826                         DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
1827                         error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1828                 }
1829
1830                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1831                         BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1832                         DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1833                         error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1834                 }
1835
1836                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1837                         BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
1838                         DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
1839                         error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1840                 }
1841
1842                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1843                         BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
1844                         DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
1845                         error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
1846                 }
1847         }
1848         /*else: I am a RODC so I don't handle backup key protocol */
1849
1850         talloc_unlink(mem_ctx, ldb_ctx);
1851         return error;
1852 }
1853
1854 /* include the generated boilerplate */
1855 #include "librpc/gen_ndr/ndr_backupkey_s.c"