Blame SOURCES/00298-do-not-send-IP-in-SNI-TLS-extension.patch

925e6b
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
925e6b
index d0a3830..51b192c 100644
925e6b
--- a/Modules/_ssl.c
925e6b
+++ b/Modules/_ssl.c
925e6b
@@ -50,6 +50,11 @@
925e6b
 #include <sys/poll.h>
925e6b
 #endif
925e6b
 
925e6b
+#ifndef MS_WINDOWS
925e6b
+/* inet_pton */
925e6b
+#include <arpa/inet.h>
925e6b
+#endif
925e6b
+
925e6b
 /* Include OpenSSL header files */
925e6b
 #include "openssl/rsa.h"
925e6b
 #include "openssl/crypto.h"
925e6b
@@ -493,8 +498,41 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
925e6b
     SSL_set_mode(self->ssl, mode);
925e6b
 
925e6b
 #if HAVE_SNI
925e6b
-    if (server_hostname != NULL)
925e6b
-        SSL_set_tlsext_host_name(self->ssl, server_hostname);
925e6b
+    if (server_hostname != NULL) {
925e6b
+/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
925e6b
+ * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
925e6b
+ * available on all platforms. Use OpenSSL's IP address parser. It's
925e6b
+ * available since 1.0.2 and LibreSSL since at least 2.3.0. */
925e6b
+        int send_sni = 1;
925e6b
+#if OPENSSL_VERSION_NUMBER >= 0x10200000L
925e6b
+        ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
925e6b
+        if (ip == NULL) {
925e6b
+            send_sni = 1;
925e6b
+            ERR_clear_error();
925e6b
+        } else {
925e6b
+            send_sni = 0;
925e6b
+            ASN1_OCTET_STRING_free(ip);
925e6b
+        }
925e6b
+#elif defined(HAVE_INET_PTON)
925e6b
+#ifdef ENABLE_IPV6
925e6b
+        char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
925e6b
+#else
925e6b
+        char packed[sizeof(struct in_addr)];
925e6b
+#endif /* ENABLE_IPV6 */
925e6b
+        if (inet_pton(AF_INET, server_hostname, packed)) {
925e6b
+            send_sni = 0;
925e6b
+#ifdef ENABLE_IPV6
925e6b
+        } else if(inet_pton(AF_INET6, server_hostname, packed)) {
925e6b
+            send_sni = 0;
925e6b
+#endif /* ENABLE_IPV6 */
925e6b
+        } else {
925e6b
+            send_sni = 1;
925e6b
+        }
925e6b
+#endif /* HAVE_INET_PTON */
925e6b
+        if (send_sni) {
925e6b
+            SSL_set_tlsext_host_name(self->ssl, server_hostname);
925e6b
+        }
925e6b
+    }
925e6b
 #endif
925e6b
 
925e6b
     /* If the socket is in non-blocking mode or timeout mode, set the BIO