From 5ffbddedaedc3215da219d35dc3f95b1c52ef393 Mon Sep 17 00:00:00 2001
From: jiangfangjie 00559066 <jiangfangjie@huawei.com>
Date: Tue, 11 May 2021 14:15:09 +0800
Subject: [PATCH 6/7] tpm2: Pass SEED_COMPAT_LEVEL to CryptAdjustPrimeCandidate
 function

Pass the SEED_COMPAT_LEVEL, originating from the seed that's being used,
to the CryptAdjustPrimeCandidate function and use it to determine
whether the old code should be used or the new one.
---
 src/tpm2/crypto/CryptPrime_fp.h      |  3 ++-
 src/tpm2/crypto/openssl/CryptPrime.c | 26 ++++++++++++++++++++------
 2 files changed, 22 insertions(+), 7 deletions(-)

diff --git a/src/tpm2/crypto/CryptPrime_fp.h b/src/tpm2/crypto/CryptPrime_fp.h
index 8cd23f5..e8ac8b8 100644
--- a/src/tpm2/crypto/CryptPrime_fp.h
+++ b/src/tpm2/crypto/CryptPrime_fp.h
@@ -89,7 +89,8 @@ RsaCheckPrime(
 	      );
 LIB_EXPORT void
 RsaAdjustPrimeCandidate(
-			bigNum          prime
+			bigNum          prime,
+			SEED_COMPAT_LEVEL seedCompatLevel  // IN: compatibility level; libtpms added
 			);
 void
 BnGeneratePrimeForRSA(
diff --git a/src/tpm2/crypto/openssl/CryptPrime.c b/src/tpm2/crypto/openssl/CryptPrime.c
index 9a5ee7d..2e8601c 100644
--- a/src/tpm2/crypto/openssl/CryptPrime.c
+++ b/src/tpm2/crypto/openssl/CryptPrime.c
@@ -361,13 +361,21 @@ RsaAdjustPrimeCandidate_New(
 }
 LIB_EXPORT void
 RsaAdjustPrimeCandidate(
-			bigNum          prime
+			bigNum          prime,
+			SEED_COMPAT_LEVEL seedCompatLevel  // IN: compatibility level; libtpms added
 			)
 {
-    if (1)
+    switch (seedCompatLevel) {
+    case SEED_COMPAT_LEVEL_ORIGINAL:
         RsaAdjustPrimeCandidate_PreRev155(prime);
-    else
+        break;
+    /* case SEED_COMPAT_LEVEL_LAST: */
+    case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX:
         RsaAdjustPrimeCandidate_New(prime);
+        break;
+    default:
+        FAIL(FATAL_ERROR_INTERNAL);
+    }
 }
 /* 10.2.14.1.8 BnGeneratePrimeForRSA() */
 
@@ -395,15 +403,21 @@ BnGeneratePrimeForRSA(
 	    //       DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));// old
 	    //       if(g_inFailureMode)                                                // old
 	// libtpms changed begin
-	    if (1) {
+	    switch (DRBG_GetSeedCompatLevel(rand)) {
+	    case SEED_COMPAT_LEVEL_ORIGINAL:
 		DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));
 		if (g_inFailureMode)
 		    return;
-	    } else {
+		break;
+	    /* case SEED_COMPAT_LEVEL_LAST: */
+            case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX:
 		if(!BnGetRandomBits(prime, bits, rand))                              // new
 		    return;
+                break;
+            default:
+                FAIL(FATAL_ERROR_INTERNAL);
 	    }
-	    RsaAdjustPrimeCandidate(prime);
+	    RsaAdjustPrimeCandidate(prime, DRBG_GetSeedCompatLevel(rand));
 	// libtpms changed end
 	    found = RsaCheckPrime(prime, exponent, rand) == TPM_RC_SUCCESS;
 	}
-- 
2.21.0.windows.1

