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