Skip to content

Commit

Permalink
Fix SNI handling in Socket
Browse files Browse the repository at this point in the history
  • Loading branch information
jptomoya committed Nov 10, 2024
1 parent 08adcce commit 5753ec1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
4 changes: 3 additions & 1 deletion ptrlib/connection/sock.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ def __init__(self,
self.context = _ssl.SSLContext(_ssl.PROTOCOL_TLS_CLIENT)
self.context.check_hostname = False
self.context.verify_mode = _ssl.CERT_NONE
if sni is True:
if not sni:
self._sock = self.context.wrap_socket(self._sock)
elif sni is True:
self._sock = self.context.wrap_socket(self._sock, server_hostname=host)
else:
self._sock = self.context.wrap_socket(self._sock, server_hostname=sni)

Expand Down
37 changes: 26 additions & 11 deletions tests/connection/test_sock.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import unittest
from socket import gethostbyname
from ptrlib import Socket
Expand Down Expand Up @@ -45,21 +46,35 @@ def test_reset(self):
self.assertEqual(b"200 OK" in cm.exception.args[1], True)

def test_tls(self):
host = "www.example.com"
host = "check-tls.akamaized.net"
path = "/v1/tlssni.json"

# connect with sni
ip_addr = gethostbyname(host)
sock = Socket(ip_addr, 443, ssl=True, sni=host)
sock.sendline(b'GET / HTTP/1.1\r')
sock.send(b'Host: www.example.com\r\n')
# connect with SNI enabled
sock = Socket(host, 443, ssl=True)
sock.sendline(f'GET {path} HTTP/1.1'.encode() + b'\r')
sock.send(f'Host: {host}'.encode() + b'\r\n')
sock.send(b'Connection: close\r\n\r\n')
self.assertTrue(int(sock.recvlineafter('Content-Length: ')) > 0)
sock.close()

# connect without sni
sock = Socket(host, 443, ssl=True)
sock.sendline(b'GET / HTTP/1.1\r')
sock.send(b'Host: www.example.com\r\n')
# connect with a specific SNI value
sock = Socket(host, 443, ssl=True, sni="example.com")
sock.sendline(f'GET {path} HTTP/1.1'.encode() + b'\r')
sock.send(f'Host: {host}'.encode() + b'\r\n')
sock.send(b'Connection: close\r\n\r\n')
self.assertTrue(int(sock.recvlineafter('Content-Length: ')) > 0)
self.assertTrue((contentlength := int(sock.recvlineafter('Content-Length: '))) > 0)
sock.recvuntil(b'\r\n\r\n')
content = json.loads(sock.recvonce(contentlength))
sock.close()
self.assertEqual(content['tls_sni_value'], "example.com")

# connect with SNI disabled
sock = Socket(host, 443, ssl=True, sni=False)
sock.sendline(f'GET {path} HTTP/1.1'.encode() + b'\r')
sock.send(f'Host: {host}'.encode() + b'\r\n')
sock.send(b'Connection: close\r\n\r\n')
self.assertTrue((contentlength := int(sock.recvlineafter('Content-Length: '))) > 0)
sock.recvuntil(b'\r\n\r\n')
content = json.loads(sock.recvonce(contentlength))
sock.close()
self.assertEqual(content['tls_sni_status'], "missing")

0 comments on commit 5753ec1

Please sign in to comment.