From 779c075d93f339ee4043ea026586a463376b301c Mon Sep 17 00:00:00 2001
From: Jonas Karlman <jonas@kwiboo.se>
Date: Wed, 20 Apr 2016 22:26:49 +0200
Subject: [PATCH] trusted first

---
 apps/openssl/apps.c        |  2 ++
 crypto/x509/x509_vfy.c     | 14 ++++++++++++++
 include/openssl/x509_vfy.h |  2 ++
 3 files changed, 18 insertions(+)

diff --git a/apps/openssl/apps.c b/apps/openssl/apps.c
index 6e40965..cbdd080 100644
--- a/apps/openssl/apps.c
+++ b/apps/openssl/apps.c
@@ -1943,6 +1943,8 @@ args_verify(char ***pargs, int *pargc, int *badarg, BIO *err,
 		flags |= X509_V_FLAG_NOTIFY_POLICY;
 	else if (!strcmp(arg, "-check_ss_sig"))
 		flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
+	else if (!strcmp(arg, "-trusted_first"))
+		flags |= X509_V_FLAG_TRUSTED_FIRST;
 	else
 		return 0;
 
diff --git a/crypto/x509/x509_vfy.c b/crypto/x509/x509_vfy.c
index f9fd3a0..6e51edb 100644
--- a/crypto/x509/x509_vfy.c
+++ b/crypto/x509/x509_vfy.c
@@ -209,6 +209,20 @@ X509_verify_cert(X509_STORE_CTX *ctx)
 		if (ctx->check_issued(ctx, x, x))
 			break;
 
+		/* If asked see if we can find issuer in trusted store first */
+		if (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) {
+			ok = ctx->get_issuer(&xtmp, ctx, x);
+			if (ok < 0)
+				goto end;
+			/* If successful for now free up cert so it
+			 * will be picked up again later.
+			 */
+			if (ok > 0) {
+				X509_free(xtmp);
+				break;
+			}
+		}
+
 		/* If we were passed a cert chain, use it first */
 		if (ctx->untrusted != NULL) {
 			xtmp = find_issuer(ctx, sktmp, x);
diff --git a/include/openssl/x509_vfy.h b/include/openssl/x509_vfy.h
index e4050b2..ddf77e7 100644
--- a/include/openssl/x509_vfy.h
+++ b/include/openssl/x509_vfy.h
@@ -383,6 +383,8 @@ void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth);
 #define X509_V_FLAG_USE_DELTAS			0x2000
 /* Check selfsigned CA signature */
 #define X509_V_FLAG_CHECK_SS_SIGNATURE		0x4000
+/* Use trusted store first */
+#define X509_V_FLAG_TRUSTED_FIRST		0x8000
 /* Do not check certificate or CRL validity against current time. */
 #define X509_V_FLAG_NO_CHECK_TIME		0x200000
 
