s4:rpc_server: only use context within op_bind() hooks and dcesrv_interface_bind_...
[samba.git] / source4 / rpc_server / backupkey / dcesrv_backupkey.c
index 1bcb115521694419e3f1c2bad5d26c5de4c5646a..307a7f09b74e8a8391c5bd51fef883d417edc6a8 100644 (file)
@@ -4,6 +4,7 @@
    endpoint server for the backupkey interface
 
    Copyright (C) Matthieu Patou <mat@samba.org> 2010
+   Copyright (C) Andreas Schneider <asn@samba.org> 2015
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -21,6 +22,7 @@
 
 #include "includes.h"
 #include "rpc_server/dcerpc_server.h"
+#include "rpc_server/common/common.h"
 #include "librpc/gen_ndr/ndr_backupkey.h"
 #include "dsdb/common/util.h"
 #include "dsdb/samdb/samdb.h"
 #include "param/param.h"
 #include "auth/session.h"
 #include "system/network.h"
-#include <com_err.h>
-#include <hx509.h>
-#include <hcrypto/rsa.h>
-#include <hcrypto/bn.h>
-#include <hcrypto/sha.h>
-#include <der.h>
+
 #include "../lib/tsocket/tsocket.h"
 #include "../libcli/security/security.h"
-
-#define BACKUPKEY_MIN_VERSION 2
-#define BACKUPKEY_MAX_VERSION 3
-
-static const unsigned rsa_with_var_num[] = { 1, 2, 840, 113549, 1, 1, 1 };
-/* Equivalent to asn1_oid_id_pkcs1_rsaEncryption*/
-static const AlgorithmIdentifier _hx509_signature_rsa_with_var_num = {
-       { 7, discard_const_p(unsigned, rsa_with_var_num) }, NULL
-};
+#include "librpc/gen_ndr/ndr_security.h"
+#include "libds/common/roles.h"
+
+#include <gnutls/gnutls.h>
+#include <gnutls/x509.h>
+#include <gnutls/crypto.h>
+#include <gnutls/abstract.h>
+
+#define DCESRV_INTERFACE_BACKUPKEY_BIND(call, iface) \
+       dcesrv_interface_backupkey_bind(call, iface)
+static NTSTATUS dcesrv_interface_backupkey_bind(struct dcesrv_call_state *dce_call,
+                                               const struct dcesrv_interface *iface)
+{
+       struct dcesrv_connection_context *context = dce_call->context;
+       return dcesrv_interface_bind_require_privacy(context, iface);
+}
 
 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
                               struct ldb_context *ldb,
                               const char *name,
-                              const DATA_BLOB *secret)
+                              const DATA_BLOB *lsa_secret)
 {
        struct ldb_message *msg;
        struct ldb_result *res;
@@ -137,8 +141,8 @@ static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
                talloc_free(msg);
                return NT_STATUS_NO_MEMORY;
        }
-       val.data = secret->data;
-       val.length = secret->length;
+       val.data = lsa_secret->data;
+       val.length = lsa_secret->length;
        ret = ldb_msg_add_value(msg, "currentValue", &val, NULL);
        if (ret != LDB_SUCCESS) {
                talloc_free(msg);
@@ -172,7 +176,7 @@ static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
 static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
                               struct ldb_context *ldb,
                               const char *name,
-                              DATA_BLOB *secret)
+                              DATA_BLOB *lsa_secret)
 {
        TALLOC_CTX *tmp_mem;
        struct ldb_result *res;
@@ -186,8 +190,8 @@ static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
        };
        int ret;
 
-       secret->data = NULL;
-       secret->length = 0;
+       lsa_secret->data = NULL;
+       lsa_secret->length = 0;
 
        domain_dn = ldb_get_default_basedn(ldb);
        if (!domain_dn) {
@@ -209,17 +213,14 @@ static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
                           "(&(cn=%s Secret)(objectclass=secret))",
                           ldb_binary_encode_string(tmp_mem, name));
 
-       if (ret != LDB_SUCCESS || res->count == 0) {
+       if (ret != LDB_SUCCESS) {
+               talloc_free(tmp_mem);
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+       if (res->count == 0) {
                talloc_free(tmp_mem);
-               /*
-                * Important NOT to use NT_STATUS_OBJECT_NAME_NOT_FOUND
-                * as this return value is used to detect the case
-                * when we have the secret but without the currentValue
-                * (case RODC)
-                */
                return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
        }
-
        if (res->count > 1) {
                DEBUG(2, ("Secret %s collision\n", name));
                talloc_free(tmp_mem);
@@ -232,146 +233,125 @@ static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
                 * The secret object is here but we don't have the secret value
                 * The most common case is a RODC
                 */
+               *lsa_secret = data_blob_null;
                talloc_free(tmp_mem);
-               return NT_STATUS_OBJECT_NAME_NOT_FOUND;
+               return NT_STATUS_OK;
        }
 
        data = val->data;
-       secret->data = talloc_move(mem_ctx, &data);
-       secret->length = val->length;
+       lsa_secret->data = talloc_move(mem_ctx, &data);
+       lsa_secret->length = val->length;
 
        talloc_free(tmp_mem);
        return NT_STATUS_OK;
 }
 
-static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx, BIGNUM *bn)
-{
-       DATA_BLOB blob;
-       DATA_BLOB *rev = talloc(mem_ctx, DATA_BLOB);
-       uint32_t i;
-
-       blob.length = BN_num_bytes(bn);
-       blob.data = talloc_array(mem_ctx, uint8_t, blob.length);
-
-       if (blob.data == NULL) {
-               return NULL;
-       }
-
-       BN_bn2bin(bn, blob.data);
-
-       rev->data = talloc_array(mem_ctx, uint8_t, blob.length);
-       if (rev->data == NULL) {
-               return NULL;
-       }
-
-       for(i=0; i < blob.length; i++) {
-               rev->data[i] = blob.data[blob.length - i -1];
-       }
-       rev->length = blob.length;
-       talloc_free(blob.data);
-       return rev;
-}
-
-static BIGNUM *reverse_and_get_bignum(TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
+static int reverse_and_get_bignum(TALLOC_CTX *mem_ctx,
+                                 DATA_BLOB blob,
+                                 gnutls_datum_t *datum)
 {
-       BIGNUM *ret;
-       DATA_BLOB rev;
        uint32_t i;
 
-       rev.data = talloc_array(mem_ctx, uint8_t, blob->length);
-       if (rev.data == NULL) {
-               return NULL;
+       datum->data = talloc_array(mem_ctx, uint8_t, blob.length);
+       if (datum->data == NULL) {
+               return -1;
        }
 
-       for(i=0; i < blob->length; i++) {
-               rev.data[i] = blob->data[blob->length - i -1];
+       for(i = 0; i < blob.length; i++) {
+               datum->data[i] = blob.data[blob.length - i - 1];
        }
-       rev.length = blob->length;
+       datum->size = blob.length;
 
-       ret = BN_bin2bn(rev.data, rev.length, NULL);
-       talloc_free(rev.data);
-
-       return ret;
+       return 0;
 }
 
 static NTSTATUS get_pk_from_raw_keypair_params(TALLOC_CTX *ctx,
                                struct bkrp_exported_RSA_key_pair *keypair,
-                               hx509_private_key *pk)
+                               gnutls_privkey_t *pk)
 {
-       hx509_context hctx;
-       RSA *rsa;
-       struct hx509_private_key_ops *ops;
-
-       hx509_context_init(&hctx);
-       ops = hx509_find_private_alg(&_hx509_signature_rsa_with_var_num.algorithm);
-       if (ops == NULL) {
-               DEBUG(2, ("Not supported algorithm\n"));
-               return NT_STATUS_INTERNAL_ERROR;
-       }
+       gnutls_x509_privkey_t x509_privkey = NULL;
+       gnutls_privkey_t privkey = NULL;
+       gnutls_datum_t m, e, d, p, q, u, e1, e2;
+       int rc;
 
-       if (hx509_private_key_init(pk, ops, NULL) != 0) {
-               hx509_context_free(&hctx);
-               return NT_STATUS_NO_MEMORY;
-       }
-
-       rsa = RSA_new();
-       if (rsa ==NULL) {
-               hx509_context_free(&hctx);
+       rc = reverse_and_get_bignum(ctx, keypair->modulus, &m);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-
-       rsa->n = reverse_and_get_bignum(ctx, &(keypair->modulus));
-       if (rsa->n == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+       rc = reverse_and_get_bignum(ctx, keypair->public_exponent, &e);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->d = reverse_and_get_bignum(ctx, &(keypair->private_exponent));
-       if (rsa->d == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+       rc = reverse_and_get_bignum(ctx, keypair->private_exponent, &d);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->p = reverse_and_get_bignum(ctx, &(keypair->prime1));
-       if (rsa->p == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+
+       rc = reverse_and_get_bignum(ctx, keypair->prime1, &p);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->q = reverse_and_get_bignum(ctx, &(keypair->prime2));
-       if (rsa->q == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+       rc = reverse_and_get_bignum(ctx, keypair->prime2, &q);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->dmp1 = reverse_and_get_bignum(ctx, &(keypair->exponent1));
-       if (rsa->dmp1 == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+
+       rc = reverse_and_get_bignum(ctx, keypair->coefficient, &u);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->dmq1 = reverse_and_get_bignum(ctx, &(keypair->exponent2));
-       if (rsa->dmq1 == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+
+       rc = reverse_and_get_bignum(ctx, keypair->exponent1, &e1);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->iqmp = reverse_and_get_bignum(ctx, &(keypair->coefficient));
-       if (rsa->iqmp == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
+       rc = reverse_and_get_bignum(ctx, keypair->exponent2, &e2);
+       if (rc != 0) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       rsa->e = reverse_and_get_bignum(ctx, &(keypair->public_exponent));
-       if (rsa->e == NULL) {
-               RSA_free(rsa);
-               hx509_context_free(&hctx);
-               return NT_STATUS_INVALID_PARAMETER;
+
+       rc = gnutls_x509_privkey_init(&x509_privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
+               return NT_STATUS_INTERNAL_ERROR;
        }
 
-       hx509_private_key_assign_rsa(*pk, rsa);
+       rc = gnutls_x509_privkey_import_rsa_raw2(x509_privkey,
+                                                &m,
+                                                &e,
+                                                &d,
+                                                &p,
+                                                &q,
+                                                &u,
+                                                &e1,
+                                                &e2);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_import_rsa_raw2 failed - %s\n",
+                       gnutls_strerror(rc));
+               return NT_STATUS_INTERNAL_ERROR;
+       }
+
+       rc = gnutls_privkey_init(&privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_privkey);
+               return NT_STATUS_INTERNAL_ERROR;
+       }
+
+       rc = gnutls_privkey_import_x509(privkey,
+                                       x509_privkey,
+                                       GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_privkey);
+               return NT_STATUS_INTERNAL_ERROR;
+       }
+
+       *pk = privkey;
 
-       hx509_context_free(&hctx);
        return NT_STATUS_OK;
 }
 
@@ -380,100 +360,89 @@ static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
                                          uint8_t *key_and_iv,
                                          uint8_t *access_check,
                                          uint32_t access_check_len,
-                                         struct dom_sid **access_sid)
+                                         struct auth_session_info *session_info)
 {
-       heim_octet_string iv;
-       heim_octet_string access_check_os;
-       hx509_crypto crypto;
-
+       struct bkrp_access_check_v2 uncrypted_accesscheckv2;
+       struct bkrp_access_check_v3 uncrypted_accesscheckv3;
+       gnutls_cipher_hd_t cipher_handle = { 0 };
+       gnutls_cipher_algorithm_t cipher_algo;
        DATA_BLOB blob_us;
-       uint32_t key_len;
-       uint32_t iv_len;
-       int res;
        enum ndr_err_code ndr_err;
-       hx509_context hctx;
+       gnutls_datum_t key;
+       gnutls_datum_t iv;
 
-       /* This one should not be freed */
-       const AlgorithmIdentifier *alg;
+       struct dom_sid *access_sid = NULL;
+       struct dom_sid *caller_sid = NULL;
+       int rc;
 
-       *access_sid = NULL;
        switch (version) {
        case 2:
-               key_len = 24;
-               iv_len = 8;
-               alg = hx509_crypto_des_rsdi_ede3_cbc();
+               cipher_algo = GNUTLS_CIPHER_3DES_CBC;
                break;
-
        case 3:
-               key_len = 32;
-               iv_len = 16;
-               alg =hx509_crypto_aes256_cbc();
+               cipher_algo = GNUTLS_CIPHER_AES_256_CBC;
                break;
-
        default:
                return WERR_INVALID_DATA;
        }
 
-       hx509_context_init(&hctx);
-       res = hx509_crypto_init(hctx, NULL,
-                               &(alg->algorithm),
-                               &crypto);
-       hx509_context_free(&hctx);
+       key.data = key_and_iv;
+       key.size = gnutls_cipher_get_key_size(cipher_algo);
+
+       iv.data = key_and_iv + key.size;
+       iv.size = gnutls_cipher_get_iv_size(cipher_algo);
 
-       if (res != 0) {
+       /* Allocate data structure for the plaintext */
+       blob_us = data_blob_talloc_zero(sub_ctx, access_check_len);
+       if (blob_us.data == NULL) {
                return WERR_INVALID_DATA;
        }
 
-       res = hx509_crypto_set_key_data(crypto, key_and_iv, key_len);
-
-       iv.data = talloc_memdup(sub_ctx, key_len + key_and_iv, iv_len);
-       iv.length = iv_len;
-
-       if (res != 0) {
-               hx509_crypto_destroy(crypto);
+       rc = gnutls_cipher_init(&cipher_handle,
+                               cipher_algo,
+                               &key,
+                               &iv);
+       if (rc < 0) {
+               DBG_ERR("gnutls_cipher_init failed: %s\n",
+                       gnutls_strerror(rc));
                return WERR_INVALID_DATA;
        }
 
-       hx509_crypto_set_padding(crypto, HX509_CRYPTO_PADDING_NONE);
-       res = hx509_crypto_decrypt(crypto,
-               access_check,
-               access_check_len,
-               &iv,
-               &access_check_os);
-
-       if (res != 0) {
-               hx509_crypto_destroy(crypto);
+       rc = gnutls_cipher_decrypt2(cipher_handle,
+                                   access_check,
+                                   access_check_len,
+                                   blob_us.data,
+                                   blob_us.length);
+       gnutls_cipher_deinit(cipher_handle);
+       if (rc < 0) {
+               DBG_ERR("gnutls_cipher_decrypt2 failed: %s\n",
+                       gnutls_strerror(rc));
                return WERR_INVALID_DATA;
        }
 
-       blob_us.data = access_check_os.data;
-       blob_us.length = access_check_os.length;
-
-       hx509_crypto_destroy(crypto);
-
-       if (version == 2) {
+       switch (version) {
+       case 2:
+       {
                uint32_t hash_size = 20;
                uint8_t hash[hash_size];
-               struct sha sctx;
-               struct bkrp_access_check_v2 uncrypted_accesscheckv2;
+               gnutls_hash_hd_t dig_ctx;
 
                ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv2,
                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v2);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        /* Unable to unmarshall */
-                       der_free_octet_string(&access_check_os);
                        return WERR_INVALID_DATA;
                }
                if (uncrypted_accesscheckv2.magic != 0x1) {
                        /* wrong magic */
-                       der_free_octet_string(&access_check_os);
                        return WERR_INVALID_DATA;
                }
 
-               SHA1_Init(&sctx);
-               SHA1_Update(&sctx, blob_us.data, blob_us.length - hash_size);
-               SHA1_Final(hash, &sctx);
-               der_free_octet_string(&access_check_os);
+               gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA1);
+               gnutls_hash(dig_ctx,
+                           blob_us.data,
+                           blob_us.length - hash_size);
+               gnutls_hash_deinit(dig_ctx, hash);
                /*
                 * We free it after the sha1 calculation because blob.data
                 * point to the same area
@@ -483,36 +452,32 @@ static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
                        DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
                        return WERR_INVALID_DATA;
                }
-               *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv2.sid));
-               if (*access_sid == NULL) {
-                       return WERR_NOMEM;
-               }
-               return WERR_OK;
+               access_sid = &(uncrypted_accesscheckv2.sid);
+               break;
        }
-
-       if (version == 3) {
+       case 3:
+       {
                uint32_t hash_size = 64;
                uint8_t hash[hash_size];
-               struct hc_sha512state sctx;
-               struct bkrp_access_check_v3 uncrypted_accesscheckv3;
+               gnutls_hash_hd_t dig_ctx;
 
                ndr_err = ndr_pull_struct_blob(&blob_us, sub_ctx, &uncrypted_accesscheckv3,
                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_access_check_v3);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        /* Unable to unmarshall */
-                       der_free_octet_string(&access_check_os);
                        return WERR_INVALID_DATA;
                }
                if (uncrypted_accesscheckv3.magic != 0x1) {
                        /* wrong magic */
-                       der_free_octet_string(&access_check_os);
                        return WERR_INVALID_DATA;
                }
 
-               SHA512_Init(&sctx);
-               SHA512_Update(&sctx, blob_us.data, blob_us.length - hash_size);
-               SHA512_Final(hash, &sctx);
-               der_free_octet_string(&access_check_os);
+               gnutls_hash_init(&dig_ctx, GNUTLS_DIG_SHA512);
+               gnutls_hash(dig_ctx,
+                           blob_us.data,
+                           blob_us.length - hash_size);
+               gnutls_hash_deinit(dig_ctx, hash);
+
                /*
                 * We free it after the sha1 calculation because blob.data
                 * point to the same area
@@ -522,98 +487,127 @@ static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
                        DEBUG(2, ("Wrong hash value in the access check in backup key remote protocol\n"));
                        return WERR_INVALID_DATA;
                }
-               *access_sid = dom_sid_dup(sub_ctx, &(uncrypted_accesscheckv3.sid));
-               if (*access_sid == NULL) {
-                       return WERR_NOMEM;
-               }
-               return WERR_OK;
+               access_sid = &(uncrypted_accesscheckv3.sid);
+               break;
        }
+       default:
+               /* Never reached normally as we filtered at the switch / case level */
+               return WERR_INVALID_DATA;
+       }
+
+       caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
 
-       /* Never reached normally as we filtered at the switch / case level */
-       return WERR_INVALID_DATA;
+       if (!dom_sid_equal(caller_sid, access_sid)) {
+               return WERR_INVALID_ACCESS;
+       }
+       return WERR_OK;
 }
 
-static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call,
-                                             TALLOC_CTX *mem_ctx,
-                                             struct bkrp_BackupKey *r,
-                                             struct ldb_context *ldb_ctx)
+/*
+ * We have some data, such as saved website or IMAP passwords that the
+ * client has in profile on-disk.  This needs to be decrypted.  This
+ * version gives the server the data over the network (protected by
+ * the X.509 certificate and public key encryption, and asks that it
+ * be decrypted returned for short-term use, protected only by the
+ * negotiated transport encryption.
+ *
+ * The data is NOT stored in the LSA, but a X.509 certificate, public
+ * and private keys used to encrypt the data will be stored.  There is
+ * only one active encryption key pair and certificate per domain, it
+ * is pointed at with G$BCKUPKEY_PREFERRED in the LSA secrets store.
+ *
+ * The potentially multiple valid decrypting key pairs are in turn
+ * stored in the LSA secrets store as G$BCKUPKEY_keyGuidString.
+ *
+ */
+static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
+                                           TALLOC_CTX *mem_ctx,
+                                           struct bkrp_BackupKey *r,
+                                           struct ldb_context *ldb_ctx)
 {
+       struct auth_session_info *session_info =
+               dcesrv_call_session_info(dce_call);
        struct bkrp_client_side_wrapped uncrypt_request;
        DATA_BLOB blob;
        enum ndr_err_code ndr_err;
        char *guid_string;
        char *cert_secret_name;
-       DATA_BLOB secret;
-       DATA_BLOB *uncrypted;
+       DATA_BLOB lsa_secret;
+       DATA_BLOB *uncrypted_data = NULL;
        NTSTATUS status;
+       uint32_t requested_version;
 
        blob.data = r->in.data_in;
        blob.length = r->in.data_in_len;
 
-       if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
-               return WERR_INVALID_PARAM;
+       if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       /*
+        * We check for the version here, so we can actually print the
+        * message as we are unlikely to parse it with NDR.
+        */
+       requested_version = IVAL(r->in.data_in, 0);
+       if ((requested_version != BACKUPKEY_CLIENT_WRAP_VERSION2)
+           && (requested_version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
+               DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", requested_version));
+               return WERR_INVALID_PARAMETER;
        }
 
        ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &uncrypt_request,
                                       (ndr_pull_flags_fn_t)ndr_pull_bkrp_client_side_wrapped);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               return WERR_INVALID_PARAM;
-       }
-
-       if (uncrypt_request.version < BACKUPKEY_MIN_VERSION) {
                return WERR_INVALID_PARAMETER;
        }
 
-       if (uncrypt_request.version > BACKUPKEY_MAX_VERSION) {
+       if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
+           && (uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION3)) {
+               DEBUG(1, ("Request for unknown BackupKey sub-protocol %d\n", uncrypt_request.version));
                return WERR_INVALID_PARAMETER;
        }
 
        guid_string = GUID_string(mem_ctx, &uncrypt_request.guid);
        if (guid_string == NULL) {
-               return WERR_NOMEM;
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
        cert_secret_name = talloc_asprintf(mem_ctx,
                                           "BCKUPKEY_%s",
                                           guid_string);
        if (cert_secret_name == NULL) {
-               return WERR_NOMEM;
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
        status = get_lsa_secret(mem_ctx,
                                ldb_ctx,
                                cert_secret_name,
-                               &secret);
+                               &lsa_secret);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(10, ("Error while fetching secret %s\n", cert_secret_name));
-               if (NT_STATUS_EQUAL(status,NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
-                       /* we do not have the real secret attribute */
-                       return WERR_INVALID_PARAMETER;
-               } else {
-                       return WERR_FILE_NOT_FOUND;
-               }
-       }
-
-       if (secret.length != 0) {
-               hx509_context hctx;
+               return WERR_INVALID_DATA;
+       } else if (lsa_secret.length == 0) {
+               /* we do not have the real secret attribute, like if we are an RODC */
+               return WERR_INVALID_PARAMETER;
+       } else {
                struct bkrp_exported_RSA_key_pair keypair;
-               hx509_private_key pk;
-               uint32_t i, res;
-               struct dom_sid *access_sid = NULL;
-               heim_octet_string reversed_secret;
-               heim_octet_string uncrypted_secret;
-               AlgorithmIdentifier alg;
-               struct dom_sid *caller_sid;
+               gnutls_privkey_t privkey = NULL;
+               gnutls_datum_t reversed_secret;
+               gnutls_datum_t uncrypted_secret;
+               uint32_t i;
                DATA_BLOB blob_us;
                WERROR werr;
+               int rc;
 
-               ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
+               ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair, (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        DEBUG(2, ("Unable to parse the ndr encoded cert in key %s\n", cert_secret_name));
                        return WERR_FILE_NOT_FOUND;
                }
 
-               status = get_pk_from_raw_keypair_params(mem_ctx, &keypair, &pk);
+               status = get_pk_from_raw_keypair_params(mem_ctx,
+                                                       &keypair,
+                                                       &privkey);
                if (!NT_STATUS_IS_OK(status)) {
                        return WERR_INTERNAL_ERROR;
                }
@@ -621,8 +615,8 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
                reversed_secret.data = talloc_array(mem_ctx, uint8_t,
                                                    uncrypt_request.encrypted_secret_len);
                if (reversed_secret.data == NULL) {
-                       hx509_private_key_free(&pk);
-                       return WERR_NOMEM;
+                       gnutls_privkey_deinit(privkey);
+                       return WERR_NOT_ENOUGH_MEMORY;
                }
 
                /* The secret has to be reversed ... */
@@ -631,31 +625,30 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
                        uint8_t *uncrypt = uncrypt_request.encrypted_secret;
                        reversed[i] = uncrypt[uncrypt_request.encrypted_secret_len - 1 - i];
                }
-               reversed_secret.length = uncrypt_request.encrypted_secret_len;
+               reversed_secret.size = uncrypt_request.encrypted_secret_len;
 
                /*
                 * Let's try to decrypt the secret now that
                 * we have the private key ...
                 */
-               hx509_context_init(&hctx);
-               res = hx509_private_key_private_decrypt(hctx, &reversed_secret,
-                                                        &alg.algorithm, pk,
-                                                        &uncrypted_secret);
-               hx509_context_free(&hctx);
-               hx509_private_key_free(&pk);
-               if (res != 0) {
+               rc = gnutls_privkey_decrypt_data(privkey,
+                                                0,
+                                                &reversed_secret,
+                                                &uncrypted_secret);
+               gnutls_privkey_deinit(privkey);
+               if (rc != GNUTLS_E_SUCCESS) {
                        /* We are not able to decrypt the secret, looks like something is wrong */
-                       return WERR_INVALID_DATA;
+                       return WERR_INVALID_PARAMETER;
                }
                blob_us.data = uncrypted_secret.data;
-               blob_us.length = uncrypted_secret.length;
+               blob_us.length = uncrypted_secret.size;
 
                if (uncrypt_request.version == 2) {
                        struct bkrp_encrypted_secret_v2 uncrypted_secretv2;
 
                        ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv2,
                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v2);
-                       der_free_octet_string(&uncrypted_secret);
+                       gnutls_free(uncrypted_secret.data);
                        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                                /* Unable to unmarshall */
                                return WERR_INVALID_DATA;
@@ -669,25 +662,24 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
                                                           uncrypted_secretv2.payload_key,
                                                           uncrypt_request.access_check,
                                                           uncrypt_request.access_check_len,
-                                                          &access_sid);
+                                                          session_info);
                        if (!W_ERROR_IS_OK(werr)) {
                                return werr;
                        }
-                       uncrypted = talloc(mem_ctx, DATA_BLOB);
-                       if (uncrypted == NULL) {
+                       uncrypted_data = talloc(mem_ctx, DATA_BLOB);
+                       if (uncrypted_data == NULL) {
                                return WERR_INVALID_DATA;
                        }
 
-                       uncrypted->data = uncrypted_secretv2.secret;
-                       uncrypted->length = uncrypted_secretv2.secret_len;
+                       uncrypted_data->data = uncrypted_secretv2.secret;
+                       uncrypted_data->length = uncrypted_secretv2.secret_len;
                }
                if (uncrypt_request.version == 3) {
                        struct bkrp_encrypted_secret_v3 uncrypted_secretv3;
 
                        ndr_err = ndr_pull_struct_blob(&blob_us, mem_ctx, &uncrypted_secretv3,
                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_encrypted_secret_v3);
-
-                       der_free_octet_string(&uncrypted_secret);
+                       gnutls_free(uncrypted_secret.data);
                        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                                /* Unable to unmarshall */
                                return WERR_INVALID_DATA;
@@ -700,29 +692,31 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
                                return WERR_INVALID_DATA;
                        }
 
+                       /*
+                        * Confirm that the caller is permitted to
+                        * read this particular data.  Because one key
+                        * pair is used per domain, the caller could
+                        * have stolen the profile data on-disk and
+                        * would otherwise be able to read the
+                        * passwords.
+                        */
+
                        werr = get_and_verify_access_check(mem_ctx, 3,
                                                           uncrypted_secretv3.payload_key,
                                                           uncrypt_request.access_check,
                                                           uncrypt_request.access_check_len,
-                                                          &access_sid);
+                                                          session_info);
                        if (!W_ERROR_IS_OK(werr)) {
                                return werr;
                        }
 
-                       uncrypted = talloc(mem_ctx, DATA_BLOB);
-                       if (uncrypted == NULL) {
+                       uncrypted_data = talloc(mem_ctx, DATA_BLOB);
+                       if (uncrypted_data == NULL) {
                                return WERR_INVALID_DATA;
                        }
 
-                       uncrypted->data = uncrypted_secretv3.secret;
-                       uncrypted->length = uncrypted_secretv3.secret_len;
-               }
-
-               caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
-
-               if (!dom_sid_equal(caller_sid, access_sid)) {
-                       talloc_free(uncrypted);
-                       return WERR_INVALID_ACCESS;
+                       uncrypted_data->data = uncrypted_secretv3.secret;
+                       uncrypted_data->length = uncrypted_secretv3.secret_len;
                }
 
                /*
@@ -733,7 +727,7 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
                 */
        }
 
-       if (uncrypted->data == NULL) {
+       if (uncrypted_data->data == NULL) {
                return WERR_INVALID_DATA;
        }
 
@@ -742,369 +736,390 @@ static WERROR bkrp_do_uncrypt_client_wrap_key(struct dcesrv_call_state *dce_call
         * parent structure is just an array of bytes it a lot of work
         * work just prepending 4 bytes
         */
-       *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted->length + 4);
+       *(r->out.data_out) = talloc_zero_array(mem_ctx, uint8_t, uncrypted_data->length + 4);
        W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
-       memcpy(4+*(r->out.data_out), uncrypted->data, uncrypted->length);
-       *(r->out.data_out_len) = uncrypted->length + 4;
+       memcpy(4+*(r->out.data_out), uncrypted_data->data, uncrypted_data->length);
+       *(r->out.data_out_len) = uncrypted_data->length + 4;
 
        return WERR_OK;
 }
 
-static WERROR create_heimdal_rsa_key(TALLOC_CTX *ctx, hx509_context *hctx,
-                                    hx509_private_key *pk, RSA **_rsa)
+static DATA_BLOB *reverse_and_get_blob(TALLOC_CTX *mem_ctx,
+                                      gnutls_datum_t *datum)
 {
-       BIGNUM *pub_expo;
-       RSA *rsa;
-       int ret;
-       uint8_t *p0, *p;
-       size_t len;
-       int bits = 2048;
-       int RSA_returned_bits;
+       DATA_BLOB *blob;
+       size_t i;
 
-       *_rsa = NULL;
-
-       pub_expo = BN_new();
-       if(pub_expo == NULL) {
-               return WERR_INTERNAL_ERROR;
+       blob = talloc(mem_ctx, DATA_BLOB);
+       if (blob == NULL) {
+               return NULL;
        }
 
-       /* set the public expo to 65537 like everyone */
-       BN_set_word(pub_expo, 0x10001);
-
-       rsa = RSA_new();
-       if(rsa == NULL) {
-               BN_free(pub_expo);
-               return WERR_INTERNAL_ERROR;
+       blob->length = datum->size;
+       if (datum->data[0] == '\0') {
+               /* The datum has a leading byte zero, skip it */
+               blob->length = datum->size - 1;
+       }
+       blob->data = talloc_zero_array(mem_ctx, uint8_t, blob->length);
+       if (blob->data == NULL) {
+               talloc_free(blob);
+               return NULL;
        }
 
-       while (RSA_returned_bits != bits) {
-               ret = RSA_generate_key_ex(rsa, bits, pub_expo, NULL);
-               if(ret != 1) {
-                       RSA_free(rsa);
-                       BN_free(pub_expo);
-                       return WERR_INTERNAL_ERROR;
-               }
-               RSA_returned_bits = BN_num_bits(rsa->n);
-               DEBUG(6, ("RSA_generate_key_ex returned %d Bits\n", RSA_returned_bits));
+       for (i = 0; i < blob->length; i++) {
+               blob->data[i] = datum->data[datum->size - i - 1];
        }
-       BN_free(pub_expo);
 
-       len = i2d_RSAPrivateKey(rsa, NULL);
-       if (len < 1) {
-               RSA_free(rsa);
+       return blob;
+}
+
+static WERROR create_privkey_rsa(gnutls_privkey_t *pk)
+{
+       int bits = 2048;
+       gnutls_x509_privkey_t x509_privkey = NULL;
+       gnutls_privkey_t privkey = NULL;
+       int rc;
+
+       rc = gnutls_x509_privkey_init(&x509_privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
                return WERR_INTERNAL_ERROR;
        }
 
-       p0 = p = talloc_array(ctx, uint8_t, len);
-       if (p == NULL) {
-               RSA_free(rsa);
+       rc = gnutls_x509_privkey_generate(x509_privkey,
+                                         GNUTLS_PK_RSA,
+                                         bits,
+                                         0);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_generate failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_privkey);
                return WERR_INTERNAL_ERROR;
        }
 
-       len = i2d_RSAPrivateKey(rsa, &p);
-       if (len < 1) {
-               RSA_free(rsa);
-               talloc_free(p0);
+       rc = gnutls_privkey_init(&privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_privkey);
                return WERR_INTERNAL_ERROR;
        }
 
-       /*
-        * To dump the key we can use :
-        * rk_dumpdata("h5lkey", p0, len);
-        */
-       ret = hx509_parse_private_key(*hctx, &_hx509_signature_rsa_with_var_num ,
-                                      p0, len, HX509_KEY_FORMAT_DER, pk);
-       memset(p0, 0, len);
-       talloc_free(p0);
-       if (ret !=0) {
-               RSA_free(rsa);
+       rc = gnutls_privkey_import_x509(privkey,
+                                       x509_privkey,
+                                       GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_privkey_import_x509 failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_privkey);
                return WERR_INTERNAL_ERROR;
        }
 
-       *_rsa = rsa;
+       *pk = privkey;
+
        return WERR_OK;
 }
 
-static WERROR self_sign_cert(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
-                               time_t lifetime, hx509_private_key *private_key,
-                               hx509_cert *cert, DATA_BLOB *guidblob)
+static WERROR self_sign_cert(TALLOC_CTX *mem_ctx,
+                            time_t lifetime,
+                            const char *dn,
+                            gnutls_privkey_t issuer_privkey,
+                            gnutls_x509_crt_t *certificate,
+                            DATA_BLOB *guidblob)
 {
-       SubjectPublicKeyInfo spki;
-       hx509_name subject = NULL;
-       hx509_ca_tbs tbs;
-       struct heim_bit_string uniqueid;
-       struct heim_integer serialnumber;
-       int ret, i;
-
-       uniqueid.data = talloc_memdup(ctx, guidblob->data, guidblob->length);
-       if (uniqueid.data == NULL) {
-               return WERR_NOMEM;
-       }
-       /* uniqueid is a bit string in which each byte represent 1 bit (1 or 0)
-        * so as 1 byte is 8 bits we need to provision 8 times more space as in the
-        * blob
-        */
-       uniqueid.length = 8 * guidblob->length;
-
-       serialnumber.data = talloc_array(ctx, uint8_t,
-                                           guidblob->length);
-       if (serialnumber.data == NULL) {
-               talloc_free(uniqueid.data);
-               return WERR_NOMEM;
+       gnutls_datum_t unique_id;
+       gnutls_datum_t serial_number;
+       gnutls_x509_crt_t issuer_cert;
+       gnutls_x509_privkey_t x509_issuer_privkey;
+       time_t activation = time(NULL);
+       time_t expiry = activation + lifetime;
+       const char *error_string;
+       uint8_t *reversed;
+       size_t i;
+       int rc;
+
+       unique_id.size = guidblob->length;
+       unique_id.data = talloc_memdup(mem_ctx,
+                                      guidblob->data,
+                                      guidblob->length);
+       if (unique_id.data == NULL) {
+               return WERR_NOT_ENOUGH_MEMORY;
+       }
+
+       reversed = talloc_array(mem_ctx, uint8_t, guidblob->length);
+       if (reversed == NULL) {
+               talloc_free(unique_id.data);
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
        /* Native AD generates certificates with serialnumber in reversed notation */
        for (i = 0; i < guidblob->length; i++) {
-               uint8_t *reversed = (uint8_t *)serialnumber.data;
                uint8_t *uncrypt = guidblob->data;
-               reversed[i] = uncrypt[guidblob->length - 1 - i];
+               reversed[i] = uncrypt[guidblob->length - i - 1];
        }
-       serialnumber.length = guidblob->length;
-       serialnumber.negative = 0;
+       serial_number.size = guidblob->length;
+       serial_number.data = reversed;
 
-       memset(&spki, 0, sizeof(spki));
-
-       ret = hx509_request_get_name(*hctx, *req, &subject);
-       if (ret !=0) {
-               goto fail_subject;
-       }
-       ret = hx509_request_get_SubjectPublicKeyInfo(*hctx, *req, &spki);
-       if (ret !=0) {
-               goto fail_spki;
+       /* Create certificate to sign */
+       rc = gnutls_x509_crt_init(&issuer_cert);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_init failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
-       ret = hx509_ca_tbs_init(*hctx, &tbs);
-       if (ret !=0) {
-               goto fail_tbs;
+       rc = gnutls_x509_crt_set_dn(issuer_cert, dn, &error_string);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_dn failed - %s (%s)\n",
+                       gnutls_strerror(rc),
+                       error_string);
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
 
-       ret = hx509_ca_tbs_set_spki(*hctx, tbs, &spki);
-       if (ret !=0) {
-               goto fail;
-       }
-       ret = hx509_ca_tbs_set_subject(*hctx, tbs, subject);
-       if (ret !=0) {
-               goto fail;
-       }
-       ret = hx509_ca_tbs_set_ca(*hctx, tbs, 1);
-       if (ret !=0) {
-               goto fail;
-       }
-       ret = hx509_ca_tbs_set_notAfter_lifetime(*hctx, tbs, lifetime);
-       if (ret !=0) {
-               goto fail;
-       }
-       ret = hx509_ca_tbs_set_unique(*hctx, tbs, &uniqueid, &uniqueid);
-       if (ret !=0) {
-               goto fail;
-       }
-       ret = hx509_ca_tbs_set_serialnumber(*hctx, tbs, &serialnumber);
-       if (ret !=0) {
-               goto fail;
+       rc = gnutls_x509_crt_set_issuer_dn(issuer_cert, dn, &error_string);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_issuer_dn failed - %s (%s)\n",
+                       gnutls_strerror(rc),
+                       error_string);
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
-       ret = hx509_ca_sign_self(*hctx, tbs, *private_key, cert);
-       if (ret !=0) {
-               goto fail;
+
+       /* Get x509 privkey for subjectPublicKeyInfo */
+       rc = gnutls_x509_privkey_init(&x509_issuer_privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
-       hx509_name_free(&subject);
-       free_SubjectPublicKeyInfo(&spki);
-       hx509_ca_tbs_free(&tbs);
 
-       return WERR_OK;
+       rc = gnutls_privkey_export_x509(issuer_privkey,
+                                       &x509_issuer_privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_privkey_init failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_privkey_deinit(x509_issuer_privkey);
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
+       }
 
-fail:
-       hx509_ca_tbs_free(&tbs);
-fail_tbs:
-       free_SubjectPublicKeyInfo(&spki);
-fail_spki:
-       hx509_name_free(&subject);
-fail_subject:
-       talloc_free(uniqueid.data);
-       talloc_free(serialnumber.data);
-       return WERR_INTERNAL_ERROR;
-}
+       /* Set subjectPublicKeyInfo */
+       rc = gnutls_x509_crt_set_key(issuer_cert, x509_issuer_privkey);
+       gnutls_x509_privkey_deinit(x509_issuer_privkey);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_pubkey failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
+       }
 
-static WERROR create_req(TALLOC_CTX *ctx, hx509_context *hctx, hx509_request *req,
-                        hx509_private_key *signer,RSA **rsa, const char *dn)
-{
-       int ret;
-       SubjectPublicKeyInfo key;
+       rc = gnutls_x509_crt_set_activation_time(issuer_cert, activation);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_activation_time failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
+       }
 
-       hx509_name name;
-       WERROR werr;
+       rc = gnutls_x509_crt_set_expiration_time(issuer_cert, expiry);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_expiration_time failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
+       }
 
-       werr = create_heimdal_rsa_key(ctx, hctx, signer, rsa);
-       if (!W_ERROR_IS_OK(werr)) {
-               return werr;
+       rc = gnutls_x509_crt_set_version(issuer_cert, 3);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_version failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
 
-       hx509_request_init(*hctx, req);
-       ret = hx509_parse_name(*hctx, dn, &name);
-       if (ret != 0) {
-               RSA_free(*rsa);
-               hx509_private_key_free(signer);
-               hx509_request_free(req);
-               hx509_name_free(&name);
-               return WERR_INTERNAL_ERROR;
+       rc = gnutls_x509_crt_set_subject_unique_id(issuer_cert,
+                                                  unique_id.data,
+                                                  unique_id.size);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_subject_key_id failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
 
-       ret = hx509_request_set_name(*hctx, *req, name);
-       if (ret != 0) {
-               RSA_free(*rsa);
-               hx509_private_key_free(signer);
-               hx509_request_free(req);
-               hx509_name_free(&name);
-               return WERR_INTERNAL_ERROR;
+       rc = gnutls_x509_crt_set_issuer_unique_id(issuer_cert,
+                                                 unique_id.data,
+                                                 unique_id.size);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_issuer_unique_id failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
-       hx509_name_free(&name);
 
-       ret = hx509_private_key2SPKI(*hctx, *signer, &key);
-       if (ret != 0) {
-               RSA_free(*rsa);
-               hx509_private_key_free(signer);
-               hx509_request_free(req);
-               return WERR_INTERNAL_ERROR;
+       rc = gnutls_x509_crt_set_serial(issuer_cert,
+                                       serial_number.data,
+                                       serial_number.size);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_set_serial failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_x509_crt_deinit(issuer_cert);
+               return WERR_INVALID_PARAMETER;
        }
-       ret = hx509_request_set_SubjectPublicKeyInfo(*hctx, *req, &key);
-       if (ret != 0) {
-               RSA_free(*rsa);
-               hx509_private_key_free(signer);
-               free_SubjectPublicKeyInfo(&key);
-               hx509_request_free(req);
-               return WERR_INTERNAL_ERROR;
+
+       rc = gnutls_x509_crt_privkey_sign(issuer_cert,
+                                         issuer_cert,
+                                         issuer_privkey,
+                                         GNUTLS_DIG_SHA1,
+                                         0);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_privkey_sign failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_INVALID_PARAMETER;
        }
 
-       free_SubjectPublicKeyInfo(&key);
+       *certificate = issuer_cert;
 
        return WERR_OK;
 }
 
 /* Return an error when we fail to generate a certificate */
-static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_call, struct ldb_context *ldb_ctx, const char *dn)
+static WERROR generate_bkrp_cert(TALLOC_CTX *mem_ctx,
+                                struct dcesrv_call_state *dce_call,
+                                struct ldb_context *ldb_ctx,
+                                const char *dn)
 {
-       heim_octet_string data;
        WERROR werr;
-       RSA *rsa;
-       hx509_context hctx;
-       hx509_private_key pk;
-       hx509_request req;
-       hx509_cert cert;
+       gnutls_privkey_t issuer_privkey = NULL;
+       gnutls_x509_crt_t cert = NULL;
+       gnutls_datum_t cert_blob;
+       gnutls_datum_t m, e, d, p, q, u, e1, e2;
        DATA_BLOB blob;
        DATA_BLOB blobkeypair;
        DATA_BLOB *tmp;
-       int ret;
        bool ok = true;
        struct GUID guid = GUID_random();
        NTSTATUS status;
        char *secret_name;
        struct bkrp_exported_RSA_key_pair keypair;
        enum ndr_err_code ndr_err;
-       uint32_t nb_seconds_validity = 3600 * 24 * 365;
+       time_t nb_seconds_validity = 3600 * 24 * 365;
+       int rc;
 
        DEBUG(6, ("Trying to generate a certificate\n"));
-       hx509_context_init(&hctx);
-       werr = create_req(ctx, &hctx, &req, &pk, &rsa, dn);
+       werr = create_privkey_rsa(&issuer_privkey);
        if (!W_ERROR_IS_OK(werr)) {
-               hx509_context_free(&hctx);
                return werr;
        }
 
-       status = GUID_to_ndr_blob(&guid, ctx, &blob);
+       status = GUID_to_ndr_blob(&guid, mem_ctx, &blob);
        if (!NT_STATUS_IS_OK(status)) {
-               hx509_context_free(&hctx);
-               hx509_private_key_free(&pk);
-               RSA_free(rsa);
+               gnutls_privkey_deinit(issuer_privkey);
                return WERR_INVALID_DATA;
        }
 
-       werr = self_sign_cert(ctx, &hctx, &req, nb_seconds_validity, &pk, &cert, &blob);
+       werr = self_sign_cert(mem_ctx,
+                             nb_seconds_validity,
+                             dn,
+                             issuer_privkey,
+                             &cert,
+                             &blob);
        if (!W_ERROR_IS_OK(werr)) {
-               hx509_private_key_free(&pk);
-               hx509_context_free(&hctx);
+               gnutls_privkey_deinit(issuer_privkey);
                return WERR_INVALID_DATA;
        }
 
-       ret = hx509_cert_binary(hctx, cert, &data);
-       if (ret !=0) {
-               hx509_cert_free(cert);
-               hx509_private_key_free(&pk);
-               hx509_context_free(&hctx);
+       rc = gnutls_x509_crt_export2(cert, GNUTLS_X509_FMT_DER, &cert_blob);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_x509_crt_export2 failed - %s\n",
+                       gnutls_strerror(rc));
+               gnutls_privkey_deinit(issuer_privkey);
+               gnutls_x509_crt_deinit(cert);
                return WERR_INVALID_DATA;
        }
 
-       keypair.cert.data = talloc_memdup(ctx, data.data, data.length);
-       keypair.cert.length = data.length;
+       keypair.cert.length = cert_blob.size;
+       keypair.cert.data = talloc_memdup(mem_ctx, cert_blob.data, cert_blob.size);
+       gnutls_x509_crt_deinit(cert);
+       gnutls_free(cert_blob.data);
+       if (keypair.cert.data == NULL) {
+               gnutls_privkey_deinit(issuer_privkey);
+               return WERR_NOT_ENOUGH_MEMORY;
+       }
+
+       rc = gnutls_privkey_export_rsa_raw(issuer_privkey,
+                                          &m,
+                                          &e,
+                                          &d,
+                                          &p,
+                                          &q,
+                                          &u,
+                                          &e1,
+                                          &e2);
+       if (rc != GNUTLS_E_SUCCESS) {
+               gnutls_privkey_deinit(issuer_privkey);
+               return WERR_INVALID_DATA;
+       }
 
        /*
         * Heimdal's bignum are big endian and the
         * structure expect it to be in little endian
         * so we reverse the buffer to make it work
         */
-       tmp = reverse_and_get_blob(ctx, rsa->e);
+       tmp = reverse_and_get_blob(mem_ctx, &e);
        if (tmp == NULL) {
                ok = false;
        } else {
-               keypair.public_exponent = *tmp;
                SMB_ASSERT(tmp->length <= 4);
-               /*
-                * The value is now in little endian but if can happen that the length is
-                * less than 4 bytes.
-                * So if we have less than 4 bytes we pad with zeros so that it correctly
-                * fit into the structure.
-                */
-               if (tmp->length < 4) {
-                       /*
-                        * We need the expo to fit 4 bytes
-                        */
-                       keypair.public_exponent.data = talloc_zero_array(ctx, uint8_t, 4);
-                       memcpy(keypair.public_exponent.data, tmp->data, tmp->length);
-                       keypair.public_exponent.length = 4;
-               }
+               keypair.public_exponent = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->d);
+       tmp = reverse_and_get_blob(mem_ctx, &d);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.private_exponent = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->n);
+       tmp = reverse_and_get_blob(mem_ctx, &m);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.modulus = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->p);
+       tmp = reverse_and_get_blob(mem_ctx, &p);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.prime1 = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->q);
+       tmp = reverse_and_get_blob(mem_ctx, &q);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.prime2 = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->dmp1);
+       tmp = reverse_and_get_blob(mem_ctx, &e1);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.exponent1 = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->dmq1);
+       tmp = reverse_and_get_blob(mem_ctx, &e2);
        if (tmp == NULL) {
                ok = false;
        } else {
                keypair.exponent2 = *tmp;
        }
 
-       tmp = reverse_and_get_blob(ctx,rsa->iqmp);
+       tmp = reverse_and_get_blob(mem_ctx, &u);
        if (tmp == NULL) {
                ok = false;
        } else {
@@ -1113,60 +1128,46 @@ static WERROR generate_bkrp_cert(TALLOC_CTX *ctx, struct dcesrv_call_state *dce_
 
        /* One of the keypair allocation was wrong */
        if (ok == false) {
-               der_free_octet_string(&data);
-               hx509_cert_free(cert);
-               hx509_private_key_free(&pk);
-               hx509_context_free(&hctx);
-               RSA_free(rsa);
+               gnutls_privkey_deinit(issuer_privkey);
                return WERR_INVALID_DATA;
        }
+
        keypair.certificate_len = keypair.cert.length;
-       ndr_err = ndr_push_struct_blob(&blobkeypair, ctx, &keypair, (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
+       ndr_err = ndr_push_struct_blob(&blobkeypair,
+                                      mem_ctx,
+                                      &keypair,
+                                      (ndr_push_flags_fn_t)ndr_push_bkrp_exported_RSA_key_pair);
+       gnutls_privkey_deinit(issuer_privkey);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               der_free_octet_string(&data);
-               hx509_cert_free(cert);
-               hx509_private_key_free(&pk);
-               hx509_context_free(&hctx);
-               RSA_free(rsa);
                return WERR_INVALID_DATA;
        }
 
-       secret_name = talloc_asprintf(ctx, "BCKUPKEY_%s", GUID_string(ctx, &guid));
+       secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", GUID_string(mem_ctx, &guid));
        if (secret_name == NULL) {
-               der_free_octet_string(&data);
-               hx509_cert_free(cert);
-               hx509_private_key_free(&pk);
-               hx509_context_free(&hctx);
-               RSA_free(rsa);
                return WERR_OUTOFMEMORY;
        }
 
-       status = set_lsa_secret(ctx, ldb_ctx, secret_name, &blobkeypair);
+       status = set_lsa_secret(mem_ctx, ldb_ctx, secret_name, &blobkeypair);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(2, ("Failed to save the secret %s\n", secret_name));
        }
        talloc_free(secret_name);
 
-       GUID_to_ndr_blob(&guid, ctx, &blob);
-       status = set_lsa_secret(ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
+       GUID_to_ndr_blob(&guid, mem_ctx, &blob);
+       status = set_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_PREFERRED", &blob);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(2, ("Failed to save the secret BCKUPKEY_PREFERRED\n"));
        }
 
-       der_free_octet_string(&data);
-       hx509_cert_free(cert);
-       hx509_private_key_free(&pk);
-       hx509_context_free(&hctx);
-       RSA_free(rsa);
        return WERR_OK;
 }
 
-static WERROR bkrp_do_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
-               struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
+static WERROR bkrp_retrieve_client_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
+                                           struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
 {
        struct GUID guid;
        char *guid_string;
-       DATA_BLOB secret;
+       DATA_BLOB lsa_secret;
        enum ndr_err_code ndr_err;
        NTSTATUS status;
 
@@ -1178,41 +1179,38 @@ static WERROR bkrp_do_retrieve_client_wrap_key(struct dcesrv_call_state *dce_cal
        status = get_lsa_secret(mem_ctx,
                                ldb_ctx,
                                "BCKUPKEY_PREFERRED",
-                               &secret);
-       if (!NT_STATUS_IS_OK(status)) {
-               DEBUG(10, ("Error while fetching secret BCKUPKEY_PREFERRED\n"));
-               if (!NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
-                       /* Ok we can be in this case if there was no certs */
-                       struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
-                       char *dn = talloc_asprintf(mem_ctx, "CN=%s",
-                                                       lpcfg_realm(lp_ctx));
-
-                       WERROR werr =  generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
-                       if (!W_ERROR_IS_OK(werr)) {
-                               return WERR_INVALID_PARAMETER;
-                       }
-                       status = get_lsa_secret(mem_ctx,
+                               &lsa_secret);
+       if (NT_STATUS_EQUAL(status, NT_STATUS_RESOURCE_NAME_NOT_FOUND)) {
+               /* Ok we can be in this case if there was no certs */
+               struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
+               char *dn = talloc_asprintf(mem_ctx, "CN=%s",
+                                          lpcfg_realm(lp_ctx));
+
+               WERROR werr =  generate_bkrp_cert(mem_ctx, dce_call, ldb_ctx, dn);
+               if (!W_ERROR_IS_OK(werr)) {
+                       return WERR_INVALID_PARAMETER;
+               }
+               status = get_lsa_secret(mem_ctx,
                                        ldb_ctx,
                                        "BCKUPKEY_PREFERRED",
-                                       &secret);
+                                       &lsa_secret);
 
-                       if (!NT_STATUS_IS_OK(status)) {
-                               /* Ok we really don't manage to get this certs ...*/
-                               DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
-                               return WERR_FILE_NOT_FOUND;
-                       }
-               } else {
-                       /* In theory we should NEVER reach this point as it
-                          should only appear in a rodc server */
-                       /* we do not have the real secret attribute */
-                       return WERR_INVALID_PARAMETER;
+               if (!NT_STATUS_IS_OK(status)) {
+                       /* Ok we really don't manage to get this certs ...*/
+                       DEBUG(2, ("Unable to locate BCKUPKEY_PREFERRED after cert generation\n"));
+                       return WERR_FILE_NOT_FOUND;
                }
+       } else if (!NT_STATUS_IS_OK(status)) {
+               return WERR_INTERNAL_ERROR;
        }
 
-       if (secret.length != 0) {
+       if (lsa_secret.length == 0) {
+               DEBUG(1, ("No secret in BCKUPKEY_PREFERRED, are we an undetected RODC?\n"));
+               return WERR_INTERNAL_ERROR;
+       } else {
                char *cert_secret_name;
 
-               status = GUID_from_ndr_blob(&secret, &guid);
+               status = GUID_from_ndr_blob(&lsa_secret, &guid);
                if (!NT_STATUS_IS_OK(status)) {
                        return WERR_FILE_NOT_FOUND;
                }
@@ -1231,14 +1229,14 @@ static WERROR bkrp_do_retrieve_client_wrap_key(struct dcesrv_call_state *dce_cal
                status = get_lsa_secret(mem_ctx,
                                        ldb_ctx,
                                        cert_secret_name,
-                                       &secret);
+                                       &lsa_secret);
                if (!NT_STATUS_IS_OK(status)) {
                        return WERR_FILE_NOT_FOUND;
                }
 
-               if (secret.length != 0) {
+               if (lsa_secret.length != 0) {
                        struct bkrp_exported_RSA_key_pair keypair;
-                       ndr_err = ndr_pull_struct_blob(&secret, mem_ctx, &keypair,
+                       ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, &keypair,
                                        (ndr_pull_flags_fn_t)ndr_pull_bkrp_exported_RSA_key_pair);
                        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                                return WERR_FILE_NOT_FOUND;
@@ -1248,39 +1246,529 @@ static WERROR bkrp_do_retrieve_client_wrap_key(struct dcesrv_call_state *dce_cal
                        W_ERROR_HAVE_NO_MEMORY(*(r->out.data_out));
                        return WERR_OK;
                } else {
-                       DEBUG(10, ("No or broken secret called %s\n", cert_secret_name));
-                       return WERR_FILE_NOT_FOUND;
+                       DEBUG(1, ("No or broken secret called %s\n", cert_secret_name));
+                       return WERR_INTERNAL_ERROR;
                }
-       } else {
-               DEBUG(10, ("No secret BCKUPKEY_PREFERRED\n"));
-               return WERR_FILE_NOT_FOUND;
        }
 
        return WERR_NOT_SUPPORTED;
 }
 
-static WERROR bkrp_do_uncrypt_server_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
-               struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
+static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context *ldb_ctx)
 {
-       return WERR_NOT_SUPPORTED;
+       struct GUID guid = GUID_random();
+       enum ndr_err_code ndr_err;
+       DATA_BLOB blob_wrap_key, guid_blob;
+       struct bkrp_dc_serverwrap_key wrap_key;
+       NTSTATUS status;
+       char *secret_name;
+       TALLOC_CTX *frame = talloc_stackframe();
+
+       generate_random_buffer(wrap_key.key, sizeof(wrap_key.key));
+
+       ndr_err = ndr_push_struct_blob(&blob_wrap_key, ctx, &wrap_key, (ndr_push_flags_fn_t)ndr_push_bkrp_dc_serverwrap_key);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               TALLOC_FREE(frame);
+               return WERR_INVALID_DATA;
+       }
+
+       secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
+       if (secret_name == NULL) {
+               TALLOC_FREE(frame);
+               return WERR_NOT_ENOUGH_MEMORY;
+       }
+
+       status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(2, ("Failed to save the secret %s\n", secret_name));
+               TALLOC_FREE(frame);
+               return WERR_INTERNAL_ERROR;
+       }
+
+       status = GUID_to_ndr_blob(&guid, frame, &guid_blob);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(2, ("Failed to save the secret %s\n", secret_name));
+               TALLOC_FREE(frame);
+       }
+
+       status = set_lsa_secret(frame, ldb_ctx, "BCKUPKEY_P", &guid_blob);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(2, ("Failed to save the secret %s\n", secret_name));
+               TALLOC_FREE(frame);
+               return WERR_INTERNAL_ERROR;
+       }
+
+       TALLOC_FREE(frame);
+
+       return WERR_OK;
 }
 
-static WERROR bkrp_do_retrieve_server_wrap_key(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
-               struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
+/*
+ * Find the specified decryption keys from the LSA secrets store as
+ * G$BCKUPKEY_keyGuidString.
+ */
+
+static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_context *ldb_ctx,
+                                              struct bkrp_dc_serverwrap_key *server_key,
+                                              struct GUID *guid)
 {
-       return WERR_NOT_SUPPORTED;
+       NTSTATUS status;
+       DATA_BLOB lsa_secret;
+       char *secret_name;
+       char *guid_string;
+       enum ndr_err_code ndr_err;
+
+       guid_string = GUID_string(mem_ctx, guid);
+       if (guid_string == NULL) {
+               /* We return file not found because the client
+                * expect this error
+                */
+               return WERR_FILE_NOT_FOUND;
+       }
+
+       secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
+       if (secret_name == NULL) {
+               return WERR_NOT_ENOUGH_MEMORY;
+       }
+
+       status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("Error while fetching secret %s\n", secret_name));
+               return WERR_INVALID_DATA;
+       }
+       if (lsa_secret.length == 0) {
+               /* RODC case, we do not have secrets locally */
+               DEBUG(1, ("Unable to fetch value for secret %s, are we an undetected RODC?\n",
+                         secret_name));
+               return WERR_INTERNAL_ERROR;
+       }
+       ndr_err = ndr_pull_struct_blob(&lsa_secret, mem_ctx, server_key,
+                                      (ndr_pull_flags_fn_t)ndr_pull_bkrp_dc_serverwrap_key);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               DEBUG(2, ("Unable to parse the ndr encoded server wrap key %s\n", secret_name));
+               return WERR_INVALID_DATA;
+       }
+
+       return WERR_OK;
+}
+
+/*
+ * Find the current, preferred ServerWrap Key by looking at
+ * G$BCKUPKEY_P in the LSA secrets store.
+ *
+ * Then find the current decryption keys from the LSA secrets store as
+ * G$BCKUPKEY_keyGuidString.
+ */
+
+static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
+                                                      struct ldb_context *ldb_ctx,
+                                                      struct bkrp_dc_serverwrap_key *server_key,
+                                                      struct GUID *returned_guid)
+{
+       NTSTATUS status;
+       DATA_BLOB guid_binary;
+
+       status = get_lsa_secret(mem_ctx, ldb_ctx, "BCKUPKEY_P", &guid_binary);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("Error while fetching secret BCKUPKEY_P to find current GUID\n"));
+               return WERR_FILE_NOT_FOUND;
+       } else if (guid_binary.length == 0) {
+               /* RODC case, we do not have secrets locally */
+               DEBUG(1, ("Unable to fetch value for secret BCKUPKEY_P, are we an undetected RODC?\n"));
+               return WERR_INTERNAL_ERROR;
+       }
+
+       status = GUID_from_ndr_blob(&guid_binary, returned_guid);
+       if (!NT_STATUS_IS_OK(status)) {
+               return WERR_FILE_NOT_FOUND;
+       }
+
+       return bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx,
+                                               server_key, returned_guid);
+}
+
+static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
+                                           struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
+{
+       struct auth_session_info *session_info =
+               dcesrv_call_session_info(dce_call);
+       WERROR werr;
+       struct bkrp_server_side_wrapped decrypt_request;
+       DATA_BLOB sid_blob, encrypted_blob;
+       DATA_BLOB blob;
+       enum ndr_err_code ndr_err;
+       struct bkrp_dc_serverwrap_key server_key;
+       struct bkrp_rc4encryptedpayload rc4payload;
+       struct dom_sid *caller_sid;
+       uint8_t symkey[20]; /* SHA-1 hash len */
+       uint8_t mackey[20]; /* SHA-1 hash len */
+       uint8_t mac[20]; /* SHA-1 hash len */
+       gnutls_hmac_hd_t hmac_hnd;
+       gnutls_cipher_hd_t cipher_hnd;
+       gnutls_datum_t cipher_key;
+       int rc;
+
+       blob.data = r->in.data_in;
+       blob.length = r->in.data_in_len;
+
+       if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       ndr_err = ndr_pull_struct_blob_all(&blob, mem_ctx, &decrypt_request,
+                                          (ndr_pull_flags_fn_t)ndr_pull_bkrp_server_side_wrapped);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
+                                               &decrypt_request.guid);
+       if (!W_ERROR_IS_OK(werr)) {
+               return werr;
+       }
+
+       dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
+
+       dump_data_pw("r2: \n", decrypt_request.r2, sizeof(decrypt_request.r2));
+
+       /*
+        * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
+        * BACKUPKEY_BACKUP_GUID, it really is the whole key
+        */
+
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        server_key.key,
+                        sizeof(server_key.key));
+       gnutls_hmac(hmac_hnd,
+                   decrypt_request.r2,
+                   sizeof(decrypt_request.r2));
+       gnutls_hmac_output(hmac_hnd, symkey);
+
+       dump_data_pw("symkey: \n", symkey, sizeof(symkey));
+
+       /* rc4 decrypt sid and secret using sym key */
+       cipher_key.data = symkey;
+       cipher_key.size = sizeof(symkey);
+
+       encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
+                                        decrypt_request.ciphertext_length);
+
+       rc = gnutls_cipher_init(&cipher_hnd,
+                               GNUTLS_CIPHER_ARCFOUR_128,
+                               &cipher_key,
+                               NULL);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_cipher_init failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_INVALID_PARAMETER;
+       }
+       rc = gnutls_cipher_encrypt2(cipher_hnd,
+                                   encrypted_blob.data,
+                                   encrypted_blob.length,
+                                   encrypted_blob.data,
+                                   encrypted_blob.length);
+       gnutls_cipher_deinit(cipher_hnd);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_cipher_encrypt2 failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_INVALID_PARAMETER;
+       }
+
+       ndr_err = ndr_pull_struct_blob_all(&encrypted_blob, mem_ctx, &rc4payload,
+                                          (ndr_pull_flags_fn_t)ndr_pull_bkrp_rc4encryptedpayload);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       if (decrypt_request.payload_length != rc4payload.secret_data.length) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
+
+       /*
+        * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
+        * BACKUPKEY_BACKUP_GUID, it really is the whole key
+        */
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.r3,
+                   sizeof(rc4payload.r3));
+       gnutls_hmac_deinit(hmac_hnd, mackey);
+
+       dump_data_pw("mackey: \n", mackey, sizeof(mackey));
+
+       ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, &rc4payload.sid,
+                                      (ndr_push_flags_fn_t)ndr_push_dom_sid);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INTERNAL_ERROR;
+       }
+
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        mackey,
+                        sizeof(mackey));
+       /* SID field */
+       gnutls_hmac(hmac_hnd,
+                   sid_blob.data,
+                   sid_blob.length);
+       /* Secret field */
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.secret_data.data,
+                   rc4payload.secret_data.length);
+       gnutls_hmac_deinit(hmac_hnd, mac);
+
+       dump_data_pw("mac: \n", mac, sizeof(mac));
+       dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
+
+       if (memcmp(mac, rc4payload.mac, sizeof(mac)) != 0) {
+               return WERR_INVALID_ACCESS;
+       }
+
+       caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
+
+       if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
+               return WERR_INVALID_ACCESS;
+       }
+
+       *(r->out.data_out) = rc4payload.secret_data.data;
+       *(r->out.data_out_len) = rc4payload.secret_data.length;
+
+       return WERR_OK;
+}
+
+/*
+ * For BACKUPKEY_RESTORE_GUID we need to check the first 4 bytes to
+ * determine what type of restore is wanted.
+ *
+ * See MS-BKRP 3.1.4.1.4 BACKUPKEY_RESTORE_GUID point 1.
+ */
+
+static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
+                                       struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
+{
+       if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
+               return bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
+       }
+
+       return bkrp_client_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
+}
+
+/*
+ * We have some data, such as saved website or IMAP passwords that the
+ * client would like to put into the profile on-disk.  This needs to
+ * be encrypted.  This version gives the server the data over the
+ * network (protected only by the negotiated transport encryption),
+ * and asks that it be encrypted and returned for long-term storage.
+ *
+ * The data is NOT stored in the LSA, but a key to encrypt the data
+ * will be stored.  There is only one active encryption key per domain,
+ * it is pointed at with G$BCKUPKEY_P in the LSA secrets store.
+ *
+ * The potentially multiple valid decryptiong keys (and the encryption
+ * key) are in turn stored in the LSA secrets store as
+ * G$BCKUPKEY_keyGuidString.
+ *
+ */
+
+static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
+                                           struct bkrp_BackupKey *r ,struct ldb_context *ldb_ctx)
+{
+       struct auth_session_info *session_info =
+               dcesrv_call_session_info(dce_call);
+       DATA_BLOB sid_blob, encrypted_blob, server_wrapped_blob;
+       WERROR werr;
+       struct dom_sid *caller_sid;
+       uint8_t symkey[20]; /* SHA-1 hash len */
+       uint8_t mackey[20]; /* SHA-1 hash len */
+       struct bkrp_rc4encryptedpayload rc4payload;
+       gnutls_hmac_hd_t hmac_hnd;
+       struct bkrp_dc_serverwrap_key server_key;
+       enum ndr_err_code ndr_err;
+       struct bkrp_server_side_wrapped server_side_wrapped;
+       struct GUID guid;
+       gnutls_cipher_hd_t cipher_hnd;
+       gnutls_datum_t cipher_key;
+       int rc;
+
+       if (r->in.data_in_len == 0 || r->in.data_in == NULL) {
+               return WERR_INVALID_PARAMETER;
+       }
+
+       werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
+                                                       ldb_ctx, &server_key,
+                                                       &guid);
+
+       if (!W_ERROR_IS_OK(werr)) {
+               if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
+                       /* Generate the server wrap key since one wasn't found */
+                       werr =  generate_bkrp_server_wrap_key(mem_ctx,
+                                                             ldb_ctx);
+                       if (!W_ERROR_IS_OK(werr)) {
+                               return WERR_INVALID_PARAMETER;
+                       }
+                       werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
+                                                                       ldb_ctx,
+                                                                       &server_key,
+                                                                       &guid);
+
+                       if (W_ERROR_EQUAL(werr, WERR_FILE_NOT_FOUND)) {
+                               /* Ok we really don't manage to get this secret ...*/
+                               return WERR_FILE_NOT_FOUND;
+                       }
+               } else {
+                       /* In theory we should NEVER reach this point as it
+                          should only appear in a rodc server */
+                       /* we do not have the real secret attribute */
+                       return WERR_INVALID_PARAMETER;
+               }
+       }
+
+       caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
+
+       dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
+
+       /*
+        * This is the key derivation step, so that the HMAC and RC4
+        * operations over the user-supplied data are not able to
+        * disclose the master key.  By using random data, the symkey
+        * and mackey values are unique for this operation, and
+        * discovering these (by reversing the RC4 over the
+        * attacker-controlled data) does not return something able to
+        * be used to decyrpt the encrypted data of other users
+        */
+       generate_random_buffer(server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
+
+       dump_data_pw("r2: \n", server_side_wrapped.r2, sizeof(server_side_wrapped.r2));
+
+       generate_random_buffer(rc4payload.r3, sizeof(rc4payload.r3));
+
+       dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
+
+
+       /*
+        * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
+        * BACKUPKEY_BACKUP_GUID, it really is the whole key
+        */
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        server_key.key,
+                        sizeof(server_key.key));
+       gnutls_hmac(hmac_hnd,
+                   server_side_wrapped.r2,
+                   sizeof(server_side_wrapped.r2));
+       gnutls_hmac_output(hmac_hnd, symkey);
+
+       dump_data_pw("symkey: \n", symkey, sizeof(symkey));
+
+       /*
+        * This is *not* the leading 64 bytes, as indicated in MS-BKRP 3.1.4.1.1
+        * BACKUPKEY_BACKUP_GUID, it really is the whole key
+        */
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.r3,
+                   sizeof(rc4payload.r3));
+       gnutls_hmac_deinit(hmac_hnd, mackey);
+
+       dump_data_pw("mackey: \n", mackey, sizeof(mackey));
+
+       ndr_err = ndr_push_struct_blob(&sid_blob, mem_ctx, caller_sid,
+                                      (ndr_push_flags_fn_t)ndr_push_dom_sid);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INTERNAL_ERROR;
+       }
+
+       rc4payload.secret_data.data = r->in.data_in;
+       rc4payload.secret_data.length = r->in.data_in_len;
+
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        mackey,
+                        sizeof(mackey));
+       /* SID field */
+       gnutls_hmac(hmac_hnd,
+                   sid_blob.data,
+                   sid_blob.length);
+       /* Secret field */
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.secret_data.data,
+                   rc4payload.secret_data.length);
+       gnutls_hmac_deinit(hmac_hnd, rc4payload.mac);
+
+       dump_data_pw("rc4payload.mac: \n", rc4payload.mac, sizeof(rc4payload.mac));
+
+       rc4payload.sid = *caller_sid;
+
+       ndr_err = ndr_push_struct_blob(&encrypted_blob, mem_ctx, &rc4payload,
+                                      (ndr_push_flags_fn_t)ndr_push_bkrp_rc4encryptedpayload);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INTERNAL_ERROR;
+       }
+
+       /* rc4 encrypt sid and secret using sym key */
+       cipher_key.data = symkey;
+       cipher_key.size = sizeof(symkey);
+
+       rc = gnutls_cipher_init(&cipher_hnd,
+                               GNUTLS_CIPHER_ARCFOUR_128,
+                               &cipher_key,
+                               NULL);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_cipher_init failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_INVALID_PARAMETER;
+       }
+       rc = gnutls_cipher_encrypt2(cipher_hnd,
+                                   encrypted_blob.data,
+                                   encrypted_blob.length,
+                                   encrypted_blob.data,
+                                   encrypted_blob.length);
+       gnutls_cipher_deinit(cipher_hnd);
+       if (rc != GNUTLS_E_SUCCESS) {
+               DBG_ERR("gnutls_cipher_encrypt2 failed - %s\n",
+                       gnutls_strerror(rc));
+               return WERR_INVALID_PARAMETER;
+       }
+
+       /* create server wrap structure */
+
+       server_side_wrapped.payload_length = rc4payload.secret_data.length;
+       server_side_wrapped.ciphertext_length = encrypted_blob.length;
+       server_side_wrapped.guid = guid;
+       server_side_wrapped.rc4encryptedpayload = encrypted_blob.data;
+
+       ndr_err = ndr_push_struct_blob(&server_wrapped_blob, mem_ctx, &server_side_wrapped,
+                                      (ndr_push_flags_fn_t)ndr_push_bkrp_server_side_wrapped);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return WERR_INTERNAL_ERROR;
+       }
+
+       *(r->out.data_out) = server_wrapped_blob.data;
+       *(r->out.data_out_len) = server_wrapped_blob.length;
+
+       return WERR_OK;
 }
 
 static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
                                    TALLOC_CTX *mem_ctx, struct bkrp_BackupKey *r)
 {
-       WERROR error = WERR_INVALID_PARAM;
+       WERROR error = WERR_INVALID_PARAMETER;
        struct ldb_context *ldb_ctx;
        bool is_rodc;
        const char *addr = "unknown";
        /* At which level we start to add more debug of what is done in the protocol */
        const int debuglevel = 4;
 
+       gnutls_global_init();
+
        if (DEBUGLVL(debuglevel)) {
                const struct tsocket_address *remote_address;
                remote_address = dcesrv_connection_get_remote_address(dce_call->conn);
@@ -1294,47 +1782,46 @@ static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
                return WERR_NOT_SUPPORTED;
        }
 
-       if (!dce_call->conn->auth_state.auth_info ||
-               dce_call->conn->auth_state.auth_info->auth_level != DCERPC_AUTH_LEVEL_PRIVACY) {
-               DCESRV_FAULT(DCERPC_FAULT_ACCESS_DENIED);
-       }
-
-       ldb_ctx = samdb_connect(mem_ctx, dce_call->event_ctx,
-                               dce_call->conn->dce_ctx->lp_ctx,
-                               system_session(dce_call->conn->dce_ctx->lp_ctx), 0);
+       /*
+        * Save the current remote session details so they can used by the
+        * audit logging module. This allows the audit logging to report the
+        * remote users details, rather than the system users details.
+        */
+       ldb_ctx = dcesrv_samdb_connect_as_system(mem_ctx, dce_call);
 
        if (samdb_rodc(ldb_ctx, &is_rodc) != LDB_SUCCESS) {
                talloc_unlink(mem_ctx, ldb_ctx);
-               return WERR_INVALID_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        if (!is_rodc) {
                if(strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
                        BACKUPKEY_RESTORE_GUID, strlen(BACKUPKEY_RESTORE_GUID)) == 0) {
-                       DEBUG(debuglevel, ("Client %s requested to decrypt a client side wrapped secret\n", addr));
-                       error = bkrp_do_uncrypt_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
+                       DEBUG(debuglevel, ("Client %s requested to decrypt a wrapped secret\n", addr));
+                       error = bkrp_generic_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
                }
 
                if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
                        BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, strlen(BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID)) == 0) {
                        DEBUG(debuglevel, ("Client %s requested certificate for client wrapped secret\n", addr));
-                       error = bkrp_do_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
+                       error = bkrp_retrieve_client_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
                }
 
                if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
                        BACKUPKEY_RESTORE_GUID_WIN2K, strlen(BACKUPKEY_RESTORE_GUID_WIN2K)) == 0) {
-                       DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret, not implemented yet\n", addr));
-                       error = bkrp_do_uncrypt_server_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
+                       DEBUG(debuglevel, ("Client %s requested to decrypt a server side wrapped secret\n", addr));
+                       error = bkrp_server_wrap_decrypt_data(dce_call, mem_ctx, r, ldb_ctx);
                }
 
                if (strncasecmp(GUID_string(mem_ctx, r->in.guidActionAgent),
                        BACKUPKEY_BACKUP_GUID, strlen(BACKUPKEY_BACKUP_GUID)) == 0) {
-                       DEBUG(debuglevel, ("Client %s requested a server wrapped secret, not implemented yet\n", addr));
-                       error = bkrp_do_retrieve_server_wrap_key(dce_call, mem_ctx, r, ldb_ctx);
+                       DEBUG(debuglevel, ("Client %s requested a server wrapped secret\n", addr));
+                       error = bkrp_server_wrap_encrypt_data(dce_call, mem_ctx, r, ldb_ctx);
                }
        }
        /*else: I am a RODC so I don't handle backup key protocol */
 
+       gnutls_global_deinit();
        talloc_unlink(mem_ctx, ldb_ctx);
        return error;
 }