Merge "Update to OpenSSL 1.0.1g"
diff --git a/Apps-config-host.mk b/Apps-config-host.mk
index e9df3e5..c1e5c6c 100644
--- a/Apps-config-host.mk
+++ b/Apps-config-host.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Apps-config-target.mk b/Apps-config-target.mk
index cedb490..bccd250 100644
--- a/Apps-config-target.mk
+++ b/Apps-config-target.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Crypto-config-host.mk b/Crypto-config-host.mk
index acae32b..3501324 100644
--- a/Crypto-config-host.mk
+++ b/Crypto-config-host.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Crypto-config-target.mk b/Crypto-config-target.mk
index f5a1f18..d7c0765 100644
--- a/Crypto-config-target.mk
+++ b/Crypto-config-target.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Crypto-config-trusty.mk b/Crypto-config-trusty.mk
index 0dc7042..dc5b12c 100644
--- a/Crypto-config-trusty.mk
+++ b/Crypto-config-trusty.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Ssl-config-host.mk b/Ssl-config-host.mk
index d3bffc1..203544d 100644
--- a/Ssl-config-host.mk
+++ b/Ssl-config-host.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/Ssl-config-target.mk b/Ssl-config-target.mk
index 55999dd..2de5a58 100644
--- a/Ssl-config-target.mk
+++ b/Ssl-config-target.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 # This script will append to the following variables:
 #
diff --git a/apps/apps.c b/apps/apps.c
index 1096eee..b76db10 100644
--- a/apps/apps.c
+++ b/apps/apps.c
@@ -586,12 +586,12 @@
 
 		if (ok >= 0)
 			ok = UI_add_input_string(ui,prompt,ui_flags,buf,
-				PW_MIN_LENGTH,BUFSIZ-1);
+				PW_MIN_LENGTH,bufsiz-1);
 		if (ok >= 0 && verify)
 			{
 			buff = (char *)OPENSSL_malloc(bufsiz);
 			ok = UI_add_verify_string(ui,prompt,ui_flags,buff,
-				PW_MIN_LENGTH,BUFSIZ-1, buf);
+				PW_MIN_LENGTH,bufsiz-1, buf);
 			}
 		if (ok >= 0)
 			do
@@ -2841,7 +2841,7 @@
 
 	if (proc==NULL)
 		{
-		if (GetVersion() < 0x80000000)
+		if (check_winnt())
 			proc = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,
 						GetCurrentProcessId());
 		if (proc==NULL) proc = (HANDLE)-1;
diff --git a/apps/crl.c b/apps/crl.c
index c395b2a..8797d30 100644
--- a/apps/crl.c
+++ b/apps/crl.c
@@ -81,6 +81,9 @@
 " -in arg         - input file - default stdin\n",
 " -out arg        - output file - default stdout\n",
 " -hash           - print hash value\n",
+#ifndef OPENSSL_NO_MD5
+" -hash_old       - print old-style (MD5) hash value\n",
+#endif
 " -fingerprint    - print the crl fingerprint\n",
 " -issuer         - print issuer DN\n",
 " -lastupdate     - lastUpdate field\n",
@@ -108,6 +111,9 @@
 	int informat,outformat;
 	char *infile=NULL,*outfile=NULL;
 	int hash=0,issuer=0,lastupdate=0,nextupdate=0,noout=0,text=0;
+#ifndef OPENSSL_NO_MD5
+       int hash_old=0;
+#endif
 	int fingerprint = 0, crlnumber = 0;
 	const char **pp;
 	X509_STORE *store = NULL;
@@ -192,6 +198,10 @@
 			text = 1;
 		else if (strcmp(*argv,"-hash") == 0)
 			hash= ++num;
+#ifndef OPENSSL_NO_MD5
+		else if (strcmp(*argv,"-hash_old") == 0)
+			hash_old= ++num;
+#endif
 		else if (strcmp(*argv,"-nameopt") == 0)
 			{
 			if (--argc < 1) goto bad;
@@ -304,6 +314,14 @@
 				BIO_printf(bio_out,"%08lx\n",
 					X509_NAME_hash(X509_CRL_get_issuer(x)));
 				}
+#ifndef OPENSSL_NO_MD5
+			if (hash_old == i)
+				{
+				BIO_printf(bio_out,"%08lx\n",
+					X509_NAME_hash_old(
+						X509_CRL_get_issuer(x)));
+				}
+#endif
 			if (lastupdate == i)
 				{
 				BIO_printf(bio_out,"lastUpdate=");
diff --git a/apps/dgst.c b/apps/dgst.c
index 81bd870..f4aec77 100644
--- a/apps/dgst.c
+++ b/apps/dgst.c
@@ -427,9 +427,9 @@
 			goto end;
 			}
 		if (do_verify)
-			r = EVP_DigestVerifyInit(mctx, &pctx, md, e, sigkey);
+			r = EVP_DigestVerifyInit(mctx, &pctx, md, NULL, sigkey);
 		else
-			r = EVP_DigestSignInit(mctx, &pctx, md, e, sigkey);
+			r = EVP_DigestSignInit(mctx, &pctx, md, NULL, sigkey);
 		if (!r)
 			{
 			BIO_printf(bio_err, "Error setting context\n");
diff --git a/apps/ecparam.c b/apps/ecparam.c
index 465480b..976ebef 100644
--- a/apps/ecparam.c
+++ b/apps/ecparam.c
@@ -105,7 +105,7 @@
  *                    in the asn1 der encoding
  *                    possible values: named_curve (default)
  *                                     explicit
- * -no_seed         - if 'explicit' parameters are choosen do not use the seed
+ * -no_seed         - if 'explicit' parameters are chosen do not use the seed
  * -genkey          - generate ec key
  * -rand file       - files to use for random number input
  * -engine e        - use engine e, possibly a hardware device
@@ -286,7 +286,7 @@
 		BIO_printf(bio_err, "                                   "
 				" explicit\n");
 		BIO_printf(bio_err, " -no_seed          if 'explicit'"
-				" parameters are choosen do not"
+				" parameters are chosen do not"
 				" use the seed\n");
 		BIO_printf(bio_err, " -genkey           generate ec"
 				" key\n");
diff --git a/apps/req.c b/apps/req.c
index 8552658..5e034a8 100644
--- a/apps/req.c
+++ b/apps/req.c
@@ -644,6 +644,11 @@
 		if (inrand)
 			app_RAND_load_files(inrand);
 
+		if (!NCONF_get_number(req_conf,SECTION,BITS, &newkey))
+			{
+			newkey=DEFAULT_KEY_LENGTH;
+			}
+
 		if (keyalg)
 			{
 			genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
@@ -652,12 +657,6 @@
 				goto end;
 			}
 	
-		if (newkey <= 0)
-			{
-			if (!NCONF_get_number(req_conf,SECTION,BITS, &newkey))
-				newkey=DEFAULT_KEY_LENGTH;
-			}
-
 		if (newkey < MIN_KEY_LENGTH && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA))
 			{
 			BIO_printf(bio_err,"private key length is too short,\n");
@@ -1649,6 +1648,8 @@
 				keylen = atol(p + 1);
 				*pkeylen = keylen;
 				}
+			else
+				keylen = *pkeylen;
 			}
 		else if (p)
 			paramfile = p + 1;
diff --git a/build-config-32.mk b/build-config-32.mk
index 7f5304f..4f7484b 100644
--- a/build-config-32.mk
+++ b/build-config-32.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 openssl_cflags_32 := \
   -DOPENSSL_THREADS \
diff --git a/build-config-64.mk b/build-config-64.mk
index b03ed3f..c0e6f6d 100644
--- a/build-config-64.mk
+++ b/build-config-64.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 openssl_cflags_64 := \
   -DOPENSSL_THREADS \
diff --git a/build-config-trusty.mk b/build-config-trusty.mk
index 287f78a..e5809a3 100644
--- a/build-config-trusty.mk
+++ b/build-config-trusty.mk
@@ -1,6 +1,6 @@
 # Auto-generated - DO NOT EDIT!
 # To regenerate, edit openssl.config, then run:
-#     ./import_openssl.sh import /path/to/openssl-1.0.1f.tar.gz
+#     ./import_openssl.sh import /path/to/openssl-1.0.1g.tar.gz
 #
 openssl_cflags_trusty := \
   -DL_ENDIAN \
diff --git a/crypto/aes/asm/vpaes-x86_64.S b/crypto/aes/asm/vpaes-x86_64.S
index 2b68e61..0162631 100644
--- a/crypto/aes/asm/vpaes-x86_64.S
+++ b/crypto/aes/asm/vpaes-x86_64.S
@@ -823,6 +823,6 @@
 .Lk_dsbo:
 .quad	0x1387EA537EF94000, 0xC7AA6DB9D4943E2D
 .quad	0x12D7560F93441D00, 0xCA4B8159D8C58E9C
-.byte	86,101,99,116,111,114,32,80,101,114,109,117,116,97,105,111,110,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0
+.byte	86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105,111,110,32,65,69,83,32,102,111,114,32,120,56,54,95,54,52,47,83,83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117,114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105,118,101,114,115,105,116,121,41,0
 .align	64
 .size	_vpaes_consts,.-_vpaes_consts
diff --git a/crypto/aes/asm/vpaes-x86_64.pl b/crypto/aes/asm/vpaes-x86_64.pl
index 41f2e46..bd7f45b 100644
--- a/crypto/aes/asm/vpaes-x86_64.pl
+++ b/crypto/aes/asm/vpaes-x86_64.pl
@@ -1060,7 +1060,7 @@
 .Lk_dsbo:	# decryption sbox final output
 	.quad	0x1387EA537EF94000, 0xC7AA6DB9D4943E2D
 	.quad	0x12D7560F93441D00, 0xCA4B8159D8C58E9C
-.asciz	"Vector Permutaion AES for x86_64/SSSE3, Mike Hamburg (Stanford University)"
+.asciz	"Vector Permutation AES for x86_64/SSSE3, Mike Hamburg (Stanford University)"
 .align	64
 .size	_vpaes_consts,.-_vpaes_consts
 ___
diff --git a/crypto/asn1/asn1_err.c b/crypto/asn1/asn1_err.c
index 1a30bf1..aa60203 100644
--- a/crypto/asn1/asn1_err.c
+++ b/crypto/asn1/asn1_err.c
@@ -305,7 +305,7 @@
 {ERR_REASON(ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE),"unknown public key type"},
 {ERR_REASON(ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM),"unknown signature algorithm"},
 {ERR_REASON(ASN1_R_UNKNOWN_TAG)          ,"unknown tag"},
-{ERR_REASON(ASN1_R_UNKOWN_FORMAT)        ,"unkown format"},
+{ERR_REASON(ASN1_R_UNKOWN_FORMAT)        ,"unknown format"},
 {ERR_REASON(ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE),"unsupported any defined by type"},
 {ERR_REASON(ASN1_R_UNSUPPORTED_CIPHER)   ,"unsupported cipher"},
 {ERR_REASON(ASN1_R_UNSUPPORTED_ENCRYPTION_ALGORITHM),"unsupported encryption algorithm"},
diff --git a/crypto/bio/bss_log.c b/crypto/bio/bss_log.c
index b7dce5c..2227b2b 100644
--- a/crypto/bio/bss_log.c
+++ b/crypto/bio/bss_log.c
@@ -245,7 +245,7 @@
 
 static void xopenlog(BIO* bp, char* name, int level)
 {
-	if (GetVersion() < 0x80000000)
+	if (check_winnt())
 		bp->ptr = RegisterEventSourceA(NULL,name);
 	else
 		bp->ptr = NULL;
diff --git a/crypto/bn/bn.h b/crypto/bn/bn.h
index 9281ce5..e776c07 100644
--- a/crypto/bn/bn.h
+++ b/crypto/bn/bn.h
@@ -538,6 +538,8 @@
 BIGNUM *BN_mod_sqrt(BIGNUM *ret,
 	const BIGNUM *a, const BIGNUM *n,BN_CTX *ctx);
 
+void	BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords);
+
 /* Deprecated versions */
 #ifndef OPENSSL_NO_DEPRECATED
 BIGNUM *BN_generate_prime(BIGNUM *ret,int bits,int safe,
@@ -778,11 +780,20 @@
 
 #define bn_fix_top(a)		bn_check_top(a)
 
+#define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2)
+#define bn_wcheck_size(bn, words) \
+	do { \
+		const BIGNUM *_bnum2 = (bn); \
+		assert(words <= (_bnum2)->dmax && words >= (_bnum2)->top); \
+	} while(0)
+
 #else /* !BN_DEBUG */
 
 #define bn_pollute(a)
 #define bn_check_top(a)
 #define bn_fix_top(a)		bn_correct_top(a)
+#define bn_check_size(bn, bits)
+#define bn_wcheck_size(bn, words)
 
 #endif
 
diff --git a/crypto/bn/bn_lib.c b/crypto/bn/bn_lib.c
index 7a5676d..5461e6e 100644
--- a/crypto/bn/bn_lib.c
+++ b/crypto/bn/bn_lib.c
@@ -824,3 +824,55 @@
 		}
 	return bn_cmp_words(a,b,cl);
 	}
+
+/* 
+ * Constant-time conditional swap of a and b.  
+ * a and b are swapped if condition is not 0.  The code assumes that at most one bit of condition is set.
+ * nwords is the number of words to swap.  The code assumes that at least nwords are allocated in both a and b,
+ * and that no more than nwords are used by either a or b.
+ * a and b cannot be the same number
+ */
+void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
+	{
+	BN_ULONG t;
+	int i;
+
+	bn_wcheck_size(a, nwords);
+	bn_wcheck_size(b, nwords);
+
+	assert(a != b);
+	assert((condition & (condition - 1)) == 0);
+	assert(sizeof(BN_ULONG) >= sizeof(int));
+
+	condition = ((condition - 1) >> (BN_BITS2 - 1)) - 1;
+
+	t = (a->top^b->top) & condition;
+	a->top ^= t;
+	b->top ^= t;
+
+#define BN_CONSTTIME_SWAP(ind) \
+	do { \
+		t = (a->d[ind] ^ b->d[ind]) & condition; \
+		a->d[ind] ^= t; \
+		b->d[ind] ^= t; \
+	} while (0)
+
+
+	switch (nwords) {
+	default:
+		for (i = 10; i < nwords; i++) 
+			BN_CONSTTIME_SWAP(i);
+		/* Fallthrough */
+	case 10: BN_CONSTTIME_SWAP(9); /* Fallthrough */
+	case 9: BN_CONSTTIME_SWAP(8); /* Fallthrough */
+	case 8: BN_CONSTTIME_SWAP(7); /* Fallthrough */
+	case 7: BN_CONSTTIME_SWAP(6); /* Fallthrough */
+	case 6: BN_CONSTTIME_SWAP(5); /* Fallthrough */
+	case 5: BN_CONSTTIME_SWAP(4); /* Fallthrough */
+	case 4: BN_CONSTTIME_SWAP(3); /* Fallthrough */
+	case 3: BN_CONSTTIME_SWAP(2); /* Fallthrough */
+	case 2: BN_CONSTTIME_SWAP(1); /* Fallthrough */
+	case 1: BN_CONSTTIME_SWAP(0);
+	}
+#undef BN_CONSTTIME_SWAP
+}
diff --git a/crypto/cms/cms_lib.c b/crypto/cms/cms_lib.c
index b62d1bf..ba08279 100644
--- a/crypto/cms/cms_lib.c
+++ b/crypto/cms/cms_lib.c
@@ -465,8 +465,6 @@
 	pcerts = cms_get0_certificate_choices(cms);
 	if (!pcerts)
 		return 0;
-	if (!pcerts)
-		return 0;
 	for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++)
 		{
 		cch = sk_CMS_CertificateChoices_value(*pcerts, i);
diff --git a/crypto/cryptlib.c b/crypto/cryptlib.c
index 304c6b7..0b77d8b 100644
--- a/crypto/cryptlib.c
+++ b/crypto/cryptlib.c
@@ -889,7 +889,7 @@
 
 #if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
     /* this -------------v--- guards NT-specific calls */
-    if (GetVersion() < 0x80000000 && OPENSSL_isservice() > 0)
+    if (check_winnt() && OPENSSL_isservice() > 0)
     {	HANDLE h = RegisterEventSource(0,_T("OPENSSL"));
 	const TCHAR *pmsg=buf;
 	ReportEvent(h,EVENTLOG_ERROR_TYPE,0,0,0,1,0,&pmsg,0);
diff --git a/crypto/ec/ec2_mult.c b/crypto/ec/ec2_mult.c
index 26f4a78..1c575dc 100644
--- a/crypto/ec/ec2_mult.c
+++ b/crypto/ec/ec2_mult.c
@@ -208,11 +208,15 @@
 	return ret;
 	}
 
+
 /* Computes scalar*point and stores the result in r.
  * point can not equal r.
- * Uses algorithm 2P of
+ * Uses a modified algorithm 2P of
  *     Lopez, J. and Dahab, R.  "Fast multiplication on elliptic curves over 
  *     GF(2^m) without precomputation" (CHES '99, LNCS 1717).
+ *
+ * To protect against side-channel attack the function uses constant time swap,
+ * avoiding conditional branches.
  */
 static int ec_GF2m_montgomery_point_multiply(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
 	const EC_POINT *point, BN_CTX *ctx)
@@ -246,6 +250,11 @@
 	x2 = &r->X;
 	z2 = &r->Y;
 
+	bn_wexpand(x1, group->field.top);
+	bn_wexpand(z1, group->field.top);
+	bn_wexpand(x2, group->field.top);
+	bn_wexpand(z2, group->field.top);
+
 	if (!BN_GF2m_mod_arr(x1, &point->X, group->poly)) goto err; /* x1 = x */
 	if (!BN_one(z1)) goto err; /* z1 = 1 */
 	if (!group->meth->field_sqr(group, z2, x1, ctx)) goto err; /* z2 = x1^2 = x^2 */
@@ -270,16 +279,12 @@
 		word = scalar->d[i];
 		while (mask)
 			{
-			if (word & mask)
-				{
-				if (!gf2m_Madd(group, &point->X, x1, z1, x2, z2, ctx)) goto err;
-				if (!gf2m_Mdouble(group, x2, z2, ctx)) goto err;
-				}
-			else
-				{
-				if (!gf2m_Madd(group, &point->X, x2, z2, x1, z1, ctx)) goto err;
-				if (!gf2m_Mdouble(group, x1, z1, ctx)) goto err;
-				}
+			BN_consttime_swap(word & mask, x1, x2, group->field.top);
+			BN_consttime_swap(word & mask, z1, z2, group->field.top);
+			if (!gf2m_Madd(group, &point->X, x2, z2, x1, z1, ctx)) goto err;
+			if (!gf2m_Mdouble(group, x1, z1, ctx)) goto err;
+			BN_consttime_swap(word & mask, x1, x2, group->field.top);
+			BN_consttime_swap(word & mask, z1, z2, group->field.top);
 			mask >>= 1;
 			}
 		mask = BN_TBIT;
diff --git a/crypto/engine/eng_list.c b/crypto/engine/eng_list.c
index 27846ed..95c8589 100644
--- a/crypto/engine/eng_list.c
+++ b/crypto/engine/eng_list.c
@@ -408,6 +408,7 @@
 				!ENGINE_ctrl_cmd_string(iterator, "DIR_LOAD", "2", 0) ||
 				!ENGINE_ctrl_cmd_string(iterator, "DIR_ADD",
 					load_dir, 0) ||
+				!ENGINE_ctrl_cmd_string(iterator, "LIST_ADD", "1", 0) ||
 				!ENGINE_ctrl_cmd_string(iterator, "LOAD", NULL, 0))
 				goto notfound;
 		return iterator;
diff --git a/crypto/evp/bio_b64.c b/crypto/evp/bio_b64.c
index 72a2a67..ac6d441 100644
--- a/crypto/evp/bio_b64.c
+++ b/crypto/evp/bio_b64.c
@@ -264,7 +264,7 @@
 				}
 
 			/* we fell off the end without starting */
-			if (j == i)
+			if ((j == i) && (num == 0))
 				{
 				/* Is this is one long chunk?, if so, keep on
 				 * reading until a new line. */
diff --git a/crypto/modes/gcm128.c b/crypto/modes/gcm128.c
index 250063d..e1dc2b0 100644
--- a/crypto/modes/gcm128.c
+++ b/crypto/modes/gcm128.c
@@ -810,7 +810,11 @@
 		GCM_MUL(ctx,Yi);
 
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctr = BSWAP4(ctx->Yi.d[3]);
+#else
 			ctr = GETU32(ctx->Yi.c+12);
+#endif
 		else
 			ctr = ctx->Yi.d[3];
 	}
@@ -818,7 +822,11 @@
 	(*ctx->block)(ctx->Yi.c,ctx->EK0.c,ctx->key);
 	++ctr;
 	if (is_endian.little)
+#ifdef BSWAP4
+		ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 		PUTU32(ctx->Yi.c+12,ctr);
+#endif
 	else
 		ctx->Yi.d[3] = ctr;
 }
@@ -913,7 +921,11 @@
 	}
 
 	if (is_endian.little)
+#ifdef BSWAP4
+		ctr = BSWAP4(ctx->Yi.d[3]);
+#else
 		ctr = GETU32(ctx->Yi.c+12);
+#endif
 	else
 		ctr = ctx->Yi.d[3];
 
@@ -947,7 +959,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i)
@@ -969,7 +985,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i)
@@ -988,7 +1008,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i)
@@ -1004,7 +1028,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			while (len--) {
@@ -1022,7 +1050,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 		}
@@ -1066,7 +1098,11 @@
 	}
 
 	if (is_endian.little)
+#ifdef BSWAP4
+		ctr = BSWAP4(ctx->Yi.d[3]);
+#else
 		ctr = GETU32(ctx->Yi.c+12);
+#endif
 	else
 		ctr = ctx->Yi.d[3];
 
@@ -1103,7 +1139,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i)
@@ -1123,7 +1163,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i)
@@ -1141,7 +1185,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			for (i=0; i<16/sizeof(size_t); ++i) {
@@ -1159,7 +1207,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 			while (len--) {
@@ -1180,7 +1232,11 @@
 			(*block)(ctx->Yi.c,ctx->EKi.c,key);
 			++ctr;
 			if (is_endian.little)
+#ifdef BSWAP4
+				ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 				PUTU32(ctx->Yi.c+12,ctr);
+#endif
 			else
 				ctx->Yi.d[3] = ctr;
 		}
@@ -1225,7 +1281,11 @@
 	}
 
 	if (is_endian.little)
+#ifdef BSWAP4
+		ctr = BSWAP4(ctx->Yi.d[3]);
+#else
 		ctr = GETU32(ctx->Yi.c+12);
+#endif
 	else
 		ctr = ctx->Yi.d[3];
 
@@ -1247,7 +1307,11 @@
 		(*stream)(in,out,GHASH_CHUNK/16,key,ctx->Yi.c);
 		ctr += GHASH_CHUNK/16;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		GHASH(ctx,out,GHASH_CHUNK);
@@ -1262,7 +1326,11 @@
 		(*stream)(in,out,j,key,ctx->Yi.c);
 		ctr += (unsigned int)j;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		in  += i;
@@ -1282,7 +1350,11 @@
 		(*ctx->block)(ctx->Yi.c,ctx->EKi.c,key);
 		++ctr;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		while (len--) {
@@ -1324,7 +1396,11 @@
 	}
 
 	if (is_endian.little)
+#ifdef BSWAP4
+		ctr = BSWAP4(ctx->Yi.d[3]);
+#else
 		ctr = GETU32(ctx->Yi.c+12);
+#endif
 	else
 		ctr = ctx->Yi.d[3];
 
@@ -1349,7 +1425,11 @@
 		(*stream)(in,out,GHASH_CHUNK/16,key,ctx->Yi.c);
 		ctr += GHASH_CHUNK/16;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		out += GHASH_CHUNK;
@@ -1375,7 +1455,11 @@
 		(*stream)(in,out,j,key,ctx->Yi.c);
 		ctr += (unsigned int)j;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		out += i;
@@ -1386,7 +1470,11 @@
 		(*ctx->block)(ctx->Yi.c,ctx->EKi.c,key);
 		++ctr;
 		if (is_endian.little)
+#ifdef BSWAP4
+			ctx->Yi.d[3] = BSWAP4(ctr);
+#else
 			PUTU32(ctx->Yi.c+12,ctr);
+#endif
 		else
 			ctx->Yi.d[3] = ctr;
 		while (len--) {
diff --git a/crypto/opensslv.h b/crypto/opensslv.h
index b27a5bb..ebe7180 100644
--- a/crypto/opensslv.h
+++ b/crypto/opensslv.h
@@ -25,11 +25,11 @@
  * (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for
  *  major minor fix final patch/beta)
  */
-#define OPENSSL_VERSION_NUMBER	0x1000106fL
+#define OPENSSL_VERSION_NUMBER	0x1000107fL
 #ifdef OPENSSL_FIPS
-#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1f-fips 6 Jan 2014"
+#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1g-fips 7 Apr 2014"
 #else
-#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1f 6 Jan 2014"
+#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1g 7 Apr 2014"
 #endif
 #define OPENSSL_VERSION_PTEXT	" part of " OPENSSL_VERSION_TEXT
 
diff --git a/crypto/rand/md_rand.c b/crypto/rand/md_rand.c
index dd29163..aee1c30 100644
--- a/crypto/rand/md_rand.c
+++ b/crypto/rand/md_rand.c
@@ -198,6 +198,9 @@
 	EVP_MD_CTX m;
 	int do_not_lock;
 
+	if (!num)
+		return;
+
 	/*
 	 * (Based on the rand(3) manpage)
 	 *
diff --git a/crypto/rand/rand_win.c b/crypto/rand/rand_win.c
index 5d134e1..34ffcd2 100644
--- a/crypto/rand/rand_win.c
+++ b/crypto/rand/rand_win.c
@@ -750,7 +750,7 @@
   int		y;		/* y-coordinate of screen lines to grab */
   int		n = 16;		/* number of screen lines to grab at a time */
 
-  if (GetVersion() < 0x80000000 && OPENSSL_isservice()>0)
+  if (check_winnt() && OPENSSL_isservice()>0)
     return;
 
   /* Create a screen DC and a memory DC compatible to screen DC */
diff --git a/crypto/symhacks.h b/crypto/symhacks.h
index 07a412f..bd2f000 100644
--- a/crypto/symhacks.h
+++ b/crypto/symhacks.h
@@ -204,6 +204,12 @@
 #define SSL_CTX_set_next_protos_advertised_cb	SSL_CTX_set_next_protos_adv_cb
 #undef SSL_CTX_set_next_proto_select_cb
 #define SSL_CTX_set_next_proto_select_cb	SSL_CTX_set_next_proto_sel_cb
+#undef ssl3_cbc_record_digest_supported
+#define ssl3_cbc_record_digest_supported        ssl3_cbc_record_digest_support
+#undef ssl_check_clienthello_tlsext_late
+#define ssl_check_clienthello_tlsext_late       ssl_check_clihello_tlsext_late
+#undef ssl_check_clienthello_tlsext_early
+#define ssl_check_clienthello_tlsext_early      ssl_check_clihello_tlsext_early
 
 /* Hack some long ENGINE names */
 #undef ENGINE_get_default_BN_mod_exp_crt
diff --git a/crypto/x509/by_dir.c b/crypto/x509/by_dir.c
index 27ca515..c6602da 100644
--- a/crypto/x509/by_dir.c
+++ b/crypto/x509/by_dir.c
@@ -218,7 +218,7 @@
 
 	s=dir;
 	p=s;
-	for (;;p++)
+	do
 		{
 		if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0'))
 			{
@@ -264,9 +264,7 @@
 				return 0;
 				}
 			}
-		if (*p == '\0')
-			break;
-		}
+		} while (*p++ != '\0');
 	return 1;
 	}
 
diff --git a/crypto/x509/x509_vfy.c b/crypto/x509/x509_vfy.c
index 5195ffe..920066a 100644
--- a/crypto/x509/x509_vfy.c
+++ b/crypto/x509/x509_vfy.c
@@ -1462,10 +1462,9 @@
 	 * a certificate was revoked. This has since been changed since 
 	 * critical extension can change the meaning of CRL entries.
 	 */
-	if (crl->flags & EXFLAG_CRITICAL)
+	if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
+		&& (crl->flags & EXFLAG_CRITICAL))
 		{
-		if (ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
-			return 1;
 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
 		ok = ctx->verify_cb(0, ctx);
 		if(!ok)
diff --git a/e_os.h b/e_os.h
index 79c1392..6a0aad1 100644
--- a/e_os.h
+++ b/e_os.h
@@ -368,6 +368,13 @@
 #    define DEFAULT_HOME  "C:"
 #  endif
 
+/* Avoid Windows 8 SDK GetVersion deprecated problems */
+#if defined(_MSC_VER) && _MSC_VER>=1800
+#  define check_winnt() (1)
+#else
+#  define check_winnt() (GetVersion() < 0x80000000)
+#endif 
+
 #else /* The non-microsoft world */
 
 #  ifdef OPENSSL_SYS_VMS
diff --git a/include/openssl/bn.h b/include/openssl/bn.h
index 9281ce5..e776c07 100644
--- a/include/openssl/bn.h
+++ b/include/openssl/bn.h
@@ -538,6 +538,8 @@
 BIGNUM *BN_mod_sqrt(BIGNUM *ret,
 	const BIGNUM *a, const BIGNUM *n,BN_CTX *ctx);
 
+void	BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords);
+
 /* Deprecated versions */
 #ifndef OPENSSL_NO_DEPRECATED
 BIGNUM *BN_generate_prime(BIGNUM *ret,int bits,int safe,
@@ -778,11 +780,20 @@
 
 #define bn_fix_top(a)		bn_check_top(a)
 
+#define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2)
+#define bn_wcheck_size(bn, words) \
+	do { \
+		const BIGNUM *_bnum2 = (bn); \
+		assert(words <= (_bnum2)->dmax && words >= (_bnum2)->top); \
+	} while(0)
+
 #else /* !BN_DEBUG */
 
 #define bn_pollute(a)
 #define bn_check_top(a)
 #define bn_fix_top(a)		bn_correct_top(a)
+#define bn_check_size(bn, bits)
+#define bn_wcheck_size(bn, words)
 
 #endif
 
diff --git a/include/openssl/kssl.h b/include/openssl/kssl.h
index 8242fd5..e4df843 100644
--- a/include/openssl/kssl.h
+++ b/include/openssl/kssl.h
@@ -70,6 +70,15 @@
 #include <stdio.h>
 #include <ctype.h>
 #include <krb5.h>
+#ifdef OPENSSL_SYS_WIN32
+/* These can sometimes get redefined indirectly by krb5 header files
+ * after they get undefed in ossl_typ.h
+ */
+#undef X509_NAME
+#undef X509_EXTENSIONS
+#undef OCSP_REQUEST
+#undef OCSP_RESPONSE
+#endif
 
 #ifdef  __cplusplus
 extern "C" {
diff --git a/include/openssl/opensslv.h b/include/openssl/opensslv.h
index b27a5bb..ebe7180 100644
--- a/include/openssl/opensslv.h
+++ b/include/openssl/opensslv.h
@@ -25,11 +25,11 @@
  * (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for
  *  major minor fix final patch/beta)
  */
-#define OPENSSL_VERSION_NUMBER	0x1000106fL
+#define OPENSSL_VERSION_NUMBER	0x1000107fL
 #ifdef OPENSSL_FIPS
-#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1f-fips 6 Jan 2014"
+#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1g-fips 7 Apr 2014"
 #else
-#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1f 6 Jan 2014"
+#define OPENSSL_VERSION_TEXT	"OpenSSL 1.0.1g 7 Apr 2014"
 #endif
 #define OPENSSL_VERSION_PTEXT	" part of " OPENSSL_VERSION_TEXT
 
diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h
index 4c38f6e..40c4d9c 100644
--- a/include/openssl/ssl.h
+++ b/include/openssl/ssl.h
@@ -928,7 +928,7 @@
 	 */
 	unsigned int max_send_fragment;
 
-#ifndef OPENSSL_ENGINE
+#ifndef OPENSSL_NO_ENGINE
 	/* Engine to pass requests for client certs to
 	 */
 	ENGINE *client_cert_engine;
diff --git a/include/openssl/symhacks.h b/include/openssl/symhacks.h
index 07a412f..bd2f000 100644
--- a/include/openssl/symhacks.h
+++ b/include/openssl/symhacks.h
@@ -204,6 +204,12 @@
 #define SSL_CTX_set_next_protos_advertised_cb	SSL_CTX_set_next_protos_adv_cb
 #undef SSL_CTX_set_next_proto_select_cb
 #define SSL_CTX_set_next_proto_select_cb	SSL_CTX_set_next_proto_sel_cb
+#undef ssl3_cbc_record_digest_supported
+#define ssl3_cbc_record_digest_supported        ssl3_cbc_record_digest_support
+#undef ssl_check_clienthello_tlsext_late
+#define ssl_check_clienthello_tlsext_late       ssl_check_clihello_tlsext_late
+#undef ssl_check_clienthello_tlsext_early
+#define ssl_check_clienthello_tlsext_early      ssl_check_clihello_tlsext_early
 
 /* Hack some long ENGINE names */
 #undef ENGINE_get_default_BN_mod_exp_crt
diff --git a/include/openssl/tls1.h b/include/openssl/tls1.h
index 6f031a4..6283c6a 100644
--- a/include/openssl/tls1.h
+++ b/include/openssl/tls1.h
@@ -230,6 +230,12 @@
 /* ExtensionType value from RFC5620 */
 #define TLSEXT_TYPE_heartbeat	15
 
+/* ExtensionType value for TLS padding extension.
+ * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
+ * http://tools.ietf.org/html/draft-agl-tls-padding-03
+ */
+#define TLSEXT_TYPE_padding	21
+
 /* ExtensionType value from draft-ietf-tls-applayerprotoneg-00 */
 #define TLSEXT_TYPE_application_layer_protocol_negotiation 16
 
@@ -254,10 +260,6 @@
 /* This is not an IANA defined extension number */
 #define TLSEXT_TYPE_channel_id			30031
 
-/* See https://tools.ietf.org/html/draft-agl-tls-padding-02
- * Number not yet IANA assigned. */
-#define TLSEXT_TYPE_padding			35655
-
 /* NameType value from RFC 3546 */
 #define TLSEXT_NAMETYPE_host_name 0
 /* status request value from RFC 3546 */
diff --git a/openssl.config b/openssl.config
index a4c5fbe..8248107 100644
--- a/openssl.config
+++ b/openssl.config
@@ -1082,7 +1082,6 @@
 tls12_digests.patch \
 alpn.patch \
 cbc_record_splitting.patch \
-paddingext.patch \
 dsa_nonce.patch \
 "
 
diff --git a/openssl.version b/openssl.version
index 87f49ad..2e84991 100644
--- a/openssl.version
+++ b/openssl.version
@@ -1 +1 @@
-OPENSSL_VERSION=1.0.1f
+OPENSSL_VERSION=1.0.1g
diff --git a/patches/README b/patches/README
index 5348e42..4159a85 100644
--- a/patches/README
+++ b/patches/README
@@ -43,11 +43,6 @@
 BEAST attack client-side mitigation. Removes 0/n record splitting, adds 1/n-1
 record splitting. Record splitting is disabled by default.
 
-paddingext.patch
-
-ClientHello padding extension which is added, when needed, to work around bugs
-in F5 terminators.
-
 dsa_nonce.patch
 
 Adds an option to mix in hash of message and private key into (EC)DSA nonces to
diff --git a/patches/paddingext.patch b/patches/paddingext.patch
deleted file mode 100644
index 37514bc..0000000
--- a/patches/paddingext.patch
+++ /dev/null
@@ -1,99 +0,0 @@
-From 9336ed61c26255f31fac2563d0911fc29d2143fd Mon Sep 17 00:00:00 2001
-From: Adam Langley <[email protected]>
-Date: Wed, 11 Dec 2013 16:25:17 -0500
-Subject: Add padding extension.
-
-This change adds a padding extension, when needed, in order to work
-around bugs in F5 terminators.
----
- ssl/s23_clnt.c |  5 ++++-
- ssl/s3_clnt.c  |  4 +++-
- ssl/t1_lib.c   | 25 +++++++++++++++++++++++++
- ssl/tls1.h     |  4 ++++
- 4 files changed, 36 insertions(+), 2 deletions(-)
-
-diff --git a/ssl/s23_clnt.c b/ssl/s23_clnt.c
-index 84670b6..814a4c6 100644
---- a/ssl/s23_clnt.c
-+++ b/ssl/s23_clnt.c
-@@ -487,7 +487,10 @@ static int ssl23_client_hello(SSL *s)
- 			{
- 			/* create Client Hello in SSL 3.0/TLS 1.0 format */
- 
--			/* do the record header (5 bytes) and handshake message header (4 bytes) last */
-+			/* do the record header (5 bytes) and handshake message
-+			 * header (4 bytes) last. Note: the code to add the
-+			 * padding extension in t1_lib.c depends on the size of
-+			 * this prefix. */
- 			d = p = &(buf[9]);
- 			
- 			*(p++) = version_major;
-diff --git a/ssl/s3_clnt.c b/ssl/s3_clnt.c
-index 67edeaa..f37e907 100644
---- a/ssl/s3_clnt.c
-+++ b/ssl/s3_clnt.c
-@@ -751,7 +751,9 @@ int ssl3_client_hello(SSL *s)
- 		if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
- 			goto err;
- 
--		/* Do the message type and length last */
-+		/* Do the message type and length last.
-+		 * Note: the code to add the padding extension in t1_lib.c
-+		 * depends on the size of this prefix. */
- 		d=p= &(buf[4]);
- 
- 		/* version indicates the negotiated version: for example from
-diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
-index 357db6e..a499367 100644
---- a/ssl/t1_lib.c
-+++ b/ssl/t1_lib.c
-@@ -687,6 +687,31 @@ unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned cha
-                 }
- #endif
- 
-+	/* Add padding to workaround bugs in F5 terminators.
-+	 * See https://tools.ietf.org/html/draft-agl-tls-padding-02 */
-+	{
-+	int hlen = ret - (unsigned char *)s->init_buf->data;
-+	/* The code in s23_clnt.c to build ClientHello messages includes the
-+	 * 5-byte record header in the buffer, while the code in s3_clnt.c does
-+	 * not. */
-+	if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
-+		hlen -= 5;
-+	if (hlen > 0xff && hlen < 0x200)
-+		{
-+		hlen = 0x200 - hlen;
-+		if (hlen >= 4)
-+			hlen -= 4;
-+		else
-+			hlen = 0;
-+
-+		s2n(TLSEXT_TYPE_padding, ret);
-+		s2n(hlen, ret);
-+		memset(ret, 0, hlen);
-+		ret += hlen;
-+		}
-+	}
-+
-+
- 	if ((extdatalen = ret-p-2)== 0) 
- 		return p;
- 
-diff --git a/ssl/tls1.h b/ssl/tls1.h
-index ecf5da7..df8f482 100644
---- a/ssl/tls1.h
-+++ b/ssl/tls1.h
-@@ -255,6 +255,10 @@ extern "C" {
- #define TLSEXT_TYPE_channel_id			30031
- #define TLSEXT_TYPE_channel_id_new		30032
- 
-+/* See https://tools.ietf.org/html/draft-agl-tls-padding-02
-+ * Number not yet IANA assigned. */
-+#define TLSEXT_TYPE_padding			35655
-+
- /* NameType value from RFC 3546 */
- #define TLSEXT_NAMETYPE_host_name 0
- /* status request value from RFC 3546 */
--- 
-1.8.5.1
-
diff --git a/ssl/d1_both.c b/ssl/d1_both.c
index 7a5596a..2e8cf68 100644
--- a/ssl/d1_both.c
+++ b/ssl/d1_both.c
@@ -1459,26 +1459,36 @@
 	unsigned int payload;
 	unsigned int padding = 16; /* Use minimum padding */
 
-	/* Read type and payload length first */
-	hbtype = *p++;
-	n2s(p, payload);
-	pl = p;
-
 	if (s->msg_callback)
 		s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
 			&s->s3->rrec.data[0], s->s3->rrec.length,
 			s, s->msg_callback_arg);
 
+	/* Read type and payload length first */
+	if (1 + 2 + 16 > s->s3->rrec.length)
+		return 0; /* silently discard */
+	hbtype = *p++;
+	n2s(p, payload);
+	if (1 + 2 + payload + 16 > s->s3->rrec.length)
+		return 0; /* silently discard per RFC 6520 sec. 4 */
+	pl = p;
+
 	if (hbtype == TLS1_HB_REQUEST)
 		{
 		unsigned char *buffer, *bp;
+		unsigned int write_length = 1 /* heartbeat type */ +
+					    2 /* heartbeat length */ +
+					    payload + padding;
 		int r;
 
+		if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
+			return 0;
+
 		/* Allocate memory for the response, size is 1 byte
 		 * message type, plus 2 bytes payload length, plus
 		 * payload, plus padding
 		 */
-		buffer = OPENSSL_malloc(1 + 2 + payload + padding);
+		buffer = OPENSSL_malloc(write_length);
 		bp = buffer;
 
 		/* Enter response type, length and copy payload */
@@ -1489,11 +1499,11 @@
 		/* Random padding */
 		RAND_pseudo_bytes(bp, padding);
 
-		r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
+		r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
 
 		if (r >= 0 && s->msg_callback)
 			s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
-				buffer, 3 + payload + padding,
+				buffer, write_length,
 				s, s->msg_callback_arg);
 
 		OPENSSL_free(buffer);
diff --git a/ssl/kssl.h b/ssl/kssl.h
index 8242fd5..e4df843 100644
--- a/ssl/kssl.h
+++ b/ssl/kssl.h
@@ -70,6 +70,15 @@
 #include <stdio.h>
 #include <ctype.h>
 #include <krb5.h>
+#ifdef OPENSSL_SYS_WIN32
+/* These can sometimes get redefined indirectly by krb5 header files
+ * after they get undefed in ossl_typ.h
+ */
+#undef X509_NAME
+#undef X509_EXTENSIONS
+#undef OCSP_REQUEST
+#undef OCSP_RESPONSE
+#endif
 
 #ifdef  __cplusplus
 extern "C" {
diff --git a/ssl/s23_clnt.c b/ssl/s23_clnt.c
index fefcd16..2bc9214 100644
--- a/ssl/s23_clnt.c
+++ b/ssl/s23_clnt.c
@@ -283,7 +283,7 @@
 		send_time = (s->mode & SSL_MODE_SEND_CLIENTHELLO_TIME) != 0;
 	if (send_time)
 		{
-		unsigned long Time = time(NULL);
+		unsigned long Time = (unsigned long)time(NULL);
 		unsigned char *p = result;
 		l2n(Time, p);
 		return RAND_pseudo_bytes(p, len-4);
@@ -487,10 +487,7 @@
 			{
 			/* create Client Hello in SSL 3.0/TLS 1.0 format */
 
-			/* do the record header (5 bytes) and handshake message
-			 * header (4 bytes) last. Note: the code to add the
-			 * padding extension in t1_lib.c depends on the size of
-			 * this prefix. */
+			/* do the record header (5 bytes) and handshake message header (4 bytes) last */
 			d = p = &(buf[9]);
 			
 			*(p++) = version_major;
diff --git a/ssl/s3_clnt.c b/ssl/s3_clnt.c
index efbd666..f71470a 100644
--- a/ssl/s3_clnt.c
+++ b/ssl/s3_clnt.c
@@ -756,9 +756,7 @@
 		if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
 			goto err;
 
-		/* Do the message type and length last.
-		 * Note: the code to add the padding extension in t1_lib.c
-		 * depends on the size of this prefix. */
+		/* Do the message type and length last */
 		d=p= &(buf[4]);
 
 		/* version indicates the negotiated version: for example from
diff --git a/ssl/s3_srvr.c b/ssl/s3_srvr.c
index 1915885..8692f14 100644
--- a/ssl/s3_srvr.c
+++ b/ssl/s3_srvr.c
@@ -1854,7 +1854,7 @@
 			SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
 			goto f_err;
 			}
-		for (i=0; r[i] != NULL && i<4; i++)
+		for (i=0; i < 4 && r[i] != NULL; i++)
 			{
 			nr[i]=BN_num_bytes(r[i]);
 #ifndef OPENSSL_NO_SRP
@@ -1890,7 +1890,7 @@
 		d=(unsigned char *)s->init_buf->data;
 		p= &(d[4]);
 
-		for (i=0; r[i] != NULL && i<4; i++)
+		for (i=0; i < 4 && r[i] != NULL; i++)
 			{
 #ifndef OPENSSL_NO_SRP
 			if ((i == 2) && (type & SSL_kSRP))
diff --git a/ssl/ssl.h b/ssl/ssl.h
index 4c38f6e..40c4d9c 100644
--- a/ssl/ssl.h
+++ b/ssl/ssl.h
@@ -928,7 +928,7 @@
 	 */
 	unsigned int max_send_fragment;
 
-#ifndef OPENSSL_ENGINE
+#ifndef OPENSSL_NO_ENGINE
 	/* Engine to pass requests for client certs to
 	 */
 	ENGINE *client_cert_engine;
diff --git a/ssl/t1_enc.c b/ssl/t1_enc.c
index 07cb62b..2ed2e07 100644
--- a/ssl/t1_enc.c
+++ b/ssl/t1_enc.c
@@ -986,7 +986,8 @@
 		}
 		else
 		{
-			EVP_MD_CTX_copy(&hmac,hash);
+			if (!EVP_MD_CTX_copy(&hmac,hash))
+				return -1;
 			mac_ctx = &hmac;
 		}
 
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index eba732f..369e09f 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -684,8 +684,13 @@
                 }
 #endif
 
+#ifdef TLSEXT_TYPE_padding
 	/* Add padding to workaround bugs in F5 terminators.
-	 * See https://tools.ietf.org/html/draft-agl-tls-padding-02 */
+	 * See https://tools.ietf.org/html/draft-agl-tls-padding-03
+	 *
+	 * NB: because this code works out the length of all existing
+	 * extensions it MUST always appear last.
+	 */
 	{
 	int hlen = ret - (unsigned char *)s->init_buf->data;
 	/* The code in s23_clnt.c to build ClientHello messages includes the
@@ -707,7 +712,7 @@
 		ret += hlen;
 		}
 	}
-
+#endif
 
 	if ((extdatalen = ret-p-2)== 0) 
 		return p;
@@ -1412,7 +1417,7 @@
 			tls1_process_sigalgs(s, data, dsize);
 			}
 		else if (type == TLSEXT_TYPE_status_request &&
-		         s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
+		         s->version != DTLS1_VERSION)
 			{
 		
 			if (size < 5) 
@@ -2744,16 +2749,20 @@
 	unsigned int payload;
 	unsigned int padding = 16; /* Use minimum padding */
 
-	/* Read type and payload length first */
-	hbtype = *p++;
-	n2s(p, payload);
-	pl = p;
-
 	if (s->msg_callback)
 		s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
 			&s->s3->rrec.data[0], s->s3->rrec.length,
 			s, s->msg_callback_arg);
 
+	/* Read type and payload length first */
+	if (1 + 2 + 16 > s->s3->rrec.length)
+		return 0; /* silently discard */
+	hbtype = *p++;
+	n2s(p, payload);
+	if (1 + 2 + payload + 16 > s->s3->rrec.length)
+		return 0; /* silently discard per RFC 6520 sec. 4 */
+	pl = p;
+
 	if (hbtype == TLS1_HB_REQUEST)
 		{
 		unsigned char *buffer, *bp;
diff --git a/ssl/tls1.h b/ssl/tls1.h
index 6f031a4..6283c6a 100644
--- a/ssl/tls1.h
+++ b/ssl/tls1.h
@@ -230,6 +230,12 @@
 /* ExtensionType value from RFC5620 */
 #define TLSEXT_TYPE_heartbeat	15
 
+/* ExtensionType value for TLS padding extension.
+ * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
+ * http://tools.ietf.org/html/draft-agl-tls-padding-03
+ */
+#define TLSEXT_TYPE_padding	21
+
 /* ExtensionType value from draft-ietf-tls-applayerprotoneg-00 */
 #define TLSEXT_TYPE_application_layer_protocol_negotiation 16
 
@@ -254,10 +260,6 @@
 /* This is not an IANA defined extension number */
 #define TLSEXT_TYPE_channel_id			30031
 
-/* See https://tools.ietf.org/html/draft-agl-tls-padding-02
- * Number not yet IANA assigned. */
-#define TLSEXT_TYPE_padding			35655
-
 /* NameType value from RFC 3546 */
 #define TLSEXT_NAMETYPE_host_name 0
 /* status request value from RFC 3546 */