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