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