From b82cb4912113436d1fac5f6a99be88355d596738 Mon Sep 17 00:00:00 2001
From: Emmanuel Hocdet <manu@gandi.net>
Date: Mon, 26 Feb 2018 12:04:45 +0100
Subject: [PATCH] BUG/MINOR: ssl: return alpn string with NULL terminated

According to openssl documentation: "SSL_get0_alpn_selected() returns
a pointer to the selected protocol in data with length len. It is not
NUL-terminated". It consern ssl_sock_get_alpn and smp_fetch_ssl_fc_alpn
functions and impact send-proxy-v2 with alpn. The expected get is not
an array of char but a string like other similar functions.

This fix should be backported to 1.8.
---
 src/ssl_sock.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/ssl_sock.c b/src/ssl_sock.c
index 9466d5e58..849db2265 100644
--- a/src/ssl_sock.c
+++ b/src/ssl_sock.c
@@ -6103,8 +6103,12 @@ static int ssl_sock_get_alpn(const struct connection *conn, const char **str, in
 
 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
 	SSL_get0_alpn_selected(conn->xprt_ctx, (const unsigned char **)str, (unsigned *)len);
-	if (*str)
+	/* SSL_get0_alpn_selected is not NULL terminated. */
+	if (*str) {
+		((char *)*str)[*len] = '\0';
+		*len += 1;
 		return 1;
+	}
 #endif
 #ifdef OPENSSL_NPN_NEGOTIATED
 	SSL_get0_next_proto_negotiated(conn->xprt_ctx, (const unsigned char **)str, (unsigned *)len);
@@ -6831,6 +6835,9 @@ smp_fetch_ssl_fc_alpn(const struct arg *args, struct sample *smp, const char *kw
 
 	if (!smp->data.u.str.str)
 		return 0;
+	/* SSL_get0_alpn_selected is not NULL terminated. */
+	smp->data.u.str.str[smp->data.u.str.len] = '\0';
+	smp->data.u.str.len += 1;
 
 	return 1;
 }
-- 
2.11.0

