title: Sending SSL data over a TCP proxy connection in Python
body: <p>I am facing the following scenario:
  I am forced to use an HTTP proxy to connect to an HTTPS server. For several reasons I need access to the raw data (before encryption) so I am using the socket library instead of one of the HTTP specific libraries.
  I thus first connect a TCP socket to the HTTP proxy and issue the connect command.</p>
  <p>At this point, the HTTP proxy accepts the connection and seemingly forwards all further data to the target server.
  However, if I now try to switch to SSL, I receive</p>
  <blockquote>
  <p>error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol</p>
  </blockquote>
  <p>indicating that the socket attempted the handshake with the HTTP proxy and not with the HTTPS target.</p>
  <p>Here's the code I have so far:</p>
  <pre><code>import socket
  
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  s.connect(('proxy',9502))  
  s.send(&quot;&quot;&quot;CONNECT en.wikipedia.org:443 HTTP/1.1
  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:15.0) Gecko/20100101 Firefox/15.0.1  
  Proxy-Connection: keep-alive  
  Host: en.wikipedia.org 
  
  &quot;&quot;&quot;)  
  
  print s.recv(1000)  
  
  ssl = socket.ssl(s, None, None)  
  ssl.connect((&quot;en.wikipedia.org&quot;,443))  
  </code></pre>
  <p>What would be the correct way to open an SSL socket to the target server after connecting to the HTTP proxy?</p>