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