s4:rpc_server: only pass context to op_bind() hooks
[gd/samba-autobuild/.git] / source4 / rpc_server / backupkey / dcesrv_backupkey.c
index 8636e0fd62b950896b9814dd9bc12688be8d3137..a826ae083f439777cc4946ecfa93b7a488a20d20 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 <hcrypto/evp.h>
-#include <hcrypto/hmac.h>
-#include <der.h>
+
 #include "../lib/tsocket/tsocket.h"
 #include "../libcli/security/security.h"
 #include "librpc/gen_ndr/ndr_security.h"
-#include "lib/crypto/arcfour.h"
+#include "libds/common/roles.h"
+
 #include <gnutls/gnutls.h>
 #include <gnutls/x509.h>
-#if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
-#include <gcrypt.h>
-#endif
-
+#include <gnutls/crypto.h>
+#include <gnutls/abstract.h>
 
-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
-};
+#define DCESRV_INTERFACE_BACKUPKEY_BIND(context, iface) \
+       dcesrv_interface_backupkey_bind(context, iface)
+static NTSTATUS dcesrv_interface_backupkey_bind(struct dcesrv_connection_context *context,
+                                               const struct dcesrv_interface *iface)
+{
+       return dcesrv_interface_bind_require_privacy(context, iface);
+}
 
 static NTSTATUS set_lsa_secret(TALLOC_CTX *mem_ctx,
                               struct ldb_context *ldb,
@@ -249,147 +245,112 @@ static NTSTATUS get_lsa_secret(TALLOC_CTX *mem_ctx,
        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;
-
-       ret = BN_bin2bn(rev.data, rev.length, NULL);
-       talloc_free(rev.data);
+       datum->size = blob.length;
 
-       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_private_key privkey = NULL;
-
-       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"));
-               hx509_context_free(&hctx);
-               return NT_STATUS_INTERNAL_ERROR;
-       }
-
-       if (hx509_private_key_init(&privkey, ops, NULL) != 0) {
-               hx509_context_free(&hctx);
-               return NT_STATUS_NO_MEMORY;
-       }
+       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;
 
-       rsa = RSA_new();
-       if (rsa ==NULL) {
-               hx509_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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_private_key_free(&privkey);
-               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;
        }
 
-       *pk = privkey;
+       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;
+       }
 
-       hx509_private_key_assign_rsa(*pk, 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 NT_STATUS_INTERNAL_ERROR;
+       }
+
+       *pk = privkey;
 
-       hx509_context_free(&hctx);
        return NT_STATUS_OK;
 }
 
@@ -400,102 +361,87 @@ static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
                                          uint32_t access_check_len,
                                          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;
 
        struct dom_sid *access_sid = NULL;
        struct dom_sid *caller_sid = NULL;
-
-       /* This one should not be freed */
-       const AlgorithmIdentifier *alg;
+       int rc;
 
        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);
-
        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
@@ -512,26 +458,25 @@ static WERROR get_and_verify_access_check(TALLOC_CTX *sub_ctx,
        {
                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
@@ -579,6 +524,8 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                                            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;
@@ -593,7 +540,7 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
        blob.length = r->in.data_in_len;
 
        if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
-               return WERR_INVALID_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        /*
@@ -610,7 +557,7 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
        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;
+               return WERR_INVALID_PARAMETER;
        }
 
        if ((uncrypt_request.version != BACKUPKEY_CLIENT_WRAP_VERSION2)
@@ -621,14 +568,14 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
 
        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,
@@ -642,15 +589,14 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                /* we do not have the real secret attribute, like if we are an RODC */
                return WERR_INVALID_PARAMETER;
        } else {
-               hx509_context hctx;
                struct bkrp_exported_RSA_key_pair keypair;
-               hx509_private_key pk;
-               uint32_t i, res;
-               heim_octet_string reversed_secret;
-               heim_octet_string uncrypted_secret;
-               AlgorithmIdentifier alg;
+               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(&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)) {
@@ -658,7 +604,9 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                        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;
                }
@@ -666,8 +614,8 @@ static WERROR bkrp_client_wrap_decrypt_data(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 ... */
@@ -676,31 +624,30 @@ static WERROR bkrp_client_wrap_decrypt_data(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_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;
@@ -714,7 +661,7 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                                                           uncrypted_secretv2.payload_key,
                                                           uncrypt_request.access_check,
                                                           uncrypt_request.access_check_len,
-                                                          dce_call->conn->auth_state.session_info);
+                                                          session_info);
                        if (!W_ERROR_IS_OK(werr)) {
                                return werr;
                        }
@@ -731,8 +678,7 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
 
                        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;
@@ -758,7 +704,7 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                                                           uncrypted_secretv3.payload_key,
                                                           uncrypt_request.access_check,
                                                           uncrypt_request.access_check_len,
-                                                          dce_call->conn->auth_state.session_info);
+                                                          session_info);
                        if (!W_ERROR_IS_OK(werr)) {
                                return werr;
                        }
@@ -797,413 +743,382 @@ static WERROR bkrp_client_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
        return WERR_OK;
 }
 
-/*
- * Strictly, this function no longer uses Heimdal in order to generate an RSA
- * key, but GnuTLS.
- *
- * The resulting key is then imported into Heimdal's RSA structure.
- *
- * We use GnuTLS because it can reliably generate 2048 bit keys every time.
- * Windows clients strictly require 2048, no more since it won't fit and no
- * less either. Heimdal would almost always generate a smaller key.
- */
-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)
 {
-       int ret;
-       uint8_t *p0 = NULL;
-       const uint8_t *p;
-       size_t len;
-       int bits = 2048;
-       int RSA_returned_bits;
-       gnutls_x509_privkey_t gtls_key;
-       WERROR werr;
-
-       *rsa = NULL;
+       DATA_BLOB *blob;
+       size_t i;
 
-       gnutls_global_init();
-#if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
-       DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
-       gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
-#endif
-       ret = gnutls_x509_privkey_init(&gtls_key);
-       if (ret != 0) {
-               gnutls_global_deinit();
-               return WERR_INTERNAL_ERROR;
+       blob = talloc(mem_ctx, DATA_BLOB);
+       if (blob == NULL) {
+               return NULL;
        }
 
-       /*
-        * Unlike Heimdal's RSA_generate_key_ex(), this generates a
-        * 2048 bit key 100% of the time.  The heimdal code had a ~1/8
-        * chance of doing so, chewing vast quantities of computation
-        * and entropy in the process.
-        */
-
-       ret = gnutls_x509_privkey_generate(gtls_key, GNUTLS_PK_RSA, bits, 0);
-       if (ret != 0) {
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+       blob->length = datum->size;
+       if (datum->data[0] == '\0') {
+               /* The datum has a leading byte zero, skip it */
+               blob->length = datum->size - 1;
        }
-
-       /* No need to check error code, this SHOULD fail */
-       gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, NULL, &len);
-
-       if (len < 1) {
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+       blob->data = talloc_zero_array(mem_ctx, uint8_t, blob->length);
+       if (blob->data == NULL) {
+               talloc_free(blob);
+               return NULL;
        }
 
-       p0 = talloc_size(ctx, len);
-       if (p0 == NULL) {
-               werr = WERR_NOMEM;
-               goto done;
+       for (i = 0; i < blob->length; i++) {
+               blob->data[i] = datum->data[datum->size - i - 1];
        }
-       p = p0;
 
-       /*
-        * Only this GnuTLS export function correctly exports the key,
-        * we can't use gnutls_rsa_params_export_raw() because while
-        * it appears to be fixed in more recent versions, in the
-        * Ubuntu 14.04 version 2.12.23 (at least) it incorrectly
-        * exports one of the key parameters (qInv).  Additionally, we
-        * would have to work around subtle differences in big number
-        * representations.
-        *
-        * We need access to the RSA parameters directly (in the
-        * parameter RSA **rsa) as the caller has to manually encode
-        * them in a non-standard data structure.
-        */
-       ret = gnutls_x509_privkey_export(gtls_key, GNUTLS_X509_FMT_DER, p0, &len);
+       return blob;
+}
 
-       if (ret != 0) {
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+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;
        }
 
-       /*
-        * 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);
-
-       if (ret != 0) {
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+       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;
        }
 
-       *rsa = d2i_RSAPrivateKey(NULL, &p, len);
-       TALLOC_FREE(p0);
-
-       if (*rsa == NULL) {
-               hx509_private_key_free(pk);
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+       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;
        }
 
-       RSA_returned_bits = BN_num_bits((*rsa)->n);
-       DEBUG(6, ("GnuTLS returned an RSA private key with %d bits\n", RSA_returned_bits));
-
-       if (RSA_returned_bits != bits) {
-               DEBUG(0, ("GnuTLS unexpectedly returned an RSA private key with %d bits, needed %d\n", RSA_returned_bits, bits));
-               hx509_private_key_free(pk);
-               werr = WERR_INTERNAL_ERROR;
-               goto done;
+       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;
        }
 
-       werr = WERR_OK;
-
-done:
-       if (p0 != NULL) {
-               memset(p0, 0, len);
-               TALLOC_FREE(p0);
-       }
+       *pk = privkey;
 
-       gnutls_x509_privkey_deinit(gtls_key);
-       gnutls_global_deinit();
-       return werr;
+       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 {
@@ -1212,51 +1127,37 @@ 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;
 }
 
@@ -1373,7 +1274,7 @@ static WERROR generate_bkrp_server_wrap_key(TALLOC_CTX *ctx, struct ldb_context
        secret_name = talloc_asprintf(frame, "BCKUPKEY_%s", GUID_string(ctx, &guid));
        if (secret_name == NULL) {
                TALLOC_FREE(frame);
-               return WERR_NOMEM;
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
        status = set_lsa_secret(frame, ldb_ctx, secret_name, &blob_wrap_key);
@@ -1426,7 +1327,7 @@ static WERROR bkrp_do_retrieve_server_wrap_key(TALLOC_CTX *mem_ctx, struct ldb_c
 
        secret_name = talloc_asprintf(mem_ctx, "BCKUPKEY_%s", guid_string);
        if (secret_name == NULL) {
-               return WERR_NOMEM;
+               return WERR_NOT_ENOUGH_MEMORY;
        }
 
        status = get_lsa_secret(mem_ctx, ldb_ctx, secret_name, &lsa_secret);
@@ -1488,9 +1389,11 @@ static WERROR bkrp_do_retrieve_default_server_wrap_key(TALLOC_CTX *mem_ctx,
 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, symkey_blob;
+       DATA_BLOB sid_blob, encrypted_blob;
        DATA_BLOB blob;
        enum ndr_err_code ndr_err;
        struct bkrp_dc_serverwrap_key server_key;
@@ -1499,24 +1402,26 @@ static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
        uint8_t symkey[20]; /* SHA-1 hash len */
        uint8_t mackey[20]; /* SHA-1 hash len */
        uint8_t mac[20]; /* SHA-1 hash len */
-       unsigned int hash_len;
-       HMAC_CTX ctx;
+       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_PARAM;
+               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_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        if (decrypt_request.magic != BACKUPKEY_SERVER_WRAP_VERSION) {
-               return WERR_INVALID_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        werr = bkrp_do_retrieve_server_wrap_key(mem_ctx, ldb_ctx, &server_key,
@@ -1533,28 +1438,54 @@ static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
         * 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
         */
-       HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
-            decrypt_request.r2, sizeof(decrypt_request.r2),
-            symkey, &hash_len);
 
-       dump_data_pw("symkey: \n", symkey, hash_len);
+       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 */
-       symkey_blob = data_blob_const(symkey, sizeof(symkey));
+       cipher_key.data = symkey;
+       cipher_key.size = sizeof(symkey);
 
        encrypted_blob = data_blob_const(decrypt_request.rc4encryptedpayload,
                                         decrypt_request.ciphertext_length);
 
-       arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
+       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_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        if (decrypt_request.payload_length != rc4payload.secret_data.length) {
-               return WERR_INVALID_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        dump_data_pw("r3: \n", rc4payload.r3, sizeof(rc4payload.r3));
@@ -1563,9 +1494,10 @@ static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
         * 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
         */
-       HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
-            rc4payload.r3, sizeof(rc4payload.r3),
-            mackey, &hash_len);
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.r3,
+                   sizeof(rc4payload.r3));
+       gnutls_hmac_deinit(hmac_hnd, mackey);
 
        dump_data_pw("mackey: \n", mackey, sizeof(mackey));
 
@@ -1575,14 +1507,19 @@ static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                return WERR_INTERNAL_ERROR;
        }
 
-       HMAC_CTX_init(&ctx);
-       HMAC_Init_ex(&ctx, mackey, hash_len, EVP_sha1(), NULL);
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        mackey,
+                        sizeof(mackey));
        /* SID field */
-       HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
+       gnutls_hmac(hmac_hnd,
+                   sid_blob.data,
+                   sid_blob.length);
        /* Secret field */
-       HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
-       HMAC_Final(&ctx, mac, &hash_len);
-       HMAC_CTX_cleanup(&ctx);
+       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));
@@ -1591,7 +1528,7 @@ static WERROR bkrp_server_wrap_decrypt_data(struct dcesrv_call_state *dce_call,
                return WERR_INVALID_ACCESS;
        }
 
-       caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
+       caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
 
        if (!dom_sid_equal(&rc4payload.sid, caller_sid)) {
                return WERR_INVALID_ACCESS;
@@ -1614,7 +1551,7 @@ static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALL
                                        struct bkrp_BackupKey *r, struct ldb_context *ldb_ctx)
 {
        if (r->in.data_in_len < 4 || r->in.data_in == NULL) {
-               return WERR_INVALID_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        if (IVAL(r->in.data_in, 0) == BACKUPKEY_SERVER_WRAP_VERSION) {
@@ -1644,21 +1581,25 @@ static WERROR bkrp_generic_decrypt_data(struct dcesrv_call_state *dce_call, TALL
 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)
 {
-       DATA_BLOB sid_blob, encrypted_blob, symkey_blob, server_wrapped_blob;
+       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 */
-       unsigned int hash_len;
        struct bkrp_rc4encryptedpayload rc4payload;
-       HMAC_CTX ctx;
+       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_PARAM;
+               return WERR_INVALID_PARAMETER;
        }
 
        werr = bkrp_do_retrieve_default_server_wrap_key(mem_ctx,
@@ -1690,7 +1631,7 @@ static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call,
                }
        }
 
-       caller_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
+       caller_sid = &session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
 
        dump_data_pw("server_key: \n", server_key.key, sizeof(server_key.key));
 
@@ -1716,19 +1657,25 @@ static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call,
         * 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
         */
-       HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
-            server_side_wrapped.r2, sizeof(server_side_wrapped.r2),
-            symkey, &hash_len);
+       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, hash_len);
+       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
         */
-       HMAC(EVP_sha1(), server_key.key, sizeof(server_key.key),
-            rc4payload.r3, sizeof(rc4payload.r3),
-            mackey, &hash_len);
+       gnutls_hmac(hmac_hnd,
+                   rc4payload.r3,
+                   sizeof(rc4payload.r3));
+       gnutls_hmac_deinit(hmac_hnd, mackey);
 
        dump_data_pw("mackey: \n", mackey, sizeof(mackey));
 
@@ -1741,14 +1688,19 @@ static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call,
        rc4payload.secret_data.data = r->in.data_in;
        rc4payload.secret_data.length = r->in.data_in_len;
 
-       HMAC_CTX_init(&ctx);
-       HMAC_Init_ex(&ctx, mackey, 20, EVP_sha1(), NULL);
+       gnutls_hmac_init(&hmac_hnd,
+                        GNUTLS_MAC_SHA1,
+                        mackey,
+                        sizeof(mackey));
        /* SID field */
-       HMAC_Update(&ctx, sid_blob.data, sid_blob.length);
+       gnutls_hmac(hmac_hnd,
+                   sid_blob.data,
+                   sid_blob.length);
        /* Secret field */
-       HMAC_Update(&ctx, rc4payload.secret_data.data, rc4payload.secret_data.length);
-       HMAC_Final(&ctx, rc4payload.mac, &hash_len);
-       HMAC_CTX_cleanup(&ctx);
+       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));
 
@@ -1761,8 +1713,29 @@ static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call,
        }
 
        /* rc4 encrypt sid and secret using sym key */
-       symkey_blob = data_blob_const(symkey, sizeof(symkey));
-       arcfour_crypt_blob(encrypted_blob.data, encrypted_blob.length, &symkey_blob);
+       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 */
 
@@ -1786,13 +1759,15 @@ static WERROR bkrp_server_wrap_encrypt_data(struct dcesrv_call_state *dce_call,
 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);
@@ -1806,18 +1781,16 @@ 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) {
@@ -1847,6 +1820,7 @@ static WERROR dcesrv_bkrp_BackupKey(struct dcesrv_call_state *dce_call,
        }
        /*else: I am a RODC so I don't handle backup key protocol */
 
+       gnutls_global_deinit();
        talloc_unlink(mem_ctx, ldb_ctx);
        return error;
 }