blob: 388c931d4bca12425dfbd378521f0be6d74e62fa [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum245b42e2007-08-29 03:59:57 +00004raise ImportError("ssl.py is temporarily out of order")
5
Thomas Woutersed03b412007-08-28 21:37:11 +00006"""\
7This module provides some more Pythonic support for SSL.
8
9Object types:
10
11 sslsocket -- subtype of socket.socket which does SSL over the socket
12
13Exceptions:
14
15 sslerror -- exception raised for I/O errors
16
17Functions:
18
19 cert_time_to_seconds -- convert time string used for certificate
20 notBefore and notAfter functions to integer
21 seconds past the Epoch (the time values
22 returned from time.time())
23
24 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
25 by the server running on HOST at port PORT. No
26 validation of the certificate is performed.
27
28Integer constants:
29
30SSL_ERROR_ZERO_RETURN
31SSL_ERROR_WANT_READ
32SSL_ERROR_WANT_WRITE
33SSL_ERROR_WANT_X509_LOOKUP
34SSL_ERROR_SYSCALL
35SSL_ERROR_SSL
36SSL_ERROR_WANT_CONNECT
37
38SSL_ERROR_EOF
39SSL_ERROR_INVALID_ERROR_CODE
40
41The following group define certificate requirements that one side is
42allowing/requiring from the other side:
43
44CERT_NONE - no certificates from the other side are required (or will
45 be looked at if provided)
46CERT_OPTIONAL - certificates are not required, but if provided will be
47 validated, and if validation fails, the connection will
48 also fail
49CERT_REQUIRED - certificates are required, and will be validated, and
50 if validation fails, the connection will also fail
51
52The following constants identify various SSL protocol variants:
53
54PROTOCOL_SSLv2
55PROTOCOL_SSLv3
56PROTOCOL_SSLv23
57PROTOCOL_TLSv1
58"""
59
60import os, sys
61
62import _ssl # if we can't import it, let the error propagate
Thomas Woutersed03b412007-08-28 21:37:11 +000063from _ssl import sslerror
64from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
65from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Thomas Wouters47b49bf2007-08-30 22:15:33 +000066from _ssl import \
67 SSL_ERROR_ZERO_RETURN, \
68 SSL_ERROR_WANT_READ, \
69 SSL_ERROR_WANT_WRITE, \
70 SSL_ERROR_WANT_X509_LOOKUP, \
71 SSL_ERROR_SYSCALL, \
72 SSL_ERROR_SSL, \
73 SSL_ERROR_WANT_CONNECT, \
74 SSL_ERROR_EOF, \
75 SSL_ERROR_INVALID_ERROR_CODE
Thomas Woutersed03b412007-08-28 21:37:11 +000076
Thomas Wouters47b49bf2007-08-30 22:15:33 +000077from socket import socket
78from socket import getnameinfo as _getnameinfo
79
Thomas Woutersed03b412007-08-28 21:37:11 +000080
81class sslsocket (socket):
82
Thomas Wouters47b49bf2007-08-30 22:15:33 +000083 """This class implements a subtype of socket.socket that wraps
84 the underlying OS socket in an SSL context when necessary, and
85 provides read and write methods over that channel."""
86
Thomas Woutersed03b412007-08-28 21:37:11 +000087 def __init__(self, sock, keyfile=None, certfile=None,
88 server_side=False, cert_reqs=CERT_NONE,
89 ssl_version=PROTOCOL_SSLv23, ca_certs=None):
90 socket.__init__(self, _sock=sock._sock)
91 if certfile and not keyfile:
92 keyfile = certfile
Thomas Wouters47b49bf2007-08-30 22:15:33 +000093 # see if it's connected
94 try:
95 socket.getpeername(self)
96 except:
97 # no, no connection yet
98 self._sslobj = None
Thomas Woutersed03b412007-08-28 21:37:11 +000099 else:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000100 # yes, create the SSL object
101 self._sslobj = _ssl.sslwrap(self._sock, server_side,
102 keyfile, certfile,
103 cert_reqs, ssl_version, ca_certs)
Thomas Woutersed03b412007-08-28 21:37:11 +0000104 self.keyfile = keyfile
105 self.certfile = certfile
106 self.cert_reqs = cert_reqs
107 self.ssl_version = ssl_version
108 self.ca_certs = ca_certs
109
110 def read(self, len=1024):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000111
112 """Read up to LEN bytes and return them.
113 Return zero-length string on EOF."""
114
Thomas Woutersed03b412007-08-28 21:37:11 +0000115 return self._sslobj.read(len)
116
117 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000118
119 """Write DATA to the underlying SSL channel. Returns
120 number of bytes of DATA actually transmitted."""
121
Thomas Woutersed03b412007-08-28 21:37:11 +0000122 return self._sslobj.write(data)
123
124 def getpeercert(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000125
126 """Returns a formatted version of the data in the
127 certificate provided by the other end of the SSL channel.
128 Return None if no certificate was provided, {} if a
129 certificate was provided, but not validated."""
130
Thomas Woutersed03b412007-08-28 21:37:11 +0000131 return self._sslobj.peer_certificate()
132
133 def send (self, data, flags=0):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000134 if self._sslobj:
135 if flags != 0:
136 raise ValueError(
137 "non-zero flags not allowed in calls to send() on %s" %
138 self.__class__)
139 return self._sslobj.write(data)
140 else:
141 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000142
143 def send_to (self, data, addr, flags=0):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000144 if self._sslobj:
145 raise ValueError("send_to not allowed on instances of %s" %
146 self.__class__)
147 else:
148 return socket.send_to(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000149
150 def sendall (self, data, flags=0):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000151 if self._sslobj:
152 if flags != 0:
153 raise ValueError(
154 "non-zero flags not allowed in calls to sendall() on %s" %
155 self.__class__)
156 return self._sslobj.write(data)
157 else:
158 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000159
160 def recv (self, buflen=1024, flags=0):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000161 if self._sslobj:
162 if flags != 0:
163 raise ValueError(
164 "non-zero flags not allowed in calls to sendall() on %s" %
165 self.__class__)
166 return self._sslobj.read(data, buflen)
167 else:
168 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000169
170 def recv_from (self, addr, buflen=1024, flags=0):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000171 if self._sslobj:
172 raise ValueError("recv_from not allowed on instances of %s" %
173 self.__class__)
174 else:
175 return socket.recv_from(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000176
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000177 def ssl_shutdown(self):
178
179 """Shuts down the SSL channel over this socket (if active),
180 without closing the socket connection."""
181
Thomas Woutersed03b412007-08-28 21:37:11 +0000182 if self._sslobj:
183 self._sslobj.shutdown()
184 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000185
186 def shutdown(self, how):
187 self.ssl_shutdown()
188 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000189
190 def close(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000191 self.ssl_shutdown()
192 socket.close(self)
Thomas Woutersed03b412007-08-28 21:37:11 +0000193
194 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000195
196 """Connects to remote ADDR, and then wraps the connection in
197 an SSL channel."""
198
Thomas Woutersed03b412007-08-28 21:37:11 +0000199 # Here we assume that the socket is client-side, and not
200 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000201 if self._sslobj:
Thomas Woutersed03b412007-08-28 21:37:11 +0000202 raise ValueError("attempt to connect already-connected sslsocket!")
203 socket.connect(self, addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000204 self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000205 self.cert_reqs, self.ssl_version,
206 self.ca_certs)
207
208 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000209
210 """Accepts a new connection from a remote client, and returns
211 a tuple containing that new connection wrapped with a server-side
212 SSL channel, and the address of the remote client."""
213
214 newsock, addr = socket.accept(self)
215 return (sslsocket(newsock, True, self.keyfile, self.certfile,
216 self.cert_reqs, self.ssl_version,
217 self.ca_certs), addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000218
219
220# some utility functions
221
222def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000223
224 """Takes a date-time string in standard ASN1_print form
225 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
226 a Python time value in seconds past the epoch."""
227
Thomas Woutersed03b412007-08-28 21:37:11 +0000228 import time
229 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
230
231# a replacement for the old socket.ssl function
232
233def sslwrap_simple (sock, keyfile=None, certfile=None):
234
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000235 """A replacement for the old socket.ssl function. Designed
236 for compability with Python 2.5 and earlier. Will disappear in
237 Python 3.0."""
238
Thomas Woutersed03b412007-08-28 21:37:11 +0000239 return _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
240 PROTOCOL_SSLv23, None)