[lxc-devel] [lxd/master] Attempt for Passwordless PKI mode

miranda0615 on Github lxc-bot at linuxcontainers.org
Fri Dec 13 03:10:02 UTC 2019


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 351 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20191212/e8a30679/attachment-0001.bin>
-------------- next part --------------
From 114850e096c67f828e69fd6dc527bbae464a436a Mon Sep 17 00:00:00 2001
From: Miranda Huang <miranda061500 at gmail.com>
Date: Sun, 8 Dec 2019 18:01:39 -0600
Subject: [PATCH 1/5] test

---
 lxd/util/crl.go | 336 ++++++++++++++++++++++++++++++++++++++++++++++++
 test/custom.sh  | 119 +++++++++++++++++
 2 files changed, 455 insertions(+)
 create mode 100644 lxd/util/crl.go
 create mode 100644 test/custom.sh

diff --git a/lxd/util/crl.go b/lxd/util/crl.go
new file mode 100644
index 0000000000..467dfe99ee
--- /dev/null
+++ b/lxd/util/crl.go
@@ -0,0 +1,336 @@
+// Package revoke provides functionality for checking the validity of
+// a cert. Specifically, the temporal validity of the certificate is
+// checked first, then any CRL and OCSP url in the cert is checked.
+package revoke
+
+import (
+	"bytes"
+	"crypto"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/base64"
+	"encoding/pem"
+	"errors"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"net/http"
+	neturl "net/url"
+	"sync"
+	"time"
+
+	"golang.org/x/crypto/ocsp"
+
+	"github.com/cloudflare/cfssl/helpers"
+	"github.com/cloudflare/cfssl/log"
+)
+
+// HardFail determines whether the failure to check the revocation
+// status of a certificate (i.e. due to network failure) causes
+// verification to fail (a hard failure).
+var HardFail = false
+
+// CRLSet associates a PKIX certificate list with the URL the CRL is
+// fetched from.
+var CRLSet = map[string]*pkix.CertificateList{}
+var crlLock = new(sync.Mutex)
+
+// We can't handle LDAP certificates, so this checks to see if the
+// URL string points to an LDAP resource so that we can ignore it.
+func ldapURL(url string) bool {
+	u, err := neturl.Parse(url)
+	if err != nil {
+		log.Warningf("error parsing url %s: %v", url, err)
+		return false
+	}
+	if u.Scheme == "ldap" {
+		return true
+	}
+	return false
+}
+
+// revCheck should check the certificate for any revocations. It
+// returns a pair of booleans: the first indicates whether the certificate
+// is revoked, the second indicates whether the revocations were
+// successfully checked.. This leads to the following combinations:
+//
+//  false, false: an error was encountered while checking revocations.
+//
+//  false, true:  the certificate was checked successfully and
+//                  it is not revoked.
+//
+//  true, true:   the certificate was checked successfully and
+//                  it is revoked.
+//
+//  true, false:  failure to check revocation status causes
+//                  verification to fail
+func revCheck(cert *x509.Certificate) (revoked, ok bool, err error) {
+	for _, url := range cert.CRLDistributionPoints {
+		if ldapURL(url) {
+			log.Infof("skipping LDAP CRL: %s", url)
+			continue
+		}
+
+		if revoked, ok, err := certIsRevokedCRL(cert, url); !ok {
+			log.Warning("error checking revocation via CRL")
+			if HardFail {
+				return true, false, err
+			}
+			return false, false, err
+		} else if revoked {
+			log.Info("certificate is revoked via CRL")
+			return true, true, err
+		}
+	}
+
+	if revoked, ok, err := certIsRevokedOCSP(cert, HardFail); !ok {
+		log.Warning("error checking revocation via OCSP")
+		if HardFail {
+			return true, false, err
+		}
+		return false, false, err
+	} else if revoked {
+		log.Info("certificate is revoked via OCSP")
+		return true, true, err
+	}
+
+	return false, true, nil
+}
+
+// fetchCRL fetches and parses a CRL.
+func fetchCRL(url string) (*pkix.CertificateList, error) {
+	resp, err := http.Get(url)
+	if err != nil {
+		return nil, err
+	} else if resp.StatusCode >= 300 {
+		return nil, errors.New("failed to retrieve CRL")
+	}
+
+	body, err := crlRead(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+	resp.Body.Close()
+
+	return x509.ParseCRL(body)
+}
+
+func getIssuer(cert *x509.Certificate) *x509.Certificate {
+	var issuer *x509.Certificate
+	var err error
+	for _, issuingCert := range cert.IssuingCertificateURL {
+		issuer, err = fetchRemote(issuingCert)
+		if err != nil {
+			continue
+		}
+		break
+	}
+
+	return issuer
+
+}
+
+// check a cert against a specific CRL. Returns the same bool pair
+// as revCheck, plus an error if one occurred.
+func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err error) {
+	crl, ok := CRLSet[url]
+	if ok && crl == nil {
+		ok = false
+		crlLock.Lock()
+		delete(CRLSet, url)
+		crlLock.Unlock()
+	}
+
+	var shouldFetchCRL = true
+	if ok {
+		if !crl.HasExpired(time.Now()) {
+			shouldFetchCRL = false
+		}
+	}
+
+	issuer := getIssuer(cert)
+
+	if shouldFetchCRL {
+		var err error
+		crl, err = fetchCRL(url)
+		if err != nil {
+			log.Warningf("failed to fetch CRL: %v", err)
+			return false, false, err
+		}
+
+		// check CRL signature
+		if issuer != nil {
+			err = issuer.CheckCRLSignature(crl)
+			if err != nil {
+				log.Warningf("failed to verify CRL: %v", err)
+				return false, false, err
+			}
+		}
+
+		crlLock.Lock()
+		CRLSet[url] = crl
+		crlLock.Unlock()
+	}
+
+	for _, revoked := range crl.TBSCertList.RevokedCertificates {
+		if cert.SerialNumber.Cmp(revoked.SerialNumber) == 0 {
+			log.Info("Serial number match: intermediate is revoked.")
+			return true, true, err
+		}
+	}
+
+	return false, true, err
+}
+
+// VerifyCertificate ensures that the certificate passed in hasn't
+// expired and checks the CRL for the server.
+func VerifyCertificate(cert *x509.Certificate) (revoked, ok bool) {
+	revoked, ok, _ = VerifyCertificateError(cert)
+	return revoked, ok
+}
+
+// VerifyCertificateError ensures that the certificate passed in hasn't
+// expired and checks the CRL for the server.
+func VerifyCertificateError(cert *x509.Certificate) (revoked, ok bool, err error) {
+	if !time.Now().Before(cert.NotAfter) {
+		msg := fmt.Sprintf("Certificate expired %s\n", cert.NotAfter)
+		log.Info(msg)
+		return true, true, fmt.Errorf(msg)
+	} else if !time.Now().After(cert.NotBefore) {
+		msg := fmt.Sprintf("Certificate isn't valid until %s\n", cert.NotBefore)
+		log.Info(msg)
+		return true, true, fmt.Errorf(msg)
+	}
+	return revCheck(cert)
+}
+
+func fetchRemote(url string) (*x509.Certificate, error) {
+	resp, err := http.Get(url)
+	if err != nil {
+		return nil, err
+	}
+
+	in, err := remoteRead(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+	resp.Body.Close()
+
+	p, _ := pem.Decode(in)
+	if p != nil {
+		return helpers.ParseCertificatePEM(in)
+	}
+
+	return x509.ParseCertificate(in)
+}
+
+var ocspOpts = ocsp.RequestOptions{
+	Hash: crypto.SHA1,
+}
+
+func certIsRevokedOCSP(leaf *x509.Certificate, strict bool) (revoked, ok bool, e error) {
+	var err error
+
+	ocspURLs := leaf.OCSPServer
+	if len(ocspURLs) == 0 {
+		// OCSP not enabled for this certificate.
+		return false, true, nil
+	}
+
+	issuer := getIssuer(leaf)
+
+	if issuer == nil {
+		return false, false, nil
+	}
+
+	ocspRequest, err := ocsp.CreateRequest(leaf, issuer, &ocspOpts)
+	if err != nil {
+		return revoked, ok, err
+	}
+
+	for _, server := range ocspURLs {
+		resp, err := sendOCSPRequest(server, ocspRequest, leaf, issuer)
+		if err != nil {
+			if strict {
+				return revoked, ok, err
+			}
+			continue
+		}
+
+		// There wasn't an error fetching the OCSP status.
+		ok = true
+
+		if resp.Status != ocsp.Good {
+			// The certificate was revoked.
+			revoked = true
+		}
+
+		return revoked, ok, err
+	}
+	return revoked, ok, err
+}
+
+// sendOCSPRequest attempts to request an OCSP response from the
+// server. The error only indicates a failure to *fetch* the
+// certificate, and *does not* mean the certificate is valid.
+func sendOCSPRequest(server string, req []byte, leaf, issuer *x509.Certificate) (*ocsp.Response, error) {
+	var resp *http.Response
+	var err error
+	if len(req) > 256 {
+		buf := bytes.NewBuffer(req)
+		resp, err = http.Post(server, "application/ocsp-request", buf)
+	} else {
+		reqURL := server + "/" + neturl.QueryEscape(base64.StdEncoding.EncodeToString(req))
+		resp, err = http.Get(reqURL)
+	}
+
+	if err != nil {
+		return nil, err
+	}
+
+	if resp.StatusCode != http.StatusOK {
+		return nil, errors.New("failed to retrieve OSCP")
+	}
+
+	body, err := ocspRead(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+	resp.Body.Close()
+
+	switch {
+	case bytes.Equal(body, ocsp.UnauthorizedErrorResponse):
+		return nil, errors.New("OSCP unauthorized")
+	case bytes.Equal(body, ocsp.MalformedRequestErrorResponse):
+		return nil, errors.New("OSCP malformed")
+	case bytes.Equal(body, ocsp.InternalErrorErrorResponse):
+		return nil, errors.New("OSCP internal error")
+	case bytes.Equal(body, ocsp.TryLaterErrorResponse):
+		return nil, errors.New("OSCP try later")
+	case bytes.Equal(body, ocsp.SigRequredErrorResponse):
+		return nil, errors.New("OSCP signature required")
+	}
+
+	return ocsp.ParseResponseForCert(body, leaf, issuer)
+}
+
+var crlRead = ioutil.ReadAll
+
+// SetCRLFetcher sets the function to use to read from the http response body
+func SetCRLFetcher(fn func(io.Reader) ([]byte, error)) {
+	crlRead = fn
+}
+
+var remoteRead = ioutil.ReadAll
+
+// SetRemoteFetcher sets the function to use to read from the http response body
+func SetRemoteFetcher(fn func(io.Reader) ([]byte, error)) {
+	remoteRead = fn
+}
+
+var ocspRead = ioutil.ReadAll
+
+// SetOCSPFetcher sets the function to use to read from the http response body
+func SetOCSPFetcher(fn func(io.Reader) ([]byte, error)) {
+	ocspRead = fn
+}
diff --git a/test/custom.sh b/test/custom.sh
new file mode 100644
index 0000000000..254d406271
--- /dev/null
+++ b/test/custom.sh
@@ -0,0 +1,119 @@
+#!/bin/sh -eu
+[ -n "${GOPATH:-}" ] && export "PATH=${GOPATH}/bin:${PATH}"
+export "TEST_DIR=~"
+if [ ! -d "/usr/share/easy-rsa/" ]; then
+  echo "==> SKIP: The pki test requires easy-rsa to be installed"
+  return
+fi
+
+# Setup the PKI
+cp -R /usr/share/easy-rsa "${TEST_DIR}/pki"
+(
+  set -e
+  cd "${TEST_DIR}/pki"
+  # shellcheck disable=SC1091
+  if [ -e pkitool ]; then
+      . ./vars
+      ./clean-all
+      ./pkitool --initca
+      ./pkitool --server 127.0.0.1
+      ./pkitool lxd-client
+  else
+      ./easyrsa init-pki
+      echo "lxd" | ./easyrsa build-ca nopass
+      ./easyrsa build-server-full 127.0.0.1 nopass
+      ./easyrsa build-client-full lxd-client nopass
+      mkdir keys
+      cp pki/private/* keys/
+      cp pki/issued/* keys/
+      cp pki/ca.crt keys/
+  fi
+)
+
+# Setup the daemon
+LXD5_DIR=$(mktemp -d -p "${TEST_DIR}" XXX)
+chmod +x "${LXD5_DIR}"
+cat "${TEST_DIR}/pki/keys/127.0.0.1.crt" "${TEST_DIR}/pki/keys/ca.crt" > "${LXD5_DIR}/server.crt"
+cp "${TEST_DIR}/pki/keys/127.0.0.1.key" "${LXD5_DIR}/server.key"
+cp "${TEST_DIR}/pki/keys/ca.crt" "${LXD5_DIR}/server.ca"
+spawn_lxd "${LXD5_DIR}" true
+LXD5_ADDR=$(cat "${LXD5_DIR}/lxd.addr")
+
+# Setup the client
+LXC5_DIR=$(mktemp -d -p "${TEST_DIR}" XXX)
+cp "${TEST_DIR}/pki/keys/lxd-client.crt" "${LXC5_DIR}/client.crt"
+cp "${TEST_DIR}/pki/keys/lxd-client.key" "${LXC5_DIR}/client.key"
+cp "${TEST_DIR}/pki/keys/ca.crt" "${LXC5_DIR}/client.ca"
+
+# Confirm that a valid client certificate works
+(
+  set -e
+  export LXD_CONF=${LXC5_DIR}
+  lxc_remote remote add pki-lxd "${LXD5_ADDR}" --accept-certificate --password=foo
+  lxc_remote info pki-lxd:
+  lxc_remote remote remove pki-lxd
+)
+
+# Confirm that a normal, non-PKI certificate doesn't
+! lxc_remote remote add pki-lxd "${LXD5_ADDR}" --accept-certificate --password=foo || false
+
+kill_lxd "${LXD5_DIR}"
+}
+test_pki() {
+if [ ! -d "/usr/share/easy-rsa/" ]; then
+  echo "==> SKIP: The pki test requires easy-rsa to be installed"
+  return
+fi
+
+# Setup the PKI
+cp -R /usr/share/easy-rsa "${TEST_DIR}/pki"
+(
+  set -e
+  cd "${TEST_DIR}/pki"
+  # shellcheck disable=SC1091
+  if [ -e pkitool ]; then
+      . ./vars
+      ./clean-all
+      ./pkitool --initca
+      ./pkitool --server 127.0.0.1
+      ./pkitool lxd-client
+  else
+      ./easyrsa init-pki
+      echo "lxd" | ./easyrsa build-ca nopass
+      ./easyrsa build-server-full 127.0.0.1 nopass
+      ./easyrsa build-client-full lxd-client nopass
+      mkdir keys
+      cp pki/private/* keys/
+      cp pki/issued/* keys/
+      cp pki/ca.crt keys/
+  fi
+)
+
+# Setup the daemon
+LXD5_DIR=$(mktemp -d -p "${TEST_DIR}" XXX)
+chmod +x "${LXD5_DIR}"
+cat "${TEST_DIR}/pki/keys/127.0.0.1.crt" "${TEST_DIR}/pki/keys/ca.crt" > "${LXD5_DIR}/server.crt"
+cp "${TEST_DIR}/pki/keys/127.0.0.1.key" "${LXD5_DIR}/server.key"
+cp "${TEST_DIR}/pki/keys/ca.crt" "${LXD5_DIR}/server.ca"
+spawn_lxd "${LXD5_DIR}" true
+LXD5_ADDR=$(cat "${LXD5_DIR}/lxd.addr")
+
+# Setup the client
+LXC5_DIR=$(mktemp -d -p "${TEST_DIR}" XXX)
+cp "${TEST_DIR}/pki/keys/lxd-client.crt" "${LXC5_DIR}/client.crt"
+cp "${TEST_DIR}/pki/keys/lxd-client.key" "${LXC5_DIR}/client.key"
+cp "${TEST_DIR}/pki/keys/ca.crt" "${LXC5_DIR}/client.ca"
+
+# Confirm that a valid client certificate works
+(
+  set -e
+  export LXD_CONF=${LXC5_DIR}
+  lxc_remote remote add pki-lxd "${LXD5_ADDR}" --accept-certificate --password=foo
+  lxc_remote info pki-lxd:
+  lxc_remote remote remove pki-lxd
+)
+
+# Confirm that a normal, non-PKI certificate doesn't
+! lxc_remote remote add pki-lxd "${LXD5_ADDR}" --accept-certificate --password=foo || false
+
+kill_lxd "${LXD5_DIR}"

From 592eb0aedbc868ed5ce81ceefc659316a7c8e45b Mon Sep 17 00:00:00 2001
From: Miranda Huang <miranda061500 at gmail.com>
Date: Sun, 8 Dec 2019 18:06:07 -0600
Subject: [PATCH 2/5] test

---
 test/custom.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/test/custom.sh b/test/custom.sh
index 254d406271..2303579f5e 100644
--- a/test/custom.sh
+++ b/test/custom.sh
@@ -1,6 +1,6 @@
 #!/bin/sh -eu
 [ -n "${GOPATH:-}" ] && export "PATH=${GOPATH}/bin:${PATH}"
-export "TEST_DIR=~"
+export "TEST_DIR=."
 if [ ! -d "/usr/share/easy-rsa/" ]; then
   echo "==> SKIP: The pki test requires easy-rsa to be installed"
   return

From 5d906928264f030b6819f21c072bb36a9551005b Mon Sep 17 00:00:00 2001
From: Ubuntu <ubuntu at ip-172-31-84-43.ec2.internal>
Date: Mon, 9 Dec 2019 00:06:16 +0000
Subject: [PATCH 3/5] per

---
 test/custom.sh                      |   0
 test/openssl.cnf                    |   1 +
 test/pki/build-ca                   |   8 +
 test/pki/build-dh                   |  11 +
 test/pki/build-inter                |   7 +
 test/pki/build-key                  |   7 +
 test/pki/build-key-pass             |   7 +
 test/pki/build-key-pkcs12           |   8 +
 test/pki/build-key-server           |  10 +
 test/pki/build-req                  |   7 +
 test/pki/build-req-pass             |   7 +
 test/pki/clean-all                  |  16 ++
 test/pki/easy-rsa/build-ca          |   8 +
 test/pki/easy-rsa/build-dh          |  11 +
 test/pki/easy-rsa/build-inter       |   7 +
 test/pki/easy-rsa/build-key         |   7 +
 test/pki/easy-rsa/build-key-pass    |   7 +
 test/pki/easy-rsa/build-key-pkcs12  |   8 +
 test/pki/easy-rsa/build-key-server  |  10 +
 test/pki/easy-rsa/build-req         |   7 +
 test/pki/easy-rsa/build-req-pass    |   7 +
 test/pki/easy-rsa/clean-all         |  16 ++
 test/pki/easy-rsa/inherit-inter     |  39 +++
 test/pki/easy-rsa/list-crl          |  13 +
 test/pki/easy-rsa/openssl-0.9.6.cnf | 268 +++++++++++++++++++
 test/pki/easy-rsa/openssl-0.9.8.cnf | 293 ++++++++++++++++++++
 test/pki/easy-rsa/openssl-1.0.0.cnf | 288 ++++++++++++++++++++
 test/pki/easy-rsa/pkitool           | 399 ++++++++++++++++++++++++++++
 test/pki/easy-rsa/revoke-full       |  43 +++
 test/pki/easy-rsa/sign-req          |   7 +
 test/pki/easy-rsa/vars              |  80 ++++++
 test/pki/easy-rsa/whichopensslcnf   |  26 ++
 test/pki/inherit-inter              |  39 +++
 test/pki/keys/index.txt             |   0
 test/pki/keys/serial                |   1 +
 test/pki/list-crl                   |  13 +
 test/pki/openssl-0.9.6.cnf          | 268 +++++++++++++++++++
 test/pki/openssl-0.9.8.cnf          | 293 ++++++++++++++++++++
 test/pki/openssl-1.0.0.cnf          | 288 ++++++++++++++++++++
 test/pki/pkitool                    | 399 ++++++++++++++++++++++++++++
 test/pki/revoke-full                |  43 +++
 test/pki/sign-req                   |   7 +
 test/pki/vars                       |  80 ++++++
 test/pki/whichopensslcnf            |  26 ++
 44 files changed, 3090 insertions(+)
 mode change 100644 => 100755 test/custom.sh
 create mode 120000 test/openssl.cnf
 create mode 100755 test/pki/build-ca
 create mode 100755 test/pki/build-dh
 create mode 100755 test/pki/build-inter
 create mode 100755 test/pki/build-key
 create mode 100755 test/pki/build-key-pass
 create mode 100755 test/pki/build-key-pkcs12
 create mode 100755 test/pki/build-key-server
 create mode 100755 test/pki/build-req
 create mode 100755 test/pki/build-req-pass
 create mode 100755 test/pki/clean-all
 create mode 100755 test/pki/easy-rsa/build-ca
 create mode 100755 test/pki/easy-rsa/build-dh
 create mode 100755 test/pki/easy-rsa/build-inter
 create mode 100755 test/pki/easy-rsa/build-key
 create mode 100755 test/pki/easy-rsa/build-key-pass
 create mode 100755 test/pki/easy-rsa/build-key-pkcs12
 create mode 100755 test/pki/easy-rsa/build-key-server
 create mode 100755 test/pki/easy-rsa/build-req
 create mode 100755 test/pki/easy-rsa/build-req-pass
 create mode 100755 test/pki/easy-rsa/clean-all
 create mode 100755 test/pki/easy-rsa/inherit-inter
 create mode 100755 test/pki/easy-rsa/list-crl
 create mode 100644 test/pki/easy-rsa/openssl-0.9.6.cnf
 create mode 100644 test/pki/easy-rsa/openssl-0.9.8.cnf
 create mode 100644 test/pki/easy-rsa/openssl-1.0.0.cnf
 create mode 100755 test/pki/easy-rsa/pkitool
 create mode 100755 test/pki/easy-rsa/revoke-full
 create mode 100755 test/pki/easy-rsa/sign-req
 create mode 100644 test/pki/easy-rsa/vars
 create mode 100755 test/pki/easy-rsa/whichopensslcnf
 create mode 100755 test/pki/inherit-inter
 create mode 100644 test/pki/keys/index.txt
 create mode 100644 test/pki/keys/serial
 create mode 100755 test/pki/list-crl
 create mode 100644 test/pki/openssl-0.9.6.cnf
 create mode 100644 test/pki/openssl-0.9.8.cnf
 create mode 100644 test/pki/openssl-1.0.0.cnf
 create mode 100755 test/pki/pkitool
 create mode 100755 test/pki/revoke-full
 create mode 100755 test/pki/sign-req
 create mode 100644 test/pki/vars
 create mode 100755 test/pki/whichopensslcnf

diff --git a/test/custom.sh b/test/custom.sh
old mode 100644
new mode 100755
diff --git a/test/openssl.cnf b/test/openssl.cnf
new file mode 120000
index 0000000000..9cc2ab387f
--- /dev/null
+++ b/test/openssl.cnf
@@ -0,0 +1 @@
+openssl-1.0.0.cnf
\ No newline at end of file
diff --git a/test/pki/build-ca b/test/pki/build-ca
new file mode 100755
index 0000000000..bce29a6a3a
--- /dev/null
+++ b/test/pki/build-ca
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+#
+# Build a root certificate
+#
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --initca $*
diff --git a/test/pki/build-dh b/test/pki/build-dh
new file mode 100755
index 0000000000..4beb127fd8
--- /dev/null
+++ b/test/pki/build-dh
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+# Build Diffie-Hellman parameters for the server side
+# of an SSL/TLS connection.
+
+if [ -d $KEY_DIR ] && [ $KEY_SIZE ]; then
+    $OPENSSL dhparam -out ${KEY_DIR}/dh${KEY_SIZE}.pem ${KEY_SIZE}
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/build-inter b/test/pki/build-inter
new file mode 100755
index 0000000000..87bf98d4da
--- /dev/null
+++ b/test/pki/build-inter
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Make an intermediate CA certificate/private key pair using a locally generated
+# root certificate.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --inter $*
diff --git a/test/pki/build-key b/test/pki/build-key
new file mode 100755
index 0000000000..6c0fed82a4
--- /dev/null
+++ b/test/pki/build-key
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact $*
diff --git a/test/pki/build-key-pass b/test/pki/build-key-pass
new file mode 100755
index 0000000000..8ef830774a
--- /dev/null
+++ b/test/pki/build-key-pass
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Similar to build-key, but protect the private key
+# with a password.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --pass $*
diff --git a/test/pki/build-key-pkcs12 b/test/pki/build-key-pkcs12
new file mode 100755
index 0000000000..ba90e6adf2
--- /dev/null
+++ b/test/pki/build-key-pkcs12
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate and convert it to a PKCS #12 file including the
+# the CA certificate as well.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --pkcs12 $*
diff --git a/test/pki/build-key-server b/test/pki/build-key-server
new file mode 100755
index 0000000000..fee0194885
--- /dev/null
+++ b/test/pki/build-key-server
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate.
+#
+# Explicitly set nsCertType to server using the "server"
+# extension in the openssl.cnf file.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --server $*
diff --git a/test/pki/build-req b/test/pki/build-req
new file mode 100755
index 0000000000..559d512e8c
--- /dev/null
+++ b/test/pki/build-req
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Build a certificate signing request and private key.  Use this
+# when your root certificate and key is not available locally.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --csr $*
diff --git a/test/pki/build-req-pass b/test/pki/build-req-pass
new file mode 100755
index 0000000000..b73ee1b5ed
--- /dev/null
+++ b/test/pki/build-req-pass
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Like build-req, but protect your private key
+# with a password.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --csr --pass $*
diff --git a/test/pki/clean-all b/test/pki/clean-all
new file mode 100755
index 0000000000..b1d02374f4
--- /dev/null
+++ b/test/pki/clean-all
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+# Initialize the $KEY_DIR directory.
+# Note that this script does a
+# rm -rf on $KEY_DIR so be careful!
+
+if [ "$KEY_DIR" ]; then
+    rm -rf "$KEY_DIR"
+    mkdir "$KEY_DIR" && \
+        chmod go-rwx "$KEY_DIR" && \
+        touch "$KEY_DIR/index.txt" && \
+        echo 01 >"$KEY_DIR/serial"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/build-ca b/test/pki/easy-rsa/build-ca
new file mode 100755
index 0000000000..bce29a6a3a
--- /dev/null
+++ b/test/pki/easy-rsa/build-ca
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+#
+# Build a root certificate
+#
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --initca $*
diff --git a/test/pki/easy-rsa/build-dh b/test/pki/easy-rsa/build-dh
new file mode 100755
index 0000000000..4beb127fd8
--- /dev/null
+++ b/test/pki/easy-rsa/build-dh
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+# Build Diffie-Hellman parameters for the server side
+# of an SSL/TLS connection.
+
+if [ -d $KEY_DIR ] && [ $KEY_SIZE ]; then
+    $OPENSSL dhparam -out ${KEY_DIR}/dh${KEY_SIZE}.pem ${KEY_SIZE}
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/build-inter b/test/pki/easy-rsa/build-inter
new file mode 100755
index 0000000000..87bf98d4da
--- /dev/null
+++ b/test/pki/easy-rsa/build-inter
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Make an intermediate CA certificate/private key pair using a locally generated
+# root certificate.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --inter $*
diff --git a/test/pki/easy-rsa/build-key b/test/pki/easy-rsa/build-key
new file mode 100755
index 0000000000..6c0fed82a4
--- /dev/null
+++ b/test/pki/easy-rsa/build-key
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact $*
diff --git a/test/pki/easy-rsa/build-key-pass b/test/pki/easy-rsa/build-key-pass
new file mode 100755
index 0000000000..8ef830774a
--- /dev/null
+++ b/test/pki/easy-rsa/build-key-pass
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Similar to build-key, but protect the private key
+# with a password.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --pass $*
diff --git a/test/pki/easy-rsa/build-key-pkcs12 b/test/pki/easy-rsa/build-key-pkcs12
new file mode 100755
index 0000000000..ba90e6adf2
--- /dev/null
+++ b/test/pki/easy-rsa/build-key-pkcs12
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate and convert it to a PKCS #12 file including the
+# the CA certificate as well.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --pkcs12 $*
diff --git a/test/pki/easy-rsa/build-key-server b/test/pki/easy-rsa/build-key-server
new file mode 100755
index 0000000000..fee0194885
--- /dev/null
+++ b/test/pki/easy-rsa/build-key-server
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+# Make a certificate/private key pair using a locally generated
+# root certificate.
+#
+# Explicitly set nsCertType to server using the "server"
+# extension in the openssl.cnf file.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --server $*
diff --git a/test/pki/easy-rsa/build-req b/test/pki/easy-rsa/build-req
new file mode 100755
index 0000000000..559d512e8c
--- /dev/null
+++ b/test/pki/easy-rsa/build-req
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Build a certificate signing request and private key.  Use this
+# when your root certificate and key is not available locally.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --csr $*
diff --git a/test/pki/easy-rsa/build-req-pass b/test/pki/easy-rsa/build-req-pass
new file mode 100755
index 0000000000..b73ee1b5ed
--- /dev/null
+++ b/test/pki/easy-rsa/build-req-pass
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Like build-req, but protect your private key
+# with a password.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --csr --pass $*
diff --git a/test/pki/easy-rsa/clean-all b/test/pki/easy-rsa/clean-all
new file mode 100755
index 0000000000..b1d02374f4
--- /dev/null
+++ b/test/pki/easy-rsa/clean-all
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+# Initialize the $KEY_DIR directory.
+# Note that this script does a
+# rm -rf on $KEY_DIR so be careful!
+
+if [ "$KEY_DIR" ]; then
+    rm -rf "$KEY_DIR"
+    mkdir "$KEY_DIR" && \
+        chmod go-rwx "$KEY_DIR" && \
+        touch "$KEY_DIR/index.txt" && \
+        echo 01 >"$KEY_DIR/serial"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/inherit-inter b/test/pki/easy-rsa/inherit-inter
new file mode 100755
index 0000000000..1fe35396f5
--- /dev/null
+++ b/test/pki/easy-rsa/inherit-inter
@@ -0,0 +1,39 @@
+#!/bin/sh
+
+# Build a new PKI which is rooted on an intermediate certificate generated
+# by ./build-inter or ./pkitool --inter from a parent PKI.  The new PKI should
+# have independent vars settings, and must use a different KEY_DIR directory
+# from the parent.  This tool can be used to generate arbitrary depth
+# certificate chains.
+#
+# To build an intermediate CA, follow the same steps for a regular PKI but
+# replace ./build-key or ./pkitool --initca with this script.
+
+# The EXPORT_CA file will contain the CA certificate chain and should be
+# referenced by the OpenVPN "ca" directive in config files.  The ca.crt file
+# will only contain the local intermediate CA -- it's needed by the easy-rsa
+# scripts but not by OpenVPN directly.
+EXPORT_CA="export-ca.crt"
+
+if [ $# -ne 2 ]; then
+    echo "usage: $0 <parent-key-dir> <common-name>"
+    echo "parent-key-dir: the KEY_DIR directory of the parent PKI"
+    echo "common-name: the common name of the intermediate certificate in the parent PKI"
+    exit 1;
+fi
+
+if [ "$KEY_DIR" ]; then
+    cp "$1/$2.crt" "$KEY_DIR/ca.crt"
+    cp "$1/$2.key" "$KEY_DIR/ca.key"
+
+    if [ -e "$1/$EXPORT_CA" ]; then
+        PARENT_CA="$1/$EXPORT_CA"
+    else
+        PARENT_CA="$1/ca.crt"
+    fi
+    cp "$PARENT_CA" "$KEY_DIR/$EXPORT_CA"
+    cat "$KEY_DIR/ca.crt" >> "$KEY_DIR/$EXPORT_CA"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/list-crl b/test/pki/easy-rsa/list-crl
new file mode 100755
index 0000000000..32c1143024
--- /dev/null
+++ b/test/pki/easy-rsa/list-crl
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+# list revoked certificates
+
+CRL="${1:-crl.pem}"
+
+if [ "$KEY_DIR" ]; then
+    cd "$KEY_DIR" && \
+        $OPENSSL crl -text -noout -in "$CRL"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/openssl-0.9.6.cnf b/test/pki/easy-rsa/openssl-0.9.6.cnf
new file mode 100644
index 0000000000..fb08fea88f
--- /dev/null
+++ b/test/pki/easy-rsa/openssl-0.9.6.cnf
@@ -0,0 +1,268 @@
+# For use with easy-rsa version 2.0
+
+#
+# OpenSSL example configuration file.
+# This is mostly being used for generation of certificate requests.
+#
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		= 
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key	 	# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# which md to use.
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options. 
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString.
+# utf8only: only UTF8Strings.
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
+# so use this option with caution!
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType			= server
+nsComment			= "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
diff --git a/test/pki/easy-rsa/openssl-0.9.8.cnf b/test/pki/easy-rsa/openssl-0.9.8.cnf
new file mode 100644
index 0000000000..90331a0250
--- /dev/null
+++ b/test/pki/easy-rsa/openssl-0.9.8.cnf
@@ -0,0 +1,293 @@
+# For use with easy-rsa version 2.0
+
+#
+# OpenSSL example configuration file.
+# This is mostly being used for generation of certificate requests.
+#
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+openssl_conf		= openssl_init
+
+[ openssl_init ]
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+engines                 = engine_section
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		=
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key	 	# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# which md to use.
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options.
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString.
+# utf8only: only UTF8Strings.
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
+# so use this option with caution!
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+name				= Name
+name_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+name_default = $ENV::KEY_NAME
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType			= server
+nsComment			= "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
+
+[ engine_section ]
+#
+# If you are using PKCS#11
+# Install engine_pkcs11 of opensc (www.opensc.org)
+# And uncomment the following
+# verify that dynamic_path points to the correct location
+#
+#pkcs11 = pkcs11_section
+
+[ pkcs11_section ]
+engine_id = pkcs11
+dynamic_path = /usr/lib/engines/engine_pkcs11.so
+MODULE_PATH = $ENV::PKCS11_MODULE_PATH
+PIN = $ENV::PKCS11_PIN
+init = 0
diff --git a/test/pki/easy-rsa/openssl-1.0.0.cnf b/test/pki/easy-rsa/openssl-1.0.0.cnf
new file mode 100644
index 0000000000..c301e4457b
--- /dev/null
+++ b/test/pki/easy-rsa/openssl-1.0.0.cnf
@@ -0,0 +1,288 @@
+# For use with easy-rsa version 2.0 and OpenSSL 1.0.0*
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+openssl_conf		= openssl_init
+
+[ openssl_init ]
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+engines			= engine_section
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		=
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key		# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# use public key default MD
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options.
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString (PKIX recommendation after 2004).
+# utf8only: only UTF8Strings (PKIX recommendation after 2004).
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+name				= Name
+name_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+name_default = $ENV::KEY_NAME
+
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType                     = server
+nsComment                      = "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
+
+[ engine_section ]
+#
+# If you are using PKCS#11
+# Install engine_pkcs11 of opensc (www.opensc.org)
+# And uncomment the following
+# verify that dynamic_path points to the correct location
+#
+#pkcs11 = pkcs11_section
+
+[ pkcs11_section ]
+engine_id = pkcs11
+dynamic_path = /usr/lib/engines/engine_pkcs11.so
+MODULE_PATH = $ENV::PKCS11_MODULE_PATH
+PIN = $ENV::PKCS11_PIN
+init = 0
diff --git a/test/pki/easy-rsa/pkitool b/test/pki/easy-rsa/pkitool
new file mode 100755
index 0000000000..44145ad7e0
--- /dev/null
+++ b/test/pki/easy-rsa/pkitool
@@ -0,0 +1,399 @@
+#!/bin/sh
+
+#  OpenVPN -- An application to securely tunnel IP networks
+#             over a single TCP/UDP port, with support for SSL/TLS-based
+#             session authentication and key exchange,
+#             packet encryption, packet authentication, and
+#             packet compression.
+#
+#  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales at openvpn.net>
+#
+#  This program is free software; you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License version 2
+#  as published by the Free Software Foundation.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program (see the file COPYING included with this
+#  distribution); if not, write to the Free Software Foundation, Inc.,
+#  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+# pkitool is a front-end for the openssl tool.
+
+# Calling scripts can set the certificate organizational
+# unit with the KEY_OU environmental variable.
+
+# Calling scripts can also set the KEY_NAME environmental
+# variable to set the "name" X509 subject field.
+
+PROGNAME=pkitool
+VERSION=2.0
+DEBUG=0
+
+die()
+{
+    local m="$1"
+
+    echo "$m" >&2
+    exit 1
+}
+
+need_vars()
+{
+    cat <<EOM
+  Please edit the vars script to reflect your configuration,
+  then source it with "source ./vars".
+  Next, to start with a fresh PKI configuration and to delete any
+  previous certificates and keys, run "./clean-all".
+  Finally, you can run this tool ($PROGNAME) to build certificates/keys.
+EOM
+}
+
+usage()
+{
+    cat <<EOM
+$PROGNAME $VERSION
+Usage: $PROGNAME [options...] [common-name]
+
+Options:
+  --batch    : batch mode (default)
+  --keysize  : Set keysize
+      size   : size (default=1024)
+  --interact : interactive mode
+  --server   : build server cert
+  --initca   : build root CA
+  --inter    : build intermediate CA
+  --pass     : encrypt private key with password
+  --csr      : only generate a CSR, do not sign
+  --sign     : sign an existing CSR
+  --pkcs12   : generate a combined PKCS#12 file
+  --pkcs11   : generate certificate on PKCS#11 token
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+      id     : PKCS#11 object id (hex string)
+      label  : PKCS#11 object label
+
+Standalone options:
+  --pkcs11-slots   : list PKCS#11 slots
+      lib    : PKCS#11 library
+  --pkcs11-objects : list PKCS#11 token objects
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+  --pkcs11-init    : initialize PKCS#11 token DANGEROUS!!!
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+      label  : PKCS#11 token label
+
+Notes:
+EOM
+    need_vars
+    cat <<EOM
+  In order to use PKCS#11 interface you must have opensc-0.10.0 or higher.
+
+Generated files and corresponding OpenVPN directives:
+(Files will be placed in the \$KEY_DIR directory, defined in ./vars)
+  ca.crt     -> root certificate (--ca)
+  ca.key     -> root key, keep secure (not directly used by OpenVPN)
+  .crt files -> client/server certificates (--cert)
+  .key files -> private keys, keep secure (--key)
+  .csr files -> certificate signing request (not directly used by OpenVPN)
+  dh1024.pem or dh2048.pem -> Diffie Hellman parameters (--dh)
+
+Examples:
+  $PROGNAME --initca          -> Build root certificate
+  $PROGNAME --initca --pass   -> Build root certificate with password-protected key
+  $PROGNAME --server server1  -> Build "server1" certificate/key
+  $PROGNAME client1           -> Build "client1" certificate/key
+  $PROGNAME --pass client2    -> Build password-protected "client2" certificate/key
+  $PROGNAME --pkcs12 client3  -> Build "client3" certificate/key in PKCS#12 format
+  $PROGNAME --csr client4     -> Build "client4" CSR to be signed by another CA
+  $PROGNAME --sign client4    -> Sign "client4" CSR
+  $PROGNAME --inter interca   -> Build an intermediate key-signing certificate/key
+                               Also see ./inherit-inter script.
+  $PROGNAME --pkcs11 /usr/lib/pkcs11/lib1 0 010203 "client5 id" client5
+                              -> Build "client5" certificate/key in PKCS#11 token
+
+Typical usage for initial PKI setup.  Build myserver, client1, and client2 cert/keys.
+Protect client2 key with a password.  Build DH parms.  Generated files in ./keys :
+  [edit vars with your site-specific info]
+  source ./vars
+  ./clean-all
+  ./build-dh     -> takes a long time, consider backgrounding
+  ./$PROGNAME --initca
+  ./$PROGNAME --server myserver
+  ./$PROGNAME client1
+  ./$PROGNAME --pass client2
+
+Typical usage for adding client cert to existing PKI:
+  source ./vars
+  ./$PROGNAME client-new
+EOM
+}
+
+# Set tool defaults
+[ -n "$OPENSSL" ] || export OPENSSL="openssl"
+[ -n "$PKCS11TOOL" ] || export PKCS11TOOL="pkcs11-tool"
+[ -n "$GREP" ] || export GREP="grep"
+
+# Set defaults
+DO_REQ="1"
+REQ_EXT=""
+DO_CA="1"
+CA_EXT=""
+DO_P12="0"
+DO_P11="0"
+DO_ROOT="0"
+NODES_REQ="-nodes"
+NODES_P12=""
+BATCH="-batch"
+CA="ca"
+# must be set or errors of openssl.cnf
+PKCS11_MODULE_PATH="dummy"
+PKCS11_PIN="dummy"
+
+# Process options
+while [ $# -gt 0 ]; do
+    case "$1" in
+        --keysize  ) KEY_SIZE=$2
+                     shift;;
+        --server   ) REQ_EXT="$REQ_EXT -extensions server"
+                     CA_EXT="$CA_EXT -extensions server" ;;
+        --batch    ) BATCH="-batch" ;;
+        --interact ) BATCH="" ;;
+        --inter    ) CA_EXT="$CA_EXT -extensions v3_ca" ;;
+        --initca   ) DO_ROOT="1" ;;
+        --pass     ) NODES_REQ="" ;;
+        --csr      ) DO_CA="0" ;;
+        --sign     ) DO_REQ="0" ;;
+        --pkcs12   ) DO_P12="1" ;;
+        --pkcs11   ) DO_P11="1"
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     PKCS11_ID="$4"
+                     PKCS11_LABEL="$5"
+                     shift 4;;
+
+        # standalone
+        --pkcs11-init)
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     PKCS11_LABEL="$4"
+                     if [ -z "$PKCS11_LABEL" ]; then
+                       die "Please specify library name, slot and label"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --init-token --slot "$PKCS11_SLOT" \
+                             --label "$PKCS11_LABEL" &&
+                        $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --init-pin --slot "$PKCS11_SLOT"
+                     exit $?;;
+        --pkcs11-slots)
+                     PKCS11_MODULE_PATH="$2"
+                     if [ -z "$PKCS11_MODULE_PATH" ]; then
+                       die "Please specify library name"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --list-slots
+                     exit 0;;
+        --pkcs11-objects)
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     if [ -z "$PKCS11_SLOT" ]; then
+                       die "Please specify library name and slot"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --list-objects --login --slot "$PKCS11_SLOT"
+                     exit 0;;
+
+        --help|--usage)
+                    usage
+                    exit ;;
+        --version)
+                    echo "$PROGNAME $VERSION"
+                    exit ;;
+        # errors
+        --*        ) die "$PROGNAME: unknown option: $1" ;;
+        *          ) break ;;
+    esac
+    shift
+done
+
+if ! [ -z "$BATCH" ]; then
+        if $OPENSSL version | grep 0.9.6 > /dev/null; then
+                die "Batch mode is unsupported in openssl<0.9.7"
+        fi
+fi
+
+if [ $DO_P12 -eq 1 -a $DO_P11 -eq 1 ]; then
+        die "PKCS#11 and PKCS#12 cannot be specified together"
+fi
+
+if [ $DO_P11 -eq 1 ]; then
+        if ! grep "^pkcs11.*=" "$KEY_CONFIG" > /dev/null; then
+                die "Please edit $KEY_CONFIG and setup PKCS#11 engine"
+        fi
+fi
+
+# If we are generating pkcs12, only encrypt the final step
+if [ $DO_P12 -eq 1 ]; then
+    NODES_P12="$NODES_REQ"
+    NODES_REQ="-nodes"
+fi
+
+if [ $DO_P11 -eq 1 ]; then
+    if [ -z "$PKCS11_LABEL" ]; then
+        die "PKCS#11 arguments incomplete"
+    fi
+fi
+
+# If undefined, set default key expiration intervals
+if [ -z "$KEY_EXPIRE" ]; then
+    KEY_EXPIRE=3650
+fi
+if [ -z "$CA_EXPIRE" ]; then
+    CA_EXPIRE=3650
+fi
+
+# Set organizational unit to empty string if undefined
+if [ -z "$KEY_OU" ]; then
+    KEY_OU=""
+fi
+
+# Set X509 Name string to empty string if undefined
+if [ -z "$KEY_NAME" ]; then
+    KEY_NAME=""
+fi
+
+# Set KEY_CN, FN
+if [ $DO_ROOT -eq 1 ]; then
+    if [ -z "$KEY_CN" ]; then
+        if [ "$1" ]; then
+            KEY_CN="$1"
+	    KEY_ALTNAMES="DNS:${KEY_CN}"
+        elif [ "$KEY_ORG" ]; then
+            KEY_CN="$KEY_ORG CA"
+	    KEY_ALTNAMES="$KEY_CN"
+        fi
+    fi
+    if [ $BATCH ] && [ "$KEY_CN" ]; then
+        echo "Using CA Common Name:" "$KEY_CN"
+	KEY_ALTNAMES="$KEY_CN"
+    fi
+    FN="$KEY_CN"
+elif [ $BATCH ] && [ "$KEY_CN" ]; then
+    echo "Using Common Name:" "$KEY_CN"
+    KEY_ALTNAMES="$KEY_CN"
+    FN="$KEY_CN"
+    if [ "$1" ]; then
+        FN="$1"
+    fi
+else
+    KEY_CN="$1"
+    KEY_ALTNAMES="DNS:$1"
+    shift
+    while [ "x$1" != "x" ]
+    do
+        KEY_ALTNAMES="${KEY_ALTNAMES},DNS:$1"
+        shift
+    done
+    FN="$KEY_CN"
+fi
+
+export CA_EXPIRE KEY_EXPIRE KEY_OU KEY_NAME KEY_CN PKCS11_MODULE_PATH PKCS11_PIN KEY_ALTNAMES
+
+# Show parameters (debugging)
+if [ $DEBUG -eq 1 ]; then
+    echo DO_REQ $DO_REQ
+    echo REQ_EXT $REQ_EXT
+    echo DO_CA $DO_CA
+    echo CA_EXT $CA_EXT
+    echo NODES_REQ $NODES_REQ
+    echo NODES_P12 $NODES_P12
+    echo DO_P12 $DO_P12
+    echo KEY_CN $KEY_CN
+    echo KEY_ALTNAMES $KEY_ALTNAMES
+    echo BATCH $BATCH
+    echo DO_ROOT $DO_ROOT
+    echo KEY_EXPIRE $KEY_EXPIRE
+    echo CA_EXPIRE $CA_EXPIRE
+    echo KEY_OU $KEY_OU
+    echo KEY_NAME $KEY_NAME
+    echo DO_P11 $DO_P11
+    echo PKCS11_MODULE_PATH $PKCS11_MODULE_PATH
+    echo PKCS11_SLOT $PKCS11_SLOT
+    echo PKCS11_ID $PKCS11_ID
+    echo PKCS11_LABEL $PKCS11_LABEL
+fi
+
+# Make sure ./vars was sourced beforehand
+if [ -d "$KEY_DIR" ] && [ "$KEY_CONFIG" ]; then
+    cd "$KEY_DIR"
+
+    # Make sure $KEY_CONFIG points to the correct version
+    # of openssl.cnf
+    if $GREP -i 'easy-rsa version 2\.[0-9]' "$KEY_CONFIG" >/dev/null; then
+        :
+    else
+        echo "$PROGNAME: KEY_CONFIG (set by the ./vars script) is pointing to the wrong"
+        echo "version of openssl.cnf: $KEY_CONFIG"
+        echo "The correct version should have a comment that says: easy-rsa version 2.x";
+        exit 1;
+    fi
+
+    # Build root CA
+    if [ $DO_ROOT -eq 1 ]; then
+        $OPENSSL req $BATCH -days $CA_EXPIRE $NODES_REQ -new -newkey rsa:$KEY_SIZE \
+            -x509 -keyout "$CA.key" -out "$CA.crt" -config "$KEY_CONFIG" && \
+            chmod 0600 "$CA.key"
+    else
+        # Make sure CA key/cert is available
+        if [ $DO_CA -eq 1 ] || [ $DO_P12 -eq 1 ]; then
+            if [ ! -r "$CA.crt" ] || [ ! -r "$CA.key" ]; then
+                echo "$PROGNAME: Need a readable $CA.crt and $CA.key in $KEY_DIR"
+                echo "Try $PROGNAME --initca to build a root certificate/key."
+                exit 1
+            fi
+        fi
+
+        # Generate key for PKCS#11 token
+        PKCS11_ARGS=
+        if [ $DO_P11 -eq 1 ]; then
+                stty -echo
+                echo -n "User PIN: "
+                read -r PKCS11_PIN
+                stty echo
+                export PKCS11_PIN
+
+                echo "Generating key pair on PKCS#11 token..."
+                $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --keypairgen \
+                        --login --pin "$PKCS11_PIN" \
+                        --key-type rsa:1024 \
+                        --slot "$PKCS11_SLOT" --id "$PKCS11_ID" --label "$PKCS11_LABEL" || exit 1
+                PKCS11_ARGS="-engine pkcs11 -keyform engine -key $PKCS11_SLOT:$PKCS11_ID"
+        fi
+
+        # Build cert/key
+        ( [ $DO_REQ -eq 0 ] || $OPENSSL req $BATCH $NODES_REQ -new -newkey rsa:$KEY_SIZE \
+                -keyout "$FN.key" -out "$FN.csr" $REQ_EXT -config "$KEY_CONFIG" $PKCS11_ARGS ) && \
+            ( [ $DO_CA -eq 0 ]  || $OPENSSL ca $BATCH -days $KEY_EXPIRE -out "$FN.crt" \
+                -in "$FN.csr" $CA_EXT -config "$KEY_CONFIG" ) && \
+            ( [ $DO_P12 -eq 0 ] || $OPENSSL pkcs12 -export -inkey "$FN.key" \
+                -in "$FN.crt" -certfile "$CA.crt" -out "$FN.p12" $NODES_P12 ) && \
+            ( [ $DO_CA -eq 0 -o $DO_P11 -eq 1 ]  || chmod 0600 "$FN.key" ) && \
+            ( [ $DO_P12 -eq 0 ] || chmod 0600 "$FN.p12" )
+
+        # Load certificate into PKCS#11 token
+        if [ $DO_P11 -eq 1 ]; then
+                $OPENSSL x509 -in "$FN.crt" -inform PEM -out "$FN.crt.der" -outform DER && \
+                  $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --write-object "$FN.crt.der" --type cert \
+                        --login --pin "$PKCS11_PIN" \
+                        --slot "$PKCS11_SLOT" --id "$PKCS11_ID" --label "$PKCS11_LABEL"
+                [ -e "$FN.crt.der" ]; rm "$FN.crt.der"
+        fi
+
+    fi
+
+# Need definitions
+else
+    need_vars
+fi
diff --git a/test/pki/easy-rsa/revoke-full b/test/pki/easy-rsa/revoke-full
new file mode 100755
index 0000000000..e9c7d02518
--- /dev/null
+++ b/test/pki/easy-rsa/revoke-full
@@ -0,0 +1,43 @@
+#!/bin/sh
+
+# revoke a certificate, regenerate CRL,
+# and verify revocation
+
+CRL="crl.pem"
+RT="revoke-test.pem"
+
+if [ $# -ne 1 ]; then
+    echo "usage: revoke-full <cert-name-base>";
+    exit 1
+fi
+
+if [ "$KEY_DIR" ]; then
+    cd "$KEY_DIR"
+    rm -f "$RT"
+
+    # set defaults
+    export KEY_CN=""
+    export KEY_OU=""
+    export KEY_NAME=""
+
+	# required due to hack in openssl.cnf that supports Subject Alternative Names
+    export KEY_ALTNAMES=""
+
+    # revoke key and generate a new CRL
+    $OPENSSL ca -revoke "$1.crt" -config "$KEY_CONFIG"
+
+    # generate a new CRL -- try to be compatible with
+    # intermediate PKIs
+    $OPENSSL ca -gencrl -out "$CRL" -config "$KEY_CONFIG"
+    if [ -e export-ca.crt ]; then
+        cat export-ca.crt "$CRL" >"$RT"
+    else
+        cat ca.crt "$CRL" >"$RT"
+    fi
+
+    # verify the revocation
+    $OPENSSL verify -CAfile "$RT" -crl_check "$1.crt"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/easy-rsa/sign-req b/test/pki/easy-rsa/sign-req
new file mode 100755
index 0000000000..6cae7b4e6d
--- /dev/null
+++ b/test/pki/easy-rsa/sign-req
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Sign a certificate signing request (a .csr file)
+# with a local root certificate and key.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --sign $*
diff --git a/test/pki/easy-rsa/vars b/test/pki/easy-rsa/vars
new file mode 100644
index 0000000000..e60420c44a
--- /dev/null
+++ b/test/pki/easy-rsa/vars
@@ -0,0 +1,80 @@
+# easy-rsa parameter settings
+
+# NOTE: If you installed from an RPM,
+# don't edit this file in place in
+# /usr/share/openvpn/easy-rsa --
+# instead, you should copy the whole
+# easy-rsa directory to another location
+# (such as /etc/openvpn) so that your
+# edits will not be wiped out by a future
+# OpenVPN package upgrade.
+
+# This variable should point to
+# the top level of the easy-rsa
+# tree.
+export EASY_RSA="`pwd`"
+
+#
+# This variable should point to
+# the requested executables
+#
+export OPENSSL="openssl"
+export PKCS11TOOL="pkcs11-tool"
+export GREP="grep"
+
+
+# This variable should point to
+# the openssl.cnf file included
+# with easy-rsa.
+export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
+
+# Edit this variable to point to
+# your soon-to-be-created key
+# directory.
+#
+# WARNING: clean-all will do
+# a rm -rf on this directory
+# so make sure you define
+# it correctly!
+export KEY_DIR="$EASY_RSA/keys"
+
+# Issue rm -rf warning
+echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
+
+# PKCS11 fixes
+export PKCS11_MODULE_PATH="dummy"
+export PKCS11_PIN="dummy"
+
+# Increase this to 2048 if you
+# are paranoid.  This will slow
+# down TLS negotiation performance
+# as well as the one-time DH parms
+# generation process.
+export KEY_SIZE=2048
+
+# In how many days should the root CA key expire?
+export CA_EXPIRE=3650
+
+# In how many days should certificates expire?
+export KEY_EXPIRE=3650
+
+# These are the default values for fields
+# which will be placed in the certificate.
+# Don't leave any of these fields blank.
+export KEY_COUNTRY="US"
+export KEY_PROVINCE="CA"
+export KEY_CITY="SanFrancisco"
+export KEY_ORG="Fort-Funston"
+export KEY_EMAIL="me at myhost.mydomain"
+export KEY_OU="MyOrganizationalUnit"
+
+# X509 Subject Field
+export KEY_NAME="EasyRSA"
+
+# PKCS11 Smart Card
+# export PKCS11_MODULE_PATH="/usr/lib/changeme.so"
+# export PKCS11_PIN=1234
+
+# If you'd like to sign all keys with the same Common Name, uncomment the KEY_CN export below
+# You will also need to make sure your OpenVPN server config has the duplicate-cn option set
+# export KEY_CN="CommonName"
diff --git a/test/pki/easy-rsa/whichopensslcnf b/test/pki/easy-rsa/whichopensslcnf
new file mode 100755
index 0000000000..4c5f3c7d8e
--- /dev/null
+++ b/test/pki/easy-rsa/whichopensslcnf
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+cnf="$1/openssl.cnf"
+
+if [ "$OPENSSL" ]; then
+    if $OPENSSL version | grep -E "0\.9\.6[[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-0.9.6.cnf"
+    elif $OPENSSL version | grep -E "0\.9\.8[[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-0.9.8.cnf"
+    elif $OPENSSL version | grep -E "1\.0\.[[:digit:]][[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-1.0.0.cnf"
+    else
+        cnf="$1/openssl.cnf"
+    fi
+fi
+
+echo $cnf
+
+if [ ! -r $cnf ]; then
+    echo "**************************************************************" >&2
+    echo "  No $cnf file could be found" >&2
+    echo "  Further invocations will fail" >&2
+    echo "**************************************************************" >&2
+fi
+
+exit 0
diff --git a/test/pki/inherit-inter b/test/pki/inherit-inter
new file mode 100755
index 0000000000..1fe35396f5
--- /dev/null
+++ b/test/pki/inherit-inter
@@ -0,0 +1,39 @@
+#!/bin/sh
+
+# Build a new PKI which is rooted on an intermediate certificate generated
+# by ./build-inter or ./pkitool --inter from a parent PKI.  The new PKI should
+# have independent vars settings, and must use a different KEY_DIR directory
+# from the parent.  This tool can be used to generate arbitrary depth
+# certificate chains.
+#
+# To build an intermediate CA, follow the same steps for a regular PKI but
+# replace ./build-key or ./pkitool --initca with this script.
+
+# The EXPORT_CA file will contain the CA certificate chain and should be
+# referenced by the OpenVPN "ca" directive in config files.  The ca.crt file
+# will only contain the local intermediate CA -- it's needed by the easy-rsa
+# scripts but not by OpenVPN directly.
+EXPORT_CA="export-ca.crt"
+
+if [ $# -ne 2 ]; then
+    echo "usage: $0 <parent-key-dir> <common-name>"
+    echo "parent-key-dir: the KEY_DIR directory of the parent PKI"
+    echo "common-name: the common name of the intermediate certificate in the parent PKI"
+    exit 1;
+fi
+
+if [ "$KEY_DIR" ]; then
+    cp "$1/$2.crt" "$KEY_DIR/ca.crt"
+    cp "$1/$2.key" "$KEY_DIR/ca.key"
+
+    if [ -e "$1/$EXPORT_CA" ]; then
+        PARENT_CA="$1/$EXPORT_CA"
+    else
+        PARENT_CA="$1/ca.crt"
+    fi
+    cp "$PARENT_CA" "$KEY_DIR/$EXPORT_CA"
+    cat "$KEY_DIR/ca.crt" >> "$KEY_DIR/$EXPORT_CA"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/keys/index.txt b/test/pki/keys/index.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/test/pki/keys/serial b/test/pki/keys/serial
new file mode 100644
index 0000000000..8a0f05e166
--- /dev/null
+++ b/test/pki/keys/serial
@@ -0,0 +1 @@
+01
diff --git a/test/pki/list-crl b/test/pki/list-crl
new file mode 100755
index 0000000000..32c1143024
--- /dev/null
+++ b/test/pki/list-crl
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+# list revoked certificates
+
+CRL="${1:-crl.pem}"
+
+if [ "$KEY_DIR" ]; then
+    cd "$KEY_DIR" && \
+        $OPENSSL crl -text -noout -in "$CRL"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/openssl-0.9.6.cnf b/test/pki/openssl-0.9.6.cnf
new file mode 100644
index 0000000000..fb08fea88f
--- /dev/null
+++ b/test/pki/openssl-0.9.6.cnf
@@ -0,0 +1,268 @@
+# For use with easy-rsa version 2.0
+
+#
+# OpenSSL example configuration file.
+# This is mostly being used for generation of certificate requests.
+#
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		= 
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key	 	# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# which md to use.
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options. 
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString.
+# utf8only: only UTF8Strings.
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
+# so use this option with caution!
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType			= server
+nsComment			= "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
diff --git a/test/pki/openssl-0.9.8.cnf b/test/pki/openssl-0.9.8.cnf
new file mode 100644
index 0000000000..90331a0250
--- /dev/null
+++ b/test/pki/openssl-0.9.8.cnf
@@ -0,0 +1,293 @@
+# For use with easy-rsa version 2.0
+
+#
+# OpenSSL example configuration file.
+# This is mostly being used for generation of certificate requests.
+#
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+openssl_conf		= openssl_init
+
+[ openssl_init ]
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+engines                 = engine_section
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		=
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key	 	# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# which md to use.
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options.
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString.
+# utf8only: only UTF8Strings.
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
+# so use this option with caution!
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+name				= Name
+name_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+name_default = $ENV::KEY_NAME
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType			= server
+nsComment			= "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
+
+[ engine_section ]
+#
+# If you are using PKCS#11
+# Install engine_pkcs11 of opensc (www.opensc.org)
+# And uncomment the following
+# verify that dynamic_path points to the correct location
+#
+#pkcs11 = pkcs11_section
+
+[ pkcs11_section ]
+engine_id = pkcs11
+dynamic_path = /usr/lib/engines/engine_pkcs11.so
+MODULE_PATH = $ENV::PKCS11_MODULE_PATH
+PIN = $ENV::PKCS11_PIN
+init = 0
diff --git a/test/pki/openssl-1.0.0.cnf b/test/pki/openssl-1.0.0.cnf
new file mode 100644
index 0000000000..c301e4457b
--- /dev/null
+++ b/test/pki/openssl-1.0.0.cnf
@@ -0,0 +1,288 @@
+# For use with easy-rsa version 2.0 and OpenSSL 1.0.0*
+
+# This definition stops the following lines choking if HOME isn't
+# defined.
+HOME			= .
+RANDFILE		= $ENV::HOME/.rnd
+openssl_conf		= openssl_init
+
+[ openssl_init ]
+# Extra OBJECT IDENTIFIER info:
+#oid_file		= $ENV::HOME/.oid
+oid_section		= new_oids
+engines			= engine_section
+
+# To use this configuration file with the "-extfile" option of the
+# "openssl x509" utility, name here the section containing the
+# X.509v3 extensions to use:
+# extensions		=
+# (Alternatively, use a configuration file that has only
+# X.509v3 extensions in its main [= default] section.)
+
+[ new_oids ]
+
+# We can add new OIDs in here for use by 'ca' and 'req'.
+# Add a simple OID like this:
+# testoid1=1.2.3.4
+# Or use config file substitution like this:
+# testoid2=${testoid1}.5.6
+
+####################################################################
+[ ca ]
+default_ca	= CA_default		# The default ca section
+
+####################################################################
+[ CA_default ]
+
+dir		= $ENV::KEY_DIR		# Where everything is kept
+certs		= $dir			# Where the issued certs are kept
+crl_dir		= $dir			# Where the issued crl are kept
+database	= $dir/index.txt	# database index file.
+new_certs_dir	= $dir			# default place for new certs.
+
+certificate	= $dir/ca.crt	 	# The CA certificate
+serial		= $dir/serial 		# The current serial number
+crl		= $dir/crl.pem 		# The current CRL
+private_key	= $dir/ca.key		# The private key
+RANDFILE	= $dir/.rand		# private random number file
+
+x509_extensions	= usr_cert		# The extentions to add to the cert
+
+# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
+# so this is commented out by default to leave a V1 CRL.
+# crl_extensions	= crl_ext
+
+default_days	= 3650			# how long to certify for
+default_crl_days= 30			# how long before next CRL
+default_md	= sha256		# use public key default MD
+preserve	= no			# keep passed DN ordering
+
+# A few difference way of specifying how similar the request should look
+# For type CA, the listed attributes must be the same, and the optional
+# and supplied fields are just that :-)
+policy		= policy_anything
+
+# For the CA policy
+[ policy_match ]
+countryName		= match
+stateOrProvinceName	= match
+organizationName	= match
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+# For the 'anything' policy
+# At this point in time, you must list all acceptable 'object'
+# types.
+[ policy_anything ]
+countryName		= optional
+stateOrProvinceName	= optional
+localityName		= optional
+organizationName	= optional
+organizationalUnitName	= optional
+commonName		= supplied
+name			= optional
+emailAddress		= optional
+
+####################################################################
+[ req ]
+default_bits		= $ENV::KEY_SIZE
+default_keyfile 	= privkey.pem
+default_md		= sha256
+distinguished_name	= req_distinguished_name
+attributes		= req_attributes
+x509_extensions	= v3_ca	# The extentions to add to the self signed cert
+
+# Passwords for private keys if not present they will be prompted for
+# input_password = secret
+# output_password = secret
+
+# This sets a mask for permitted string types. There are several options.
+# default: PrintableString, T61String, BMPString.
+# pkix	 : PrintableString, BMPString (PKIX recommendation after 2004).
+# utf8only: only UTF8Strings (PKIX recommendation after 2004).
+# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
+# MASK:XXXX a literal mask value.
+string_mask = nombstr
+
+# req_extensions = v3_req # The extensions to add to a certificate request
+
+[ req_distinguished_name ]
+countryName			= Country Name (2 letter code)
+countryName_default		= $ENV::KEY_COUNTRY
+countryName_min			= 2
+countryName_max			= 2
+
+stateOrProvinceName		= State or Province Name (full name)
+stateOrProvinceName_default	= $ENV::KEY_PROVINCE
+
+localityName			= Locality Name (eg, city)
+localityName_default		= $ENV::KEY_CITY
+
+0.organizationName		= Organization Name (eg, company)
+0.organizationName_default	= $ENV::KEY_ORG
+
+# we can do this but it is not needed normally :-)
+#1.organizationName		= Second Organization Name (eg, company)
+#1.organizationName_default	= World Wide Web Pty Ltd
+
+organizationalUnitName		= Organizational Unit Name (eg, section)
+#organizationalUnitName_default	=
+
+commonName			= Common Name (eg, your name or your server\'s hostname)
+commonName_max			= 64
+
+name				= Name
+name_max			= 64
+
+emailAddress			= Email Address
+emailAddress_default		= $ENV::KEY_EMAIL
+emailAddress_max		= 40
+
+# JY -- added for batch mode
+organizationalUnitName_default = $ENV::KEY_OU
+commonName_default = $ENV::KEY_CN
+name_default = $ENV::KEY_NAME
+
+
+# SET-ex3			= SET extension number 3
+
+[ req_attributes ]
+challengePassword		= A challenge password
+challengePassword_min		= 4
+challengePassword_max		= 20
+
+unstructuredName		= An optional company name
+
+[ usr_cert ]
+
+# These extensions are added when 'ca' signs a request.
+
+# This goes against PKIX guidelines but some CAs do it and some software
+# requires this to avoid interpreting an end user certificate as a CA.
+
+basicConstraints=CA:FALSE
+
+# Here are some examples of the usage of nsCertType. If it is omitted
+# the certificate can be used for anything *except* object signing.
+
+# This is OK for an SSL server.
+# nsCertType			= server
+
+# For an object signing certificate this would be used.
+# nsCertType = objsign
+
+# For normal client use this is typical
+# nsCertType = client, email
+
+# and for everything including object signing:
+# nsCertType = client, email, objsign
+
+# This is typical in keyUsage for a client certificate.
+# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+# This will be displayed in Netscape's comment listbox.
+nsComment			= "Easy-RSA Generated Certificate"
+
+# PKIX recommendations harmless if included in all certificates.
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=clientAuth
+keyUsage = digitalSignature
+
+
+# This stuff is for subjectAltName and issuerAltname.
+# Import the email address.
+# subjectAltName=email:copy
+subjectAltName=$ENV::KEY_ALTNAMES
+
+# Copy subject details
+# issuerAltName=issuer:copy
+
+#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
+#nsBaseUrl
+#nsRevocationUrl
+#nsRenewalUrl
+#nsCaPolicyUrl
+#nsSslServerName
+
+[ server ]
+
+# JY ADDED -- Make a cert with nsCertType set to "server"
+basicConstraints=CA:FALSE
+nsCertType                     = server
+nsComment                      = "Easy-RSA Generated Server Certificate"
+subjectKeyIdentifier=hash
+authorityKeyIdentifier=keyid,issuer:always
+extendedKeyUsage=serverAuth
+keyUsage = digitalSignature, keyEncipherment
+subjectAltName=$ENV::KEY_ALTNAMES
+
+[ v3_req ]
+
+# Extensions to add to a certificate request
+
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+
+[ v3_ca ]
+
+
+# Extensions for a typical CA
+
+
+# PKIX recommendation.
+
+subjectKeyIdentifier=hash
+
+authorityKeyIdentifier=keyid:always,issuer:always
+
+# This is what PKIX recommends but some broken software chokes on critical
+# extensions.
+#basicConstraints = critical,CA:true
+# So we do this instead.
+basicConstraints = CA:true
+
+# Key usage: this is typical for a CA certificate. However since it will
+# prevent it being used as an test self-signed certificate it is best
+# left out by default.
+# keyUsage = cRLSign, keyCertSign
+
+# Some might want this also
+# nsCertType = sslCA, emailCA
+
+# Include email address in subject alt name: another PKIX recommendation
+# subjectAltName=email:copy
+# Copy issuer details
+# issuerAltName=issuer:copy
+
+# DER hex encoding of an extension: beware experts only!
+# obj=DER:02:03
+# Where 'obj' is a standard or added object
+# You can even override a supported extension:
+# basicConstraints= critical, DER:30:03:01:01:FF
+
+[ crl_ext ]
+
+# CRL extensions.
+# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
+
+# issuerAltName=issuer:copy
+authorityKeyIdentifier=keyid:always,issuer:always
+
+[ engine_section ]
+#
+# If you are using PKCS#11
+# Install engine_pkcs11 of opensc (www.opensc.org)
+# And uncomment the following
+# verify that dynamic_path points to the correct location
+#
+#pkcs11 = pkcs11_section
+
+[ pkcs11_section ]
+engine_id = pkcs11
+dynamic_path = /usr/lib/engines/engine_pkcs11.so
+MODULE_PATH = $ENV::PKCS11_MODULE_PATH
+PIN = $ENV::PKCS11_PIN
+init = 0
diff --git a/test/pki/pkitool b/test/pki/pkitool
new file mode 100755
index 0000000000..44145ad7e0
--- /dev/null
+++ b/test/pki/pkitool
@@ -0,0 +1,399 @@
+#!/bin/sh
+
+#  OpenVPN -- An application to securely tunnel IP networks
+#             over a single TCP/UDP port, with support for SSL/TLS-based
+#             session authentication and key exchange,
+#             packet encryption, packet authentication, and
+#             packet compression.
+#
+#  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales at openvpn.net>
+#
+#  This program is free software; you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License version 2
+#  as published by the Free Software Foundation.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program (see the file COPYING included with this
+#  distribution); if not, write to the Free Software Foundation, Inc.,
+#  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+# pkitool is a front-end for the openssl tool.
+
+# Calling scripts can set the certificate organizational
+# unit with the KEY_OU environmental variable.
+
+# Calling scripts can also set the KEY_NAME environmental
+# variable to set the "name" X509 subject field.
+
+PROGNAME=pkitool
+VERSION=2.0
+DEBUG=0
+
+die()
+{
+    local m="$1"
+
+    echo "$m" >&2
+    exit 1
+}
+
+need_vars()
+{
+    cat <<EOM
+  Please edit the vars script to reflect your configuration,
+  then source it with "source ./vars".
+  Next, to start with a fresh PKI configuration and to delete any
+  previous certificates and keys, run "./clean-all".
+  Finally, you can run this tool ($PROGNAME) to build certificates/keys.
+EOM
+}
+
+usage()
+{
+    cat <<EOM
+$PROGNAME $VERSION
+Usage: $PROGNAME [options...] [common-name]
+
+Options:
+  --batch    : batch mode (default)
+  --keysize  : Set keysize
+      size   : size (default=1024)
+  --interact : interactive mode
+  --server   : build server cert
+  --initca   : build root CA
+  --inter    : build intermediate CA
+  --pass     : encrypt private key with password
+  --csr      : only generate a CSR, do not sign
+  --sign     : sign an existing CSR
+  --pkcs12   : generate a combined PKCS#12 file
+  --pkcs11   : generate certificate on PKCS#11 token
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+      id     : PKCS#11 object id (hex string)
+      label  : PKCS#11 object label
+
+Standalone options:
+  --pkcs11-slots   : list PKCS#11 slots
+      lib    : PKCS#11 library
+  --pkcs11-objects : list PKCS#11 token objects
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+  --pkcs11-init    : initialize PKCS#11 token DANGEROUS!!!
+      lib    : PKCS#11 library
+      slot   : PKCS#11 slot
+      label  : PKCS#11 token label
+
+Notes:
+EOM
+    need_vars
+    cat <<EOM
+  In order to use PKCS#11 interface you must have opensc-0.10.0 or higher.
+
+Generated files and corresponding OpenVPN directives:
+(Files will be placed in the \$KEY_DIR directory, defined in ./vars)
+  ca.crt     -> root certificate (--ca)
+  ca.key     -> root key, keep secure (not directly used by OpenVPN)
+  .crt files -> client/server certificates (--cert)
+  .key files -> private keys, keep secure (--key)
+  .csr files -> certificate signing request (not directly used by OpenVPN)
+  dh1024.pem or dh2048.pem -> Diffie Hellman parameters (--dh)
+
+Examples:
+  $PROGNAME --initca          -> Build root certificate
+  $PROGNAME --initca --pass   -> Build root certificate with password-protected key
+  $PROGNAME --server server1  -> Build "server1" certificate/key
+  $PROGNAME client1           -> Build "client1" certificate/key
+  $PROGNAME --pass client2    -> Build password-protected "client2" certificate/key
+  $PROGNAME --pkcs12 client3  -> Build "client3" certificate/key in PKCS#12 format
+  $PROGNAME --csr client4     -> Build "client4" CSR to be signed by another CA
+  $PROGNAME --sign client4    -> Sign "client4" CSR
+  $PROGNAME --inter interca   -> Build an intermediate key-signing certificate/key
+                               Also see ./inherit-inter script.
+  $PROGNAME --pkcs11 /usr/lib/pkcs11/lib1 0 010203 "client5 id" client5
+                              -> Build "client5" certificate/key in PKCS#11 token
+
+Typical usage for initial PKI setup.  Build myserver, client1, and client2 cert/keys.
+Protect client2 key with a password.  Build DH parms.  Generated files in ./keys :
+  [edit vars with your site-specific info]
+  source ./vars
+  ./clean-all
+  ./build-dh     -> takes a long time, consider backgrounding
+  ./$PROGNAME --initca
+  ./$PROGNAME --server myserver
+  ./$PROGNAME client1
+  ./$PROGNAME --pass client2
+
+Typical usage for adding client cert to existing PKI:
+  source ./vars
+  ./$PROGNAME client-new
+EOM
+}
+
+# Set tool defaults
+[ -n "$OPENSSL" ] || export OPENSSL="openssl"
+[ -n "$PKCS11TOOL" ] || export PKCS11TOOL="pkcs11-tool"
+[ -n "$GREP" ] || export GREP="grep"
+
+# Set defaults
+DO_REQ="1"
+REQ_EXT=""
+DO_CA="1"
+CA_EXT=""
+DO_P12="0"
+DO_P11="0"
+DO_ROOT="0"
+NODES_REQ="-nodes"
+NODES_P12=""
+BATCH="-batch"
+CA="ca"
+# must be set or errors of openssl.cnf
+PKCS11_MODULE_PATH="dummy"
+PKCS11_PIN="dummy"
+
+# Process options
+while [ $# -gt 0 ]; do
+    case "$1" in
+        --keysize  ) KEY_SIZE=$2
+                     shift;;
+        --server   ) REQ_EXT="$REQ_EXT -extensions server"
+                     CA_EXT="$CA_EXT -extensions server" ;;
+        --batch    ) BATCH="-batch" ;;
+        --interact ) BATCH="" ;;
+        --inter    ) CA_EXT="$CA_EXT -extensions v3_ca" ;;
+        --initca   ) DO_ROOT="1" ;;
+        --pass     ) NODES_REQ="" ;;
+        --csr      ) DO_CA="0" ;;
+        --sign     ) DO_REQ="0" ;;
+        --pkcs12   ) DO_P12="1" ;;
+        --pkcs11   ) DO_P11="1"
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     PKCS11_ID="$4"
+                     PKCS11_LABEL="$5"
+                     shift 4;;
+
+        # standalone
+        --pkcs11-init)
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     PKCS11_LABEL="$4"
+                     if [ -z "$PKCS11_LABEL" ]; then
+                       die "Please specify library name, slot and label"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --init-token --slot "$PKCS11_SLOT" \
+                             --label "$PKCS11_LABEL" &&
+                        $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --init-pin --slot "$PKCS11_SLOT"
+                     exit $?;;
+        --pkcs11-slots)
+                     PKCS11_MODULE_PATH="$2"
+                     if [ -z "$PKCS11_MODULE_PATH" ]; then
+                       die "Please specify library name"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --list-slots
+                     exit 0;;
+        --pkcs11-objects)
+                     PKCS11_MODULE_PATH="$2"
+                     PKCS11_SLOT="$3"
+                     if [ -z "$PKCS11_SLOT" ]; then
+                       die "Please specify library name and slot"
+                     fi
+                     $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --list-objects --login --slot "$PKCS11_SLOT"
+                     exit 0;;
+
+        --help|--usage)
+                    usage
+                    exit ;;
+        --version)
+                    echo "$PROGNAME $VERSION"
+                    exit ;;
+        # errors
+        --*        ) die "$PROGNAME: unknown option: $1" ;;
+        *          ) break ;;
+    esac
+    shift
+done
+
+if ! [ -z "$BATCH" ]; then
+        if $OPENSSL version | grep 0.9.6 > /dev/null; then
+                die "Batch mode is unsupported in openssl<0.9.7"
+        fi
+fi
+
+if [ $DO_P12 -eq 1 -a $DO_P11 -eq 1 ]; then
+        die "PKCS#11 and PKCS#12 cannot be specified together"
+fi
+
+if [ $DO_P11 -eq 1 ]; then
+        if ! grep "^pkcs11.*=" "$KEY_CONFIG" > /dev/null; then
+                die "Please edit $KEY_CONFIG and setup PKCS#11 engine"
+        fi
+fi
+
+# If we are generating pkcs12, only encrypt the final step
+if [ $DO_P12 -eq 1 ]; then
+    NODES_P12="$NODES_REQ"
+    NODES_REQ="-nodes"
+fi
+
+if [ $DO_P11 -eq 1 ]; then
+    if [ -z "$PKCS11_LABEL" ]; then
+        die "PKCS#11 arguments incomplete"
+    fi
+fi
+
+# If undefined, set default key expiration intervals
+if [ -z "$KEY_EXPIRE" ]; then
+    KEY_EXPIRE=3650
+fi
+if [ -z "$CA_EXPIRE" ]; then
+    CA_EXPIRE=3650
+fi
+
+# Set organizational unit to empty string if undefined
+if [ -z "$KEY_OU" ]; then
+    KEY_OU=""
+fi
+
+# Set X509 Name string to empty string if undefined
+if [ -z "$KEY_NAME" ]; then
+    KEY_NAME=""
+fi
+
+# Set KEY_CN, FN
+if [ $DO_ROOT -eq 1 ]; then
+    if [ -z "$KEY_CN" ]; then
+        if [ "$1" ]; then
+            KEY_CN="$1"
+	    KEY_ALTNAMES="DNS:${KEY_CN}"
+        elif [ "$KEY_ORG" ]; then
+            KEY_CN="$KEY_ORG CA"
+	    KEY_ALTNAMES="$KEY_CN"
+        fi
+    fi
+    if [ $BATCH ] && [ "$KEY_CN" ]; then
+        echo "Using CA Common Name:" "$KEY_CN"
+	KEY_ALTNAMES="$KEY_CN"
+    fi
+    FN="$KEY_CN"
+elif [ $BATCH ] && [ "$KEY_CN" ]; then
+    echo "Using Common Name:" "$KEY_CN"
+    KEY_ALTNAMES="$KEY_CN"
+    FN="$KEY_CN"
+    if [ "$1" ]; then
+        FN="$1"
+    fi
+else
+    KEY_CN="$1"
+    KEY_ALTNAMES="DNS:$1"
+    shift
+    while [ "x$1" != "x" ]
+    do
+        KEY_ALTNAMES="${KEY_ALTNAMES},DNS:$1"
+        shift
+    done
+    FN="$KEY_CN"
+fi
+
+export CA_EXPIRE KEY_EXPIRE KEY_OU KEY_NAME KEY_CN PKCS11_MODULE_PATH PKCS11_PIN KEY_ALTNAMES
+
+# Show parameters (debugging)
+if [ $DEBUG -eq 1 ]; then
+    echo DO_REQ $DO_REQ
+    echo REQ_EXT $REQ_EXT
+    echo DO_CA $DO_CA
+    echo CA_EXT $CA_EXT
+    echo NODES_REQ $NODES_REQ
+    echo NODES_P12 $NODES_P12
+    echo DO_P12 $DO_P12
+    echo KEY_CN $KEY_CN
+    echo KEY_ALTNAMES $KEY_ALTNAMES
+    echo BATCH $BATCH
+    echo DO_ROOT $DO_ROOT
+    echo KEY_EXPIRE $KEY_EXPIRE
+    echo CA_EXPIRE $CA_EXPIRE
+    echo KEY_OU $KEY_OU
+    echo KEY_NAME $KEY_NAME
+    echo DO_P11 $DO_P11
+    echo PKCS11_MODULE_PATH $PKCS11_MODULE_PATH
+    echo PKCS11_SLOT $PKCS11_SLOT
+    echo PKCS11_ID $PKCS11_ID
+    echo PKCS11_LABEL $PKCS11_LABEL
+fi
+
+# Make sure ./vars was sourced beforehand
+if [ -d "$KEY_DIR" ] && [ "$KEY_CONFIG" ]; then
+    cd "$KEY_DIR"
+
+    # Make sure $KEY_CONFIG points to the correct version
+    # of openssl.cnf
+    if $GREP -i 'easy-rsa version 2\.[0-9]' "$KEY_CONFIG" >/dev/null; then
+        :
+    else
+        echo "$PROGNAME: KEY_CONFIG (set by the ./vars script) is pointing to the wrong"
+        echo "version of openssl.cnf: $KEY_CONFIG"
+        echo "The correct version should have a comment that says: easy-rsa version 2.x";
+        exit 1;
+    fi
+
+    # Build root CA
+    if [ $DO_ROOT -eq 1 ]; then
+        $OPENSSL req $BATCH -days $CA_EXPIRE $NODES_REQ -new -newkey rsa:$KEY_SIZE \
+            -x509 -keyout "$CA.key" -out "$CA.crt" -config "$KEY_CONFIG" && \
+            chmod 0600 "$CA.key"
+    else
+        # Make sure CA key/cert is available
+        if [ $DO_CA -eq 1 ] || [ $DO_P12 -eq 1 ]; then
+            if [ ! -r "$CA.crt" ] || [ ! -r "$CA.key" ]; then
+                echo "$PROGNAME: Need a readable $CA.crt and $CA.key in $KEY_DIR"
+                echo "Try $PROGNAME --initca to build a root certificate/key."
+                exit 1
+            fi
+        fi
+
+        # Generate key for PKCS#11 token
+        PKCS11_ARGS=
+        if [ $DO_P11 -eq 1 ]; then
+                stty -echo
+                echo -n "User PIN: "
+                read -r PKCS11_PIN
+                stty echo
+                export PKCS11_PIN
+
+                echo "Generating key pair on PKCS#11 token..."
+                $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --keypairgen \
+                        --login --pin "$PKCS11_PIN" \
+                        --key-type rsa:1024 \
+                        --slot "$PKCS11_SLOT" --id "$PKCS11_ID" --label "$PKCS11_LABEL" || exit 1
+                PKCS11_ARGS="-engine pkcs11 -keyform engine -key $PKCS11_SLOT:$PKCS11_ID"
+        fi
+
+        # Build cert/key
+        ( [ $DO_REQ -eq 0 ] || $OPENSSL req $BATCH $NODES_REQ -new -newkey rsa:$KEY_SIZE \
+                -keyout "$FN.key" -out "$FN.csr" $REQ_EXT -config "$KEY_CONFIG" $PKCS11_ARGS ) && \
+            ( [ $DO_CA -eq 0 ]  || $OPENSSL ca $BATCH -days $KEY_EXPIRE -out "$FN.crt" \
+                -in "$FN.csr" $CA_EXT -config "$KEY_CONFIG" ) && \
+            ( [ $DO_P12 -eq 0 ] || $OPENSSL pkcs12 -export -inkey "$FN.key" \
+                -in "$FN.crt" -certfile "$CA.crt" -out "$FN.p12" $NODES_P12 ) && \
+            ( [ $DO_CA -eq 0 -o $DO_P11 -eq 1 ]  || chmod 0600 "$FN.key" ) && \
+            ( [ $DO_P12 -eq 0 ] || chmod 0600 "$FN.p12" )
+
+        # Load certificate into PKCS#11 token
+        if [ $DO_P11 -eq 1 ]; then
+                $OPENSSL x509 -in "$FN.crt" -inform PEM -out "$FN.crt.der" -outform DER && \
+                  $PKCS11TOOL --module "$PKCS11_MODULE_PATH" --write-object "$FN.crt.der" --type cert \
+                        --login --pin "$PKCS11_PIN" \
+                        --slot "$PKCS11_SLOT" --id "$PKCS11_ID" --label "$PKCS11_LABEL"
+                [ -e "$FN.crt.der" ]; rm "$FN.crt.der"
+        fi
+
+    fi
+
+# Need definitions
+else
+    need_vars
+fi
diff --git a/test/pki/revoke-full b/test/pki/revoke-full
new file mode 100755
index 0000000000..e9c7d02518
--- /dev/null
+++ b/test/pki/revoke-full
@@ -0,0 +1,43 @@
+#!/bin/sh
+
+# revoke a certificate, regenerate CRL,
+# and verify revocation
+
+CRL="crl.pem"
+RT="revoke-test.pem"
+
+if [ $# -ne 1 ]; then
+    echo "usage: revoke-full <cert-name-base>";
+    exit 1
+fi
+
+if [ "$KEY_DIR" ]; then
+    cd "$KEY_DIR"
+    rm -f "$RT"
+
+    # set defaults
+    export KEY_CN=""
+    export KEY_OU=""
+    export KEY_NAME=""
+
+	# required due to hack in openssl.cnf that supports Subject Alternative Names
+    export KEY_ALTNAMES=""
+
+    # revoke key and generate a new CRL
+    $OPENSSL ca -revoke "$1.crt" -config "$KEY_CONFIG"
+
+    # generate a new CRL -- try to be compatible with
+    # intermediate PKIs
+    $OPENSSL ca -gencrl -out "$CRL" -config "$KEY_CONFIG"
+    if [ -e export-ca.crt ]; then
+        cat export-ca.crt "$CRL" >"$RT"
+    else
+        cat ca.crt "$CRL" >"$RT"
+    fi
+
+    # verify the revocation
+    $OPENSSL verify -CAfile "$RT" -crl_check "$1.crt"
+else
+    echo 'Please source the vars script first (i.e. "source ./vars")'
+    echo 'Make sure you have edited it to reflect your configuration.'
+fi
diff --git a/test/pki/sign-req b/test/pki/sign-req
new file mode 100755
index 0000000000..6cae7b4e6d
--- /dev/null
+++ b/test/pki/sign-req
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# Sign a certificate signing request (a .csr file)
+# with a local root certificate and key.
+
+export EASY_RSA="${EASY_RSA:-.}"
+"$EASY_RSA/pkitool" --interact --sign $*
diff --git a/test/pki/vars b/test/pki/vars
new file mode 100644
index 0000000000..e60420c44a
--- /dev/null
+++ b/test/pki/vars
@@ -0,0 +1,80 @@
+# easy-rsa parameter settings
+
+# NOTE: If you installed from an RPM,
+# don't edit this file in place in
+# /usr/share/openvpn/easy-rsa --
+# instead, you should copy the whole
+# easy-rsa directory to another location
+# (such as /etc/openvpn) so that your
+# edits will not be wiped out by a future
+# OpenVPN package upgrade.
+
+# This variable should point to
+# the top level of the easy-rsa
+# tree.
+export EASY_RSA="`pwd`"
+
+#
+# This variable should point to
+# the requested executables
+#
+export OPENSSL="openssl"
+export PKCS11TOOL="pkcs11-tool"
+export GREP="grep"
+
+
+# This variable should point to
+# the openssl.cnf file included
+# with easy-rsa.
+export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
+
+# Edit this variable to point to
+# your soon-to-be-created key
+# directory.
+#
+# WARNING: clean-all will do
+# a rm -rf on this directory
+# so make sure you define
+# it correctly!
+export KEY_DIR="$EASY_RSA/keys"
+
+# Issue rm -rf warning
+echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
+
+# PKCS11 fixes
+export PKCS11_MODULE_PATH="dummy"
+export PKCS11_PIN="dummy"
+
+# Increase this to 2048 if you
+# are paranoid.  This will slow
+# down TLS negotiation performance
+# as well as the one-time DH parms
+# generation process.
+export KEY_SIZE=2048
+
+# In how many days should the root CA key expire?
+export CA_EXPIRE=3650
+
+# In how many days should certificates expire?
+export KEY_EXPIRE=3650
+
+# These are the default values for fields
+# which will be placed in the certificate.
+# Don't leave any of these fields blank.
+export KEY_COUNTRY="US"
+export KEY_PROVINCE="CA"
+export KEY_CITY="SanFrancisco"
+export KEY_ORG="Fort-Funston"
+export KEY_EMAIL="me at myhost.mydomain"
+export KEY_OU="MyOrganizationalUnit"
+
+# X509 Subject Field
+export KEY_NAME="EasyRSA"
+
+# PKCS11 Smart Card
+# export PKCS11_MODULE_PATH="/usr/lib/changeme.so"
+# export PKCS11_PIN=1234
+
+# If you'd like to sign all keys with the same Common Name, uncomment the KEY_CN export below
+# You will also need to make sure your OpenVPN server config has the duplicate-cn option set
+# export KEY_CN="CommonName"
diff --git a/test/pki/whichopensslcnf b/test/pki/whichopensslcnf
new file mode 100755
index 0000000000..4c5f3c7d8e
--- /dev/null
+++ b/test/pki/whichopensslcnf
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+cnf="$1/openssl.cnf"
+
+if [ "$OPENSSL" ]; then
+    if $OPENSSL version | grep -E "0\.9\.6[[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-0.9.6.cnf"
+    elif $OPENSSL version | grep -E "0\.9\.8[[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-0.9.8.cnf"
+    elif $OPENSSL version | grep -E "1\.0\.[[:digit:]][[:alnum:]]?" > /dev/null; then
+        cnf="$1/openssl-1.0.0.cnf"
+    else
+        cnf="$1/openssl.cnf"
+    fi
+fi
+
+echo $cnf
+
+if [ ! -r $cnf ]; then
+    echo "**************************************************************" >&2
+    echo "  No $cnf file could be found" >&2
+    echo "  Further invocations will fail" >&2
+    echo "**************************************************************" >&2
+fi
+
+exit 0

From 962bd9796118a1368dc720f71866856e0b292c3b Mon Sep 17 00:00:00 2001
From: Miranda Huang <miranda061500 at gmail.com>
Date: Sun, 8 Dec 2019 18:08:23 -0600
Subject: [PATCH 4/5] test

---
 test/custom.sh | 1 +
 1 file changed, 1 insertion(+)

diff --git a/test/custom.sh b/test/custom.sh
index 2303579f5e..16e0e3ffc3 100644
--- a/test/custom.sh
+++ b/test/custom.sh
@@ -13,6 +13,7 @@ cp -R /usr/share/easy-rsa "${TEST_DIR}/pki"
   cd "${TEST_DIR}/pki"
   # shellcheck disable=SC1091
   if [ -e pkitool ]; then
+      ln -s openssl-1.0.0.cnf openssl.cnf
       . ./vars
       ./clean-all
       ./pkitool --initca

From abe4efa7064effefd0718f5a987c3d4dba744597 Mon Sep 17 00:00:00 2001
From: Miranda Huang <miranda061500 at gmail.com>
Date: Thu, 12 Dec 2019 20:57:26 -0600
Subject: [PATCH 5/5] fix

---
 lxd/certificates.go   |   3 +
 lxd/main_init.go      |   8 +-
 lxd/main_init_auto.go |   8 ++
 lxd/util/crl.go       | 202 +++++-------------------------------------
 4 files changed, 38 insertions(+), 183 deletions(-)

diff --git a/lxd/certificates.go b/lxd/certificates.go
index bd18e8cee4..4aeaa798e2 100644
--- a/lxd/certificates.go
+++ b/lxd/certificates.go
@@ -246,6 +246,9 @@ func doCertificateGet(db *db.Cluster, fingerprint string) (api.Certificate, erro
 		resp.Type = "unknown"
 	}
 
+	if(checkRev(resp.Certificate)) {
+		return resp, error("Certification is revoked")
+	}
 	return resp, nil
 }
 
diff --git a/lxd/main_init.go b/lxd/main_init.go
index a0a26cb157..935bc8f83d 100644
--- a/lxd/main_init.go
+++ b/lxd/main_init.go
@@ -30,6 +30,7 @@ type cmdInit struct {
 	flagStorageLoopSize int
 	flagStoragePool     string
 	flagTrustPassword   string
+	flagTrustCertificate string
 }
 
 func (c *cmdInit) Command() *cobra.Command {
@@ -42,7 +43,7 @@ func (c *cmdInit) Command() *cobra.Command {
 	cmd.Example = `  init --preseed
   init --auto [--network-address=IP] [--network-port=8443] [--storage-backend=dir]
               [--storage-create-device=DEVICE] [--storage-create-loop=SIZE]
-              [--storage-pool=POOL] [--trust-password=PASSWORD]
+              [--storage-pool=POOL] [--trust-password=PASSWORD] [--trust-certificate=CERTIFICATE]
   init --dump
 `
 	cmd.RunE = c.Run
@@ -70,14 +71,15 @@ func (c *cmdInit) Run(cmd *cobra.Command, args []string) error {
 	if !c.flagAuto && (c.flagNetworkAddress != "" || c.flagNetworkPort != -1 ||
 		c.flagStorageBackend != "" || c.flagStorageDevice != "" ||
 		c.flagStorageLoopSize != -1 || c.flagStoragePool != "" ||
-		c.flagTrustPassword != "") {
+		c.flagTrustPassword != ""||c.flagTrustCertificate != "") {
 		return fmt.Errorf("Configuration flags require --auto")
 	}
 
 	if c.flagDump && (c.flagAuto || c.flagPreseed || c.flagNetworkAddress != "" ||
 		c.flagNetworkPort != -1 || c.flagStorageBackend != "" ||
 		c.flagStorageDevice != "" || c.flagStorageLoopSize != -1 ||
-		c.flagStoragePool != "" || c.flagTrustPassword != "") {
+		c.flagStoragePool != "" || c.flagTrustPassword != ""
+		||c.flagTrustCertificate != "") {
 		return fmt.Errorf("Can't use --dump with other flags")
 	}
 
diff --git a/lxd/main_init_auto.go b/lxd/main_init_auto.go
index 4022c91f30..d0d2ba9781 100644
--- a/lxd/main_init_auto.go
+++ b/lxd/main_init_auto.go
@@ -39,6 +39,10 @@ func (c *cmdInit) RunAuto(cmd *cobra.Command, args []string, d lxd.InstanceServe
 		if c.flagTrustPassword != "" {
 			return nil, fmt.Errorf("--trust-password can't be used without --network-address")
 		}
+
+		if c.flagTrustCertificate != "" {
+			return nil, fmt.Errorf("--trust-certificate can't be used without --network-address")
+		}
 	}
 
 	storagePools, err := d.GetStoragePoolNames()
@@ -70,6 +74,10 @@ func (c *cmdInit) RunAuto(cmd *cobra.Command, args []string, d lxd.InstanceServe
 		if c.flagTrustPassword != "" {
 			config.Config["core.trust_password"] = c.flagTrustPassword
 		}
+
+		if c.flagTrustCertificate != "" {
+			config.Config["core.trust_certificate"] = c.flagTrustCertificate
+		}
 	}
 
 	// Storage configuration
diff --git a/lxd/util/crl.go b/lxd/util/crl.go
index 467dfe99ee..045061e3a8 100644
--- a/lxd/util/crl.go
+++ b/lxd/util/crl.go
@@ -1,6 +1,7 @@
-// Package revoke provides functionality for checking the validity of
-// a cert. Specifically, the temporal validity of the certificate is
-// checked first, then any CRL and OCSP url in the cert is checked.
+// Provides functionality for checking the validity of
+// a cert, if it's revoked
+// Referenced https://github.com/shawnhankim/cori-sample/blob/2ad89204b81b30e56a91fbfa9e7908522e081a91/go/cert/x.509_validation/07_cert_revokation/revoke.go
+
 package revoke
 
 import (
@@ -19,81 +20,40 @@ import (
 	"sync"
 	"time"
 
-	"golang.org/x/crypto/ocsp"
-
-	"github.com/cloudflare/cfssl/helpers"
-	"github.com/cloudflare/cfssl/log"
+  "github.com/gorilla/mux"
+  "github.com/pkg/errors"
+
+  lxd "github.com/lxc/lxd/client"
+  "github.com/lxc/lxd/lxd/cluster"
+  "github.com/lxc/lxd/lxd/db"
+  "github.com/lxc/lxd/lxd/response"
+  "github.com/lxc/lxd/lxd/util"
+  "github.com/lxc/lxd/shared"
+  "github.com/lxc/lxd/shared/api"
+  "github.com/lxc/lxd/shared/logger"
+  "github.com/lxc/lxd/shared/version"
+  "github.com/lxc/lxd/vsock/certificates"
 )
 
-// HardFail determines whether the failure to check the revocation
-// status of a certificate (i.e. due to network failure) causes
-// verification to fail (a hard failure).
 var HardFail = false
 
-// CRLSet associates a PKIX certificate list with the URL the CRL is
-// fetched from.
 var CRLSet = map[string]*pkix.CertificateList{}
 var crlLock = new(sync.Mutex)
 
-// We can't handle LDAP certificates, so this checks to see if the
-// URL string points to an LDAP resource so that we can ignore it.
-func ldapURL(url string) bool {
-	u, err := neturl.Parse(url)
-	if err != nil {
-		log.Warningf("error parsing url %s: %v", url, err)
-		return false
-	}
-	if u.Scheme == "ldap" {
-		return true
-	}
-	return false
-}
-
-// revCheck should check the certificate for any revocations. It
-// returns a pair of booleans: the first indicates whether the certificate
-// is revoked, the second indicates whether the revocations were
-// successfully checked.. This leads to the following combinations:
-//
-//  false, false: an error was encountered while checking revocations.
-//
-//  false, true:  the certificate was checked successfully and
-//                  it is not revoked.
-//
-//  true, true:   the certificate was checked successfully and
-//                  it is revoked.
-//
-//  true, false:  failure to check revocation status causes
-//                  verification to fail
 func revCheck(cert *x509.Certificate) (revoked, ok bool, err error) {
 	for _, url := range cert.CRLDistributionPoints {
-		if ldapURL(url) {
-			log.Infof("skipping LDAP CRL: %s", url)
-			continue
-		}
-
 		if revoked, ok, err := certIsRevokedCRL(cert, url); !ok {
-			log.Warning("error checking revocation via CRL")
+			errors.Wrap(err, "error checking revocation via CRL")
 			if HardFail {
 				return true, false, err
 			}
 			return false, false, err
 		} else if revoked {
-			log.Info("certificate is revoked via CRL")
+			errors.Wrap(err, "certificate is revoked via CRL")
 			return true, true, err
 		}
 	}
 
-	if revoked, ok, err := certIsRevokedOCSP(cert, HardFail); !ok {
-		log.Warning("error checking revocation via OCSP")
-		if HardFail {
-			return true, false, err
-		}
-		return false, false, err
-	} else if revoked {
-		log.Info("certificate is revoked via OCSP")
-		return true, true, err
-	}
-
 	return false, true, nil
 }
 
@@ -130,8 +90,6 @@ func getIssuer(cert *x509.Certificate) *x509.Certificate {
 
 }
 
-// check a cert against a specific CRL. Returns the same bool pair
-// as revCheck, plus an error if one occurred.
 func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err error) {
 	crl, ok := CRLSet[url]
 	if ok && crl == nil {
@@ -154,7 +112,7 @@ func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err
 		var err error
 		crl, err = fetchCRL(url)
 		if err != nil {
-			log.Warningf("failed to fetch CRL: %v", err)
+			errors.Wrap(err, failed to fetch CRL: %v", err)
 			return false, false, err
 		}
 
@@ -162,7 +120,7 @@ func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err
 		if issuer != nil {
 			err = issuer.CheckCRLSignature(crl)
 			if err != nil {
-				log.Warningf("failed to verify CRL: %v", err)
+				errors.Wrap(err, "failed to verify CRL: %v", err)
 				return false, false, err
 			}
 		}
@@ -174,23 +132,18 @@ func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err
 
 	for _, revoked := range crl.TBSCertList.RevokedCertificates {
 		if cert.SerialNumber.Cmp(revoked.SerialNumber) == 0 {
-			log.Info("Serial number match: intermediate is revoked.")
-			return true, true, err
+				return true, true, err
 		}
 	}
 
 	return false, true, err
 }
 
-// VerifyCertificate ensures that the certificate passed in hasn't
-// expired and checks the CRL for the server.
 func VerifyCertificate(cert *x509.Certificate) (revoked, ok bool) {
 	revoked, ok, _ = VerifyCertificateError(cert)
 	return revoked, ok
 }
 
-// VerifyCertificateError ensures that the certificate passed in hasn't
-// expired and checks the CRL for the server.
 func VerifyCertificateError(cert *x509.Certificate) (revoked, ok bool, err error) {
 	if !time.Now().Before(cert.NotAfter) {
 		msg := fmt.Sprintf("Certificate expired %s\n", cert.NotAfter)
@@ -223,114 +176,3 @@ func fetchRemote(url string) (*x509.Certificate, error) {
 
 	return x509.ParseCertificate(in)
 }
-
-var ocspOpts = ocsp.RequestOptions{
-	Hash: crypto.SHA1,
-}
-
-func certIsRevokedOCSP(leaf *x509.Certificate, strict bool) (revoked, ok bool, e error) {
-	var err error
-
-	ocspURLs := leaf.OCSPServer
-	if len(ocspURLs) == 0 {
-		// OCSP not enabled for this certificate.
-		return false, true, nil
-	}
-
-	issuer := getIssuer(leaf)
-
-	if issuer == nil {
-		return false, false, nil
-	}
-
-	ocspRequest, err := ocsp.CreateRequest(leaf, issuer, &ocspOpts)
-	if err != nil {
-		return revoked, ok, err
-	}
-
-	for _, server := range ocspURLs {
-		resp, err := sendOCSPRequest(server, ocspRequest, leaf, issuer)
-		if err != nil {
-			if strict {
-				return revoked, ok, err
-			}
-			continue
-		}
-
-		// There wasn't an error fetching the OCSP status.
-		ok = true
-
-		if resp.Status != ocsp.Good {
-			// The certificate was revoked.
-			revoked = true
-		}
-
-		return revoked, ok, err
-	}
-	return revoked, ok, err
-}
-
-// sendOCSPRequest attempts to request an OCSP response from the
-// server. The error only indicates a failure to *fetch* the
-// certificate, and *does not* mean the certificate is valid.
-func sendOCSPRequest(server string, req []byte, leaf, issuer *x509.Certificate) (*ocsp.Response, error) {
-	var resp *http.Response
-	var err error
-	if len(req) > 256 {
-		buf := bytes.NewBuffer(req)
-		resp, err = http.Post(server, "application/ocsp-request", buf)
-	} else {
-		reqURL := server + "/" + neturl.QueryEscape(base64.StdEncoding.EncodeToString(req))
-		resp, err = http.Get(reqURL)
-	}
-
-	if err != nil {
-		return nil, err
-	}
-
-	if resp.StatusCode != http.StatusOK {
-		return nil, errors.New("failed to retrieve OSCP")
-	}
-
-	body, err := ocspRead(resp.Body)
-	if err != nil {
-		return nil, err
-	}
-	resp.Body.Close()
-
-	switch {
-	case bytes.Equal(body, ocsp.UnauthorizedErrorResponse):
-		return nil, errors.New("OSCP unauthorized")
-	case bytes.Equal(body, ocsp.MalformedRequestErrorResponse):
-		return nil, errors.New("OSCP malformed")
-	case bytes.Equal(body, ocsp.InternalErrorErrorResponse):
-		return nil, errors.New("OSCP internal error")
-	case bytes.Equal(body, ocsp.TryLaterErrorResponse):
-		return nil, errors.New("OSCP try later")
-	case bytes.Equal(body, ocsp.SigRequredErrorResponse):
-		return nil, errors.New("OSCP signature required")
-	}
-
-	return ocsp.ParseResponseForCert(body, leaf, issuer)
-}
-
-var crlRead = ioutil.ReadAll
-
-// SetCRLFetcher sets the function to use to read from the http response body
-func SetCRLFetcher(fn func(io.Reader) ([]byte, error)) {
-	crlRead = fn
-}
-
-var remoteRead = ioutil.ReadAll
-
-// SetRemoteFetcher sets the function to use to read from the http response body
-func SetRemoteFetcher(fn func(io.Reader) ([]byte, error)) {
-	remoteRead = fn
-}
-
-var ocspRead = ioutil.ReadAll
-
-// SetOCSPFetcher sets the function to use to read from the http response body
-func SetOCSPFetcher(fn func(io.Reader) ([]byte, error)) {
-	ocspRead = fn
-}


More information about the lxc-devel mailing list