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