s4:remove many invocations of "samdb_msg_add_string"
[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 "heimdal/lib/hx509/hx_locl.h"
32 #include "heimdal/lib/hcrypto/rsa.h"
33 #include "heimdal/lib/hcrypto/bn.h"
34 #include "../lib/tsocket/tsocket.h"
35 #include "../libcli/security/security.h"
36
37 #define BACKUPKEY_MIN_VERSION 2
38 #define BACKUPKEY_MAX_VERSION 3
39
40 static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
41 /* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
42 static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
43         { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
44 };
45
46 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
47                                struct ldb_context *ldb,
48                                const char *name,
49                                const DATA_BLOB *secret)
50 {
51         struct ldb_message *msg;
52         struct ldb_result *res;
53         struct ldb_dn *domain_dn;
54         struct ldb_dn *system_dn;
55         struct ldb_val val;
56         int ret;
57         char *name2;
58         struct timeval now = timeval_current();
59         NTTIME nt_now = timeval_to_nttime(&now);
60         const char *attrs[] = {
61                 NULL
62         };
63
64         domain_dn = ldb_get_default_basedn(ldb);
65         if (!domain_dn) {
66                 return NT_STATUS_INTERNAL_ERROR;
67         }
68
69         msg = ldb_msg_new(mem_ctx);
70         if (msg == NULL) {
71                 return NT_STATUS_NO_MEMORY;
72         }
73
74         /*
75          * This function is a lot like dcesrv_lsa_CreateSecret
76          * in the rpc_server/lsa directory
77          * The reason why we duplicate the effort here is that:
78          * * we want to keep the former function static
79          * * we want to avoid the burden of doing LSA calls
80          *   when we can just manipulate the secrets directly
81          * * taillor the function to the particular needs of backup protocol
82          */
83
84         system_dn = samdb_search_dn(ldb, msg, domain_dn, "(&(objectClass=container)(cn=System))");
85         if (system_dn == NULL) {
86                 talloc_free(msg);
87                 return NT_STATUS_NO_MEMORY;
88         }
89
90         name2 = talloc_asprintf(msg, "%s Secret", name);
91         if (name2 == NULL) {
92                 talloc_free(msg);
93                 return NT_STATUS_NO_MEMORY;
94         }
95
96         ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
97                            "(&(cn=%s)(objectclass=secret))",
98                            ldb_binary_encode_string(mem_ctx, name2));
99
100         if (ret != LDB_SUCCESS ||  res->count != 0 ) {
101                 DEBUG(2, ("Secret %s already exists !\n", name2));
102                 talloc_free(msg);
103                 return NT_STATUS_OBJECT_NAME_COLLISION;
104         }
105
106         /*
107          * We don't care about previous value as we are
108          * here only if the key didn't exists before
109          */
110
111         msg->dn = ldb_dn_copy(mem_ctx, system_dn);
112         if (msg->dn == NULL) {
113                 talloc_free(msg);
114                 return NT_STATUS_NO_MEMORY;
115         }
116         if (!ldb_dn_add_child_fmt(msg->dn, "cn=%s", name2)) {
117                 talloc_free(msg);
118                 return NT_STATUS_NO_MEMORY;
119         }
120
121         ret = ldb_msg_add_string(msg, "cn", name2);
122         if (ret != LDB_SUCCESS) {
123                 talloc_free(msg);
124                 return NT_STATUS_NO_MEMORY;
125         }
126         ret = ldb_msg_add_string(msg, "objectClass", "secret");
127         if (ret != LDB_SUCCESS) {
128                 talloc_free(msg);
129                 return NT_STATUS_NO_MEMORY;
130         }
131         ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "priorSetTime", nt_now);
132         if (ret != LDB_SUCCESS) {
133                 talloc_free(msg);
134                 return NT_STATUS_NO_MEMORY;
135         }
136         val.data = secret->data;
137         val.length = secret->length;
138         ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
139         if (ret != LDB_SUCCESS) {
140                 talloc_free(msg);
141                 return NT_STATUS_NO_MEMORY;
142         }
143         ret = samdb_msg_add_uint64(ldb, mem_ctx, msg, "lastSetTime", nt_now);
144         if (ret != LDB_SUCCESS) {
145                 talloc_free(msg);
146                 return NT_STATUS_NO_MEMORY;
147         }
148
149         /*
150          * create the secret with DSDB_MODIFY_RELAX
151          * otherwise dsdb/samdb/ldb_modules/objectclass.c forbid
152          * the create of LSA secret object
153          */
154         ret = dsdb_add(ldb, msg, DSDB_MODIFY_RELAX);
155         if (ret != LDB_SUCCESS) {
156                 DEBUG(2,("Failed to create secret record %s: %s\n",
157                         ldb_dn_get_linearized(msg->dn),
158                         ldb_errstring(ldb)));
159                 talloc_free(msg);
160                 return NT_STATUS_ACCESS_DENIED;
161         }
162
163         talloc_free(msg);
164         return NT_STATUS_OK;
165 }
166
167 /* This function is pretty much like dcesrv_lsa_QuerySecret */
168 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
169                                struct ldb_context *ldb,
170                                const char *name,
171                                DATA_BLOB *secret)
172 {
173         TALLOC_CTX *tmp_mem;
174         struct ldb_result *res;
175         struct ldb_dn *domain_dn;
176         struct ldb_dn *system_dn;
177         const struct ldb_val *val;
178         uint8_t *data;
179         const char *attrs[] = {
180                 "currentValue",
181                 NULL
182         };
183         int ret;
184
185         secret->data = NULL;
186         secret->length = 0;
187
188         domain_dn = ldb_get_default_basedn(ldb);
189         if (!domain_dn) {
190                 return NT_STATUS_INTERNAL_ERROR;
191         }
192
193         tmp_mem = talloc_new(mem_ctx);
194         if (tmp_mem == NULL) {
195                 return NT_STATUS_NO_MEMORY;
196         }
197
198         system_dn = samdb_search_dn(ldb, tmp_mem, domain_dn, "(&(objectClass=container)(cn=System))");
199         if (system_dn == NULL) {
200                 talloc_free(tmp_mem);
201                 return NT_STATUS_NO_MEMORY;
202         }
203
204         ret = ldb_search(ldb, mem_ctx, &res, system_dn, LDB_SCOPE_SUBTREE, attrs,
205                            "(&(cn=%s Secret)(objectclass=secret))",
206                            ldb_binary_encode_string(tmp_mem, name));
207
208         if (ret != LDB_SUCCESS || res->count == 0) {
209                 talloc_free(tmp_mem);
210                 /*
211                  * Important NOT to use NT_STATUS_OBJECT_NAME_NOT_FOUND
212                  * as this return value is used to detect the case
213                  * when we have the secret but without the currentValue
214                  * (case RODC)
215                  */
216                 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
217         }
218
219         if (res->count > 1) {
220                 DEBUG(2, ("Secret %s collision\n", name));
221                 talloc_free(tmp_mem);
222                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
223         }
224
225         val = ldb_msg_find_ldb_val(res->msgs[0], "currentValue");
226         if (val == NULL) {
227                 /*
228                  * The secret object is here but we don't have the secret value
229                  * The most common case is a RODC
230                  */
231                 talloc_free(tmp_mem);
232                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
233         }
234
235         data = val->data;
236         secret->data = talloc_move(mem_ctx, &data);
237         secret->length = val->length;
238
239         talloc_free(tmp_mem);
240         return NT_STATUS_OK;
241 }
242
243 static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
244 {
245         DATA_BLOB blob;
246         DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
247         uint32_t i;
248
249         blob.length = BN_num_bytes(bn);
250         blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
251
252         if (blob.data == NULL) {
253                 return NULL;
254         }
255
256         BN_bn2bin(bn, blob.data);
257
258         rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
259         if (rev->data == NULL) {
260                 return NULL;
261         }
262
263         for(i=0; i < blob.length; i++) {
264                 rev->data[i] = blob.data[blob.length - i -1];
265         }
266         rev->length = blob.length;
267         talloc_free(blob.data);
268         return rev;
269 }
270
271 static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
272 {
273         BIGNUM *ret;
274         DATA_BLOB rev;
275         uint32_t i;
276
277         rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
278         if (rev.data == NULL) {
279                 return NULL;
280         }
281
282         for(i=0; i < blob->length; i++) {
283                 rev.data[i] = blob->data[blob->length - i -1];
284         }
285         rev.length = blob->length;
286
287         ret = BN_bin2bn(rev.data, rev.length, NULL);
288         talloc_free(rev.data);
289
290         return ret;
291 }
292
293 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
294                                 struct bkrp_exported_RSA_key_pair *keypair,
295                                 hx509_private_key *pk)
296 {
297         hx509_context hctx;
298         RSA *rsa;
299         struct hx509_private_key_ops *ops;
300
301         hx509_context_init(&hctx);
302         ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
303         if (ops == NULL) {
304                 DEBUG(2, ("Not supported algorithm\n"));
305                 return NT_STATUS_INTERNAL_ERROR;
306         }
307
308         if (_hx509_private_key_init(pk, ops, NULL) != 0) {
309                 hx509_context_free(&hctx);
310                 return NT_STATUS_NO_MEMORY;
311         }
312
313         rsa = RSA_new();
314         if (rsa ==NULL) {
315                 hx509_context_free(&hctx);
316                 return NT_STATUS_INVALID_PARAMETER;
317         }
318
319         rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
320         if (rsa->n == NULL) {
321                 RSA_free(rsa);
322                 hx509_context_free(&hctx);
323                 return NT_STATUS_INVALID_PARAMETER;
324         }
325         rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
326         if (rsa->d == NULL) {
327                 RSA_free(rsa);
328                 hx509_context_free(&hctx);
329                 return NT_STATUS_INVALID_PARAMETER;
330         }
331         rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
332         if (rsa->p == NULL) {
333                 RSA_free(rsa);
334                 hx509_context_free(&hctx);
335                 return NT_STATUS_INVALID_PARAMETER;
336         }
337         rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
338         if (rsa->q == NULL) {
339                 RSA_free(rsa);
340                 hx509_context_free(&hctx);
341                 return NT_STATUS_INVALID_PARAMETER;
342         }
343         rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
344         if (rsa->dmp1 == NULL) {
345                 RSA_free(rsa);
346                 hx509_context_free(&hctx);
347                 return NT_STATUS_INVALID_PARAMETER;
348         }
349         rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
350         if (rsa->dmq1 == NULL) {
351                 RSA_free(rsa);
352                 hx509_context_free(&hctx);
353                 return NT_STATUS_INVALID_PARAMETER;
354         }
355         rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
356         if (rsa->iqmp == NULL) {
357                 RSA_free(rsa);
358                 hx509_context_free(&hctx);
359                 return NT_STATUS_INVALID_PARAMETER;
360         }
361         rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
362         if (rsa->e == NULL) {
363                 RSA_free(rsa);
364                 hx509_context_free(&hctx);
365                 return NT_STATUS_INVALID_PARAMETER;
366         }
367
368         _hx509_private_key_assign_rsa(*pk, rsa);
369
370         hx509_context_free(&hctx);
371         return NT_STATUS_OK;
372 }
373
374 static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
375                                           uint32_t version,
376                                           uint8_t *key_and_iv,
377                                           uint8_t *access_check,
378                                           uint32_t access_check_len,
379                                           struct dom_sid **access_sid)
380 {
381         heim_octet_string iv;
382         heim_octet_string access_check_os;
383         hx509_crypto crypto;
384
385         DATA_BLOB blob_us;
386         uint32_t key_len;
387         uint32_t iv_len;
388         int res;
389         enum ndr_err_code ndr_err;
390         hx509_context hctx;
391
392         /* This one should not be freed */
393         const AlgorithmIdentifier *alg;
394
395         *access_sid = NULL;
396         switch (version) {
397         case 2:
398                 key_len = 24;
399                 iv_len = 8;
400                 alg = hx509_crypto_des_rsdi_ede3_cbc();
401                 break;
402
403         case 3:
404                 key_len = 32;
405                 iv_len = 16;
406                 alg =hx509_crypto_aes256_cbc();
407                 break;
408
409         default:
410                 return WERR_INVALID_DATA;
411         }
412
413         hx509_context_init(&hctx);
414         res = hx509_crypto_init(hctx, NULL,
415                                 &(alg->algorithm),
416                                 &crypto);
417         hx509_context_free(&hctx);
418
419         if (res != 0) {
420                 return WERR_INVALID_DATA;
421         }
422
423         res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
424
425         iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
426         iv.length = iv_len;
427
428         if (res != 0) {
429                 hx509_crypto_destroy(crypto);
430                 return WERR_INVALID_DATA;
431         }
432
433         hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
434         res = hx509_crypto_decrypt(crypto,
435                 access_check,
436                 access_check_len,
437                 &iv,
438                 &access_check_os);
439
440         if (res != 0) {
441                 hx509_crypto_destroy(crypto);
442                 return WERR_INVALID_DATA;
443         }
444
445         blob_us.data = access_check_os.data;
446         blob_us.length = access_check_os.length;
447
448         hx509_crypto_destroy(crypto);
449
450         if (version == 2) {
451                 uint32_t hash_size = 20;
452                 uint8_t hash[hash_size];
453                 struct sha sctx;
454                 struct bkrp_access_check_v2 uncrypted_accesscheckv2;
455
456                 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
457                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
458                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
459                         /* Unable to unmarshall */
460                         der_free_octet_string(&access_check_os);
461                         return WERR_INVALID_DATA;
462                 }
463                 if (uncrypted_accesscheckv2.magic != 0x1) {
464                         /* wrong magic */
465                         der_free_octet_string(&access_check_os);
466                         return WERR_INVALID_DATA;
467                 }
468
469                 SHA1_Init(&sctx);
470                 SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
471                 SHA1_Final(hash, &sctx);
472                 der_free_octet_string(&access_check_os);
473                 /*
474                  * We free it after the sha1 calculation because blob.data
475                  * point to the same area
476                  */
477
478                 if (memcmp(hash, uncrypted_accesscheckv2.hash, hash_size) != 0) {
479                         DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
480                         return WERR_INVALID_DATA;
481                 }
482                 *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv2.sid));
483                 if (*access_sid == NULL) {
484                         return WERR_NOMEM;
485                 }
486                 return WERR_OK;
487         }
488
489         if (version == 3) {
490                 uint32_t hash_size = 64;
491                 uint8_t hash[hash_size];
492                 struct hc_sha512state sctx;
493                 struct bkrp_access_check_v3 uncrypted_accesscheckv3;
494
495                 ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
496                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
497                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
498                         /* Unable to unmarshall */
499                         der_free_octet_string(&access_check_os);
500                         return WERR_INVALID_DATA;
501                 }
502                 if (uncrypted_accesscheckv3.magic != 0x1) {
503                         /* wrong magic */
504                         der_free_octet_string(&access_check_os);
505                         return WERR_INVALID_DATA;
506                 }
507
508                 SHA512_Init(&sctx);
509                 SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
510                 SHA512_Final(hash, &sctx);
511                 der_free_octet_string(&access_check_os);
512                 /*
513                  * We free it after the sha1 calculation because blob.data
514                  * point to the same area
515                  */
516
517                 if (memcmp(hash, uncrypted_accesscheckv3.hash, hash_size) != 0) {
518                         DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
519                         return WERR_INVALID_DATA;
520                 }
521                 *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv3.sid));
522                 if (*access_sid == NULL) {
523                         return WERR_NOMEM;
524                 }
525                 return WERR_OK;
526         }
527
528         /* Never reached normally as we filtered at the switch / case level */
529         return WERR_INVALID_DATA;
530 }
531
532 static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call,
533                                               TALLOC_CTX *mem_ctx,
534                                               struct bkrp_BackupKey *r,
535                                               struct ldb_context *ldb_ctx)
536 {
537         struct bkrp_client_side_wrapped uncrypt_request;
538         DATA_BLOB blob;
539         enum ndr_err_code ndr_err;
540         char *guid_string;
541         char *cert_secret_name;
542         DATA_BLOB secret;
543         DATA_BLOB *uncrypted;
544         NTSTATUS status;
545
546         blob.data = r->in.data_in;
547         blob.length = r->in.data_in_len;
548
549         if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
550                 return WERR_INVALID_PARAM;
551         }
552
553         ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
554                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
555         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
556                 return WERR_INVALID_PARAM;
557         }
558
559         if (uncrypt_request.version < BACKUPKEY_MIN_VERSION) {
560                 return WERR_INVALID_PARAMETER;
561         }
562
563         if (uncrypt_request.version > BACKUPKEY_MAX_VERSION) {
564                 return WERR_INVALID_PARAMETER;
565         }
566
567         guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
568         if (guid_string == NULL) {
569                 return WERR_NOMEM;
570         }
571
572         cert_secret_name = talloc_asprintf(mem_ctx,
573                                            "BCKUPKEY_%s",
574                                            guid_string);
575         if (cert_secret_name == NULL) {
576                 return WERR_NOMEM;
577         }
578
579         status = get_lsa_secret(mem_ctx,
580                                 ldb_ctx,
581                                 cert_secret_name,
582                                 &secret);
583         if (!NT_STATUS_IS_OK(status)) {
584                 DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
585                 if (NT_STATUS_EQUAL(status,NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
586                         /* we do not have the real secret attribute */
587                         return WERR_INVALID_PARAMETER;
588                 } else {
589                         return WERR_FILE_NOT_FOUND;
590                 }
591         }
592
593         if (secret.length != 0) {
594                 hx509_context hctx;
595                 struct bkrp_exported_RSA_key_pair keypair;
596                 hx509_private_key pk;
597                 uint32_t i, res;
598                 struct dom_sid *access_sid = NULL;
599                 heim_octet_string reversed_secret;
600                 heim_octet_string uncrypted_secret;
601                 AlgorithmIdentifier alg;
602                 struct dom_sid *caller_sid;
603                 DATA_BLOB blob_us;
604                 WERROR werr;
605
606                 ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
607                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
608                         DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
609                         return WERR_FILE_NOT_FOUND;
610                 }
611
612                 status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
613                 if (!NT_STATUS_IS_OK(status)) {
614                         return WERR_INTERNAL_ERROR;
615                 }
616
617                 reversed_secret.data = talloc_array(mem_ctx, uint8_t,
618                                                     uncrypt_request.encrypted_secret_len);
619                 if (reversed_secret.data == NULL) {
620                         _hx509_private_key_free(&pk);
621                         return WERR_NOMEM;
622                 }
623
624                 /* The secret has to be reversed ... */
625                 for(i=0; i< uncrypt_request.encrypted_secret_len; i++) {
626                         uint8_t *reversed = (uint8_t *)reversed_secret.data;
627                         uint8_t *uncrypt = uncrypt_request.encrypted_secret;
628                         reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
629                 }
630                 reversed_secret.length = uncrypt_request.encrypted_secret_len;
631
632                 /*
633                  * Let's try to decrypt the secret now that
634                  * we have the private key ...
635                  */
636                 hx509_context_init(&hctx);
637                 res = _hx509_private_key_private_decrypt(hctx, &reversed_secret,
638                                                          &alg.algorithm, pk,
639                                                          &uncrypted_secret);
640                 hx509_context_free(&hctx);
641                 _hx509_private_key_free(&pk);
642                 if (res != 0) {
643                         /* We are not able to decrypt the secret, looks like something is wrong */
644                         return WERR_INVALID_DATA;
645                 }
646                 blob_us.data = uncrypted_secret.data;
647                 blob_us.length = uncrypted_secret.length;
648
649                 if (uncrypt_request.version == 2) {
650                         struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
651
652                         ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
653                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
654                         der_free_octet_string(&uncrypted_secret);
655                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
656                                 /* Unable to unmarshall */
657                                 return WERR_INVALID_DATA;
658                         }
659                         if (uncrypted_secretv2.magic != 0x20) {
660                                 /* wrong magic */
661                                 return WERR_INVALID_DATA;
662                         }
663
664                         werr = get_and_verify_access_check(mem_ctx, 2,
665                                                            uncrypted_secretv2.payload_key,
666                                                            uncrypt_request.access_check,
667                                                            uncrypt_request.access_check_len,
668                                                            &access_sid);
669                         if (!W_ERROR_IS_OK(werr)) {
670                                 return werr;
671                         }
672                         uncrypted = talloc(mem_ctx, DATA_BLOB);
673                         if (uncrypted == NULL) {
674                                 return WERR_INVALID_DATA;
675                         }
676
677                         uncrypted->data = uncrypted_secretv2.secret;
678                         uncrypted->length = uncrypted_secretv2.secret_len;
679                 }
680                 if (uncrypt_request.version == 3) {
681                         struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
682
683                         ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
684                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
685
686                         der_free_octet_string(&uncrypted_secret);
687                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
688                                 /* Unable to unmarshall */
689                                 return WERR_INVALID_DATA;
690                         }
691
692                         if (uncrypted_secretv3.magic1 != 0x30  ||
693                             uncrypted_secretv3.magic2 != 0x6610 ||
694                             uncrypted_secretv3.magic3 != 0x800e) {
695                                 /* wrong magic */
696                                 return WERR_INVALID_DATA;
697                         }
698
699                         werr = get_and_verify_access_check(mem_ctx, 3,
700                                                            uncrypted_secretv3.payload_key,
701                                                            uncrypt_request.access_check,
702                                                            uncrypt_request.access_check_len,
703                                                            &access_sid);
704                         if (!W_ERROR_IS_OK(werr)) {
705                                 return werr;
706                         }
707
708                         uncrypted = talloc(mem_ctx, DATA_BLOB);
709                         if (uncrypted == NULL) {
710                                 return WERR_INVALID_DATA;
711                         }
712
713                         uncrypted->data = uncrypted_secretv3.secret;
714                         uncrypted->length = uncrypted_secretv3.secret_len;
715                 }
716
717                 caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
718
719                 if (!dom_sid_equal(caller_sid, access_sid)) {
720                         talloc_free(uncrypted);
721                         return WERR_INVALID_ACCESS;
722                 }
723
724                 /*
725                  * Yeah if we are here all looks pretty good:
726                  * - hash is ok
727                  * - user sid is the same as the one in access check
728                  * - we were able to decrypt the whole stuff
729                  */
730         }
731
732         if (uncrypted->data == NULL) {
733                 return WERR_INVALID_DATA;
734         }
735
736         /* There is a magic value a the beginning of the data
737          * we can use an adhoc structure but as the
738          * parent structure is just an array of bytes it a lot of work
739          * work just prepending 4 bytes
740          */
741         *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted->length + 4);
742         W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
743         memcpy(4+*(r->out.data_out), uncrypted->data, uncrypted->length);
744         *(r->out.data_out_len) = uncrypted->length + 4;
745
746         return WERR_OK;
747 }
748
749 static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
750                                      hx509_private_key *pk, RSA **_rsa)
751 {
752         BIGNUM *pub_expo;
753         RSA *rsa;
754         int ret;
755         uint8_t *p0, *p;
756         size_t len;
757         int bits = 2048;
758
759         *_rsa = NULL;
760
761         pub_expo = BN_new();
762         if(pub_expo == NULL) {
763                 return WERR_INTERNAL_ERROR;
764         }
765
766         /* set the public expo to 65537 like everyone */
767         BN_set_word(pub_expo, 0x10001);
768
769         rsa = RSA_new();
770         if(rsa == NULL) {
771                 BN_free(pub_expo);
772                 return WERR_INTERNAL_ERROR;
773         }
774
775         ret = RSA_generate_key_ex(rsa, bits, pub_expo, NULL);
776         if(ret != 1) {
777                 RSA_free(rsa);
778                 BN_free(pub_expo);
779                 return WERR_INTERNAL_ERROR;
780         }
781         BN_free(pub_expo);
782
783         len = i2d_RSAPrivateKey(rsa, NULL);
784         if (len < 1) {
785                 RSA_free(rsa);
786                 return WERR_INTERNAL_ERROR;
787         }
788
789         p0 = p = talloc_array(ctx, uint8_t, len);
790         if (p == NULL) {
791                 RSA_free(rsa);
792                 return WERR_INTERNAL_ERROR;
793         }
794
795         len = i2d_RSAPrivateKey(rsa, &p);
796         if (len < 1) {
797                 RSA_free(rsa);
798                 talloc_free(p0);
799                 return WERR_INTERNAL_ERROR;
800         }
801
802         /*
803          * To dump the key we can use :
804          * rk_dumpdata("h5lkey", p0, len);
805          */
806         ret = _hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
807                                        p0, len, HX509_KEY_FORMAT_DER, pk);
808         memset(p0, 0, len);
809         talloc_free(p0);
810         if (ret !=0) {
811                 RSA_free(rsa);
812                 return WERR_INTERNAL_ERROR;
813         }
814
815         *_rsa = rsa;
816         return WERR_OK;
817 }
818
819 static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
820                                 time_t lifetime, hx509_private_key *private_key,
821                                 hx509_cert *cert, DATA_BLOB *guidblob)
822 {
823         SubjectPublicKeyInfo spki;
824         hx509_name subject = NULL;
825         hx509_ca_tbs tbs;
826         struct heim_bit_string uniqueid;
827         int ret;
828
829         uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
830         /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
831          * so as 1 byte is 8 bits we need to provision 8 times more space as in the
832          * blob
833          */
834         uniqueid.length = 8 * guidblob->length;
835
836         memset(&spki, 0, sizeof(spki));
837
838         ret = _hx509_request_get_name(*hctx, *req, &subject);
839         if (ret !=0) {
840                 talloc_free(uniqueid.data);
841                 return WERR_INTERNAL_ERROR;
842         }
843         ret = _hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
844         if (ret !=0) {
845                 talloc_free(uniqueid.data);
846                 hx509_name_free(&subject);
847                 return WERR_INTERNAL_ERROR;
848         }
849
850         ret = hx509_ca_tbs_init(*hctx, &tbs);
851         if (ret !=0) {
852                 talloc_free(uniqueid.data);
853                 hx509_name_free(&subject);
854                 free_SubjectPublicKeyInfo(&spki);
855                 return WERR_INTERNAL_ERROR;
856         }
857
858         ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
859         if (ret !=0) {
860                 talloc_free(uniqueid.data);
861                 hx509_name_free(&subject);
862                 free_SubjectPublicKeyInfo(&spki);
863                 return WERR_INTERNAL_ERROR;
864         }
865         ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
866         if (ret !=0) {
867                 talloc_free(uniqueid.data);
868                 hx509_name_free(&subject);
869                 free_SubjectPublicKeyInfo(&spki);
870                 hx509_ca_tbs_free(&tbs);
871                 return WERR_INTERNAL_ERROR;
872         }
873         ret = hx509_ca_tbs_set_ca(*hctx, tbs, 1);
874         if (ret !=0) {
875                 talloc_free(uniqueid.data);
876                 hx509_name_free(&subject);
877                 free_SubjectPublicKeyInfo(&spki);
878                 hx509_ca_tbs_free(&tbs);
879                 return WERR_INTERNAL_ERROR;
880         }
881         ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
882         if (ret !=0) {
883                 talloc_free(uniqueid.data);
884                 hx509_name_free(&subject);
885                 free_SubjectPublicKeyInfo(&spki);
886                 hx509_ca_tbs_free(&tbs);
887                 return WERR_INTERNAL_ERROR;
888         }
889         ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
890         if (ret !=0) {
891                 talloc_free(uniqueid.data);
892                 hx509_name_free(&subject);
893                 free_SubjectPublicKeyInfo(&spki);
894                 hx509_ca_tbs_free(&tbs);
895                 return WERR_INTERNAL_ERROR;
896         }
897         ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
898         if (ret !=0) {
899                 talloc_free(uniqueid.data);
900                 hx509_name_free(&subject);
901                 free_SubjectPublicKeyInfo(&spki);
902                 hx509_ca_tbs_free(&tbs);
903                 return WERR_INTERNAL_ERROR;
904         }
905         hx509_name_free(&subject);
906         free_SubjectPublicKeyInfo(&spki);
907         hx509_ca_tbs_free(&tbs);
908
909         return WERR_OK;
910 }
911
912 static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
913                          hx509_private_key *signer,RSA **rsa, const char *dn)
914 {
915         int ret;
916         SubjectPublicKeyInfo key;
917
918         hx509_name name;
919         WERROR w_err;
920
921         w_err = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
922         if (!W_ERROR_IS_OK(w_err)) {
923                 return w_err;
924         }
925
926         _hx509_request_init(*hctx, req);
927         ret = hx509_parse_name(*hctx, dn, &name);
928         if (ret != 0) {
929                 RSA_free(*rsa);
930                 _hx509_private_key_free(signer);
931                 _hx509_request_free(req);
932                 hx509_name_free(&name);
933                 return WERR_INTERNAL_ERROR;
934         }
935
936         ret = _hx509_request_set_name(*hctx, *req, name);
937         if (ret != 0) {
938                 RSA_free(*rsa);
939                 _hx509_private_key_free(signer);
940                 _hx509_request_free(req);
941                 hx509_name_free(&name);
942                 return WERR_INTERNAL_ERROR;
943         }
944         hx509_name_free(&name);
945
946         ret = _hx509_private_key2SPKI(*hctx, *signer, &key);
947         if (ret != 0) {
948                 RSA_free(*rsa);
949                 _hx509_private_key_free(signer);
950                 _hx509_request_free(req);
951                 return WERR_INTERNAL_ERROR;
952         }
953         ret = _hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
954         if (ret != 0) {
955                 RSA_free(*rsa);
956                 _hx509_private_key_free(signer);
957                 free_SubjectPublicKeyInfo(&key);
958                 _hx509_request_free(req);
959                 return WERR_INTERNAL_ERROR;
960         }
961
962         free_SubjectPublicKeyInfo(&key);
963
964         return WERR_OK;
965 }
966
967 /* Return an error when we fail to generate a certificate */
968 static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
969 {
970
971         struct heim_octet_string data;
972         WERROR w_err;
973         RSA *rsa;
974         hx509_context hctx;
975         hx509_private_key pk;
976         hx509_request req;
977         hx509_cert cert;
978         DATA_BLOB blob;
979         DATA_BLOB blobkeypair;
980         DATA_BLOB *tmp;
981         int ret;
982         bool ok = true;
983         struct GUID guid = GUID_random();
984         NTSTATUS status;
985         char *secret_name;
986         struct bkrp_exported_RSA_key_pair keypair;
987         enum ndr_err_code ndr_err;
988         uint32_t nb_days_validity = 365;
989
990         DEBUG(6, ("Trying to generate a certificate\n"));
991         hx509_context_init(&hctx);
992         w_err = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
993         if (!W_ERROR_IS_OK(w_err)) {
994                 hx509_context_free(&hctx);
995                 return w_err;
996         }
997
998         status = GUID_to_ndr_blob(&guid, ctx, &blob);
999         if (!NT_STATUS_IS_OK(status)) {
1000                 hx509_context_free(&hctx);
1001                 _hx509_private_key_free(&pk);
1002                 RSA_free(rsa);
1003                 return WERR_INVALID_DATA;
1004         }
1005
1006         w_err = self_sign_cert(ctx, &hctx, &req, nb_days_validity, &pk, &cert, &blob);
1007         if (!W_ERROR_IS_OK(w_err)) {
1008                 _hx509_private_key_free(&pk);
1009                 hx509_context_free(&hctx);
1010                 return WERR_INVALID_DATA;
1011         }
1012
1013         ret = hx509_cert_binary(hctx, cert, &data);
1014         if (ret !=0) {
1015                 hx509_cert_free(cert);
1016                 _hx509_private_key_free(&pk);
1017                 hx509_context_free(&hctx);
1018                 return WERR_INVALID_DATA;
1019         }
1020
1021         keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
1022         keypair.cert.length = data.length;
1023
1024         /*
1025          * Heimdal's bignum are big endian and the
1026          * structure expect it to be in little endian
1027          * so we reverse the buffer to make it work
1028          */
1029         tmp = reverse_and_get_blob(ctx, rsa->e);
1030         if (tmp == NULL) {
1031                 ok = false;
1032         } else {
1033                 keypair.public_exponent = *tmp;
1034                 SMB_ASSERT(tmp->length <= 4);
1035                 /*
1036                  * The value is now in little endian but if can happen that the length is
1037                  * less than 4 bytes.
1038                  * So if we have less than 4 bytes we pad with zeros so that it correctly
1039                  * fit into the structure.
1040                  */
1041                 if (tmp->length < 4) {
1042                         /*
1043                          * We need the expo to fit 4 bytes
1044                          */
1045                         keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
1046                         memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
1047                         keypair.public_exponent.length = 4;
1048                 }
1049         }
1050
1051         tmp = reverse_and_get_blob(ctx,rsa->d);
1052         if (tmp == NULL) {
1053                 ok = false;
1054         } else {
1055                 keypair.private_exponent = *tmp;
1056         }
1057
1058         tmp = reverse_and_get_blob(ctx,rsa->n);
1059         if (tmp == NULL) {
1060                 ok = false;
1061         } else {
1062                 keypair.modulus = *tmp;
1063         }
1064
1065         tmp = reverse_and_get_blob(ctx,rsa->p);
1066         if (tmp == NULL) {
1067                 ok = false;
1068         } else {
1069                 keypair.prime1 = *tmp;
1070         }
1071
1072         tmp = reverse_and_get_blob(ctx,rsa->q);
1073         if (tmp == NULL) {
1074                 ok = false;
1075         } else {
1076                 keypair.prime2 = *tmp;
1077         }
1078
1079         tmp = reverse_and_get_blob(ctx,rsa->dmp1);
1080         if (tmp == NULL) {
1081                 ok = false;
1082         } else {
1083                 keypair.exponent1 = *tmp;
1084         }
1085
1086         tmp = reverse_and_get_blob(ctx,rsa->dmq1);
1087         if (tmp == NULL) {
1088                 ok = false;
1089         } else {
1090                 keypair.exponent2 = *tmp;
1091         }
1092
1093         tmp = reverse_and_get_blob(ctx,rsa->iqmp);
1094         if (tmp == NULL) {
1095                 ok = false;
1096         } else {
1097                 keypair.coefficient = *tmp;
1098         }
1099
1100         /* One of the keypair allocation was wrong */
1101         if (ok == false) {
1102                 der_free_octet_string(&data);
1103                 hx509_cert_free(cert);
1104                 _hx509_private_key_free(&pk);
1105                 hx509_context_free(&hctx);
1106                 RSA_free(rsa);
1107                 return WERR_INVALID_DATA;
1108         }
1109         keypair.certificate_len = keypair.cert.length;
1110         ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
1111         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1112                 der_free_octet_string(&data);
1113                 hx509_cert_free(cert);
1114                 _hx509_private_key_free(&pk);
1115                 hx509_context_free(&hctx);
1116                 RSA_free(rsa);
1117                 return WERR_INVALID_DATA;
1118         }
1119
1120         secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
1121         if (secret_name == NULL) {
1122                 der_free_octet_string(&data);
1123                 hx509_cert_free(cert);
1124                 _hx509_private_key_free(&pk);
1125                 hx509_context_free(&hctx);
1126                 RSA_free(rsa);
1127                 return WERR_OUTOFMEMORY;
1128         }
1129
1130         status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
1131         if (!NT_STATUS_IS_OK(status)) {
1132                 DEBUG(2, ("Failed to save the secret %s\n", secret_name));
1133         }
1134         talloc_free(secret_name);
1135
1136         GUID_to_ndr_blob(&guid, ctx, &blob);
1137         status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
1138         if (!NT_STATUS_IS_OK(status)) {
1139                 DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
1140         }
1141
1142         der_free_octet_string(&data);
1143         hx509_cert_free(cert);
1144         _hx509_private_key_free(&pk);
1145         hx509_context_free(&hctx);
1146         RSA_free(rsa);
1147         return WERR_OK;
1148 }
1149
1150 static WERROR bkrp_do_retreive_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1151                 struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
1152 {
1153         struct GUID guid;
1154         char *guid_string;
1155         DATA_BLOB secret;
1156         enum ndr_err_code ndr_err;
1157         NTSTATUS status;
1158
1159         /*
1160          * here we basicaly need to return our certificate
1161          * search for lsa secret BCKUPKEY_PREFERRED first
1162          */
1163
1164         status = get_lsa_secret(mem_ctx,
1165                                 ldb_ctx,
1166                                 "BCKUPKEY_PREFERRED",
1167                                 &secret);
1168         if (!NT_STATUS_IS_OK(status)) {
1169                 DEBUG(10, ("Error while fetching secret BCKUPKEY_PREFERRED\n"));
1170                 if (!NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1171                         /* Ok we can be in this case if there was no certs */
1172                         struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
1173                         char *dn = talloc_asprintf(mem_ctx, "CN=%s.%s",
1174                                                         lpcfg_netbios_name(lp_ctx),
1175                                                         lpcfg_realm(lp_ctx));
1176
1177                         WERROR werr =  generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
1178                         if (!W_ERROR_IS_OK(werr)) {
1179                                 return WERR_INVALID_PARAMETER;
1180                         }
1181                         status = get_lsa_secret(mem_ctx,
1182                                         ldb_ctx,
1183                                         "BCKUPKEY_PREFERRED",
1184                                         &secret);
1185
1186                         if (!NT_STATUS_IS_OK(status)) {
1187                                 /* Ok we really don't manage to get this certs ...*/
1188                                 DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
1189                                 return WERR_FILE_NOT_FOUND;
1190                         }
1191                 } else {
1192                         /* In theory we should NEVER reach this point as it
1193                            should only appear in a rodc server */
1194                         /* we do not have the real secret attribute */
1195                         return WERR_INVALID_PARAMETER;
1196                 }
1197         }
1198
1199         if (secret.length != 0) {
1200                 char *cert_secret_name;
1201
1202                 status = GUID_from_ndr_blob(&secret, &guid);
1203                 if (!NT_STATUS_IS_OK(status)) {
1204                         return WERR_FILE_NOT_FOUND;
1205                 }
1206
1207                 guid_string = GUID_string(mem_ctx, &guid);
1208                 if (guid_string == NULL) {
1209                         /* We return file not found because the client
1210                          * expect this error
1211                          */
1212                         return WERR_FILE_NOT_FOUND;
1213                 }
1214                                 
1215                 cert_secret_name = talloc_asprintf(mem_ctx,
1216                                                         "BCKUPKEY_%s",
1217                                                         guid_string);
1218                 status = get_lsa_secret(mem_ctx,
1219                                         ldb_ctx,
1220                                         cert_secret_name,
1221                                         &secret);
1222                 if (!NT_STATUS_IS_OK(status)) {
1223                         return WERR_FILE_NOT_FOUND;
1224                 }
1225
1226                 if (secret.length != 0) {
1227                         struct bkrp_exported_RSA_key_pair keypair;
1228                         ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair,
1229                                         (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
1230                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1231                                 return WERR_FILE_NOT_FOUND;
1232                         }
1233                         *(r->out.data_out_len) = keypair.cert.length;
1234                         *(r->out.data_out) = talloc_memdup(mem_ctx, keypair.cert.data, keypair.cert.length);
1235                         W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
1236                         return WERR_OK;
1237                 } else {
1238                         DEBUG(10, ("No or broken secret called %s\n", cert_secret_name));
1239                         return WERR_FILE_NOT_FOUND;
1240                 }
1241         } else {
1242                 DEBUG(10, ("No secret BCKUPKEY_PREFERRED\n"));
1243                 return WERR_FILE_NOT_FOUND;
1244         }
1245
1246         return WERR_NOT_SUPPORTED;
1247 }
1248
1249 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
1250                                     TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
1251 {
1252         WERROR error = WERR_INVALID_PARAM;
1253         struct ldb_context *ldb_ctx;
1254         bool is_rodc;
1255         const char *addr = "unknown";
1256         /* At which level we start to add more debug of what is done in the protocol */
1257         const int debuglevel = 4;
1258
1259         if (DEBUGLVL(debuglevel)) {
1260                 const struct tsocket_address *remote_address;
1261                 remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
1262                 if (tsocket_address_is_inet(remote_address, "ip")) {
1263                         addr = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1264                         W_ERROR_HAVE_NO_MEMORY(addr);
1265                 }
1266         }
1267
1268         if (lpcfg_server_role(dce_call->conn->dce_ctx->lp_ctx) != ROLE_DOMAIN_CONTROLLER) {
1269                 return WERR_NOT_SUPPORTED;
1270         }
1271
1272         if (!dce_call->conn->auth_state.auth_info ||
1273                 dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
1274                 DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
1275         }
1276
1277         ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
1278                                 dce_call->conn->dce_ctx->lp_ctx,
1279                                 system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
1280
1281         if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
1282                 talloc_unlink(mem_ctx, ldb_ctx);
1283                 return WERR_INVALID_PARAM;
1284         }
1285
1286         if (!is_rodc) {
1287                 if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1288                         BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
1289                         DEBUG(debuglevel, ("Client %s requested to decrypt a client side wrapped secret\n", addr));
1290                         error = bkrp_do_uncrypt_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1291                 }
1292
1293                 if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
1294                         BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
1295                         DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
1296                         error = bkrp_do_retreive_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
1297                 }
1298         }
1299         /*else: I am a RODC so I don't handle backup key protocol */
1300
1301         talloc_unlink(mem_ctx, ldb_ctx);
1302         return error;
1303 }
1304
1305 /* include the generated boilerplate */
1306 #include "librpc/gen_ndr/ndr_backupkey_s.c"