From 1bf67b900fb4955a0b09f3c1cbe1ce7177adbe2f Mon Sep 17 00:00:00 2001
From: Tobias Brunner <tobias@strongswan.org>
Date: Wed, 29 Mar 2017 11:26:24 +0200
Subject: [PATCH] gmp: Make sure the modulus is odd and the exponent not zero

Unlike mpz_powm() its secure replacement mpz_powm_sec() has the additional
requirement that the exponent must be > 0 and the modulus has to be odd.
Otherwise, it will crash with a floating-point exception.

Fixes: CVE-2017-9022
---
 src/libstrongswan/plugins/gmp/gmp_rsa_public_key.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/libstrongswan/plugins/gmp/gmp_rsa_public_key.c b/src/libstrongswan/plugins/gmp/gmp_rsa_public_key.c
index 2b2c7f249590..32a72ac9600b 100644
--- a/src/libstrongswan/plugins/gmp/gmp_rsa_public_key.c
+++ b/src/libstrongswan/plugins/gmp/gmp_rsa_public_key.c
@@ -475,7 +475,7 @@ gmp_rsa_public_key_t *gmp_rsa_public_key_load(key_type_t type, va_list args)
 		}
 		break;
 	}
-	if (!e.ptr || !n.ptr)
+	if (!e.len || !n.len || (n.ptr[n.len-1] & 0x01) == 0)
 	{
 		return NULL;
 	}
@@ -506,5 +506,10 @@ gmp_rsa_public_key_t *gmp_rsa_public_key_load(key_type_t type, va_list args)
 
 	this->k = (mpz_sizeinbase(this->n, 2) + 7) / BITS_PER_BYTE;
 
+	if (!mpz_sgn(this->e))
+	{
+		destroy(this);
+		return NULL;
+	}
 	return &this->public;
 }
-- 
1.9.1