blob: 5ad94476005277db2ca51c8b22423c35b1f757bc [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
4"""\
5This module provides some more Pythonic support for SSL.
6
7Object types:
8
9 sslsocket -- subtype of socket.socket which does SSL over the socket
10
11Exceptions:
12
13 sslerror -- exception raised for I/O errors
14
15Functions:
16
17 cert_time_to_seconds -- convert time string used for certificate
18 notBefore and notAfter functions to integer
19 seconds past the Epoch (the time values
20 returned from time.time())
21
22 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
23 by the server running on HOST at port PORT. No
24 validation of the certificate is performed.
25
26Integer constants:
27
28SSL_ERROR_ZERO_RETURN
29SSL_ERROR_WANT_READ
30SSL_ERROR_WANT_WRITE
31SSL_ERROR_WANT_X509_LOOKUP
32SSL_ERROR_SYSCALL
33SSL_ERROR_SSL
34SSL_ERROR_WANT_CONNECT
35
36SSL_ERROR_EOF
37SSL_ERROR_INVALID_ERROR_CODE
38
39The following group define certificate requirements that one side is
40allowing/requiring from the other side:
41
42CERT_NONE - no certificates from the other side are required (or will
43 be looked at if provided)
44CERT_OPTIONAL - certificates are not required, but if provided will be
45 validated, and if validation fails, the connection will
46 also fail
47CERT_REQUIRED - certificates are required, and will be validated, and
48 if validation fails, the connection will also fail
49
50The following constants identify various SSL protocol variants:
51
52PROTOCOL_SSLv2
53PROTOCOL_SSLv3
54PROTOCOL_SSLv23
55PROTOCOL_TLSv1
56"""
57
58import os, sys
59
60import _ssl # if we can't import it, let the error propagate
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000061from _ssl import sslerror
62from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
63from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Bill Janssen426ea0a2007-08-29 22:35:05 +000064from _ssl import \
65 SSL_ERROR_ZERO_RETURN, \
66 SSL_ERROR_WANT_READ, \
67 SSL_ERROR_WANT_WRITE, \
68 SSL_ERROR_WANT_X509_LOOKUP, \
69 SSL_ERROR_SYSCALL, \
70 SSL_ERROR_SSL, \
71 SSL_ERROR_WANT_CONNECT, \
72 SSL_ERROR_EOF, \
73 SSL_ERROR_INVALID_ERROR_CODE
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000074
Bill Janssen426ea0a2007-08-29 22:35:05 +000075from socket import socket
76from socket import getnameinfo as _getnameinfo
77
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000078
79class sslsocket (socket):
80
Bill Janssen426ea0a2007-08-29 22:35:05 +000081 """This class implements a subtype of socket.socket that wraps
82 the underlying OS socket in an SSL context when necessary, and
83 provides read and write methods over that channel."""
84
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000085 def __init__(self, sock, keyfile=None, certfile=None,
86 server_side=False, cert_reqs=CERT_NONE,
87 ssl_version=PROTOCOL_SSLv23, ca_certs=None):
88 socket.__init__(self, _sock=sock._sock)
89 if certfile and not keyfile:
90 keyfile = certfile
Bill Janssen426ea0a2007-08-29 22:35:05 +000091 # see if it's connected
92 try:
93 socket.getpeername(self)
94 except:
95 # no, no connection yet
96 self._sslobj = None
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000097 else:
Bill Janssen426ea0a2007-08-29 22:35:05 +000098 # yes, create the SSL object
99 self._sslobj = _ssl.sslwrap(self._sock, server_side,
100 keyfile, certfile,
101 cert_reqs, ssl_version, ca_certs)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000102 self.keyfile = keyfile
103 self.certfile = certfile
104 self.cert_reqs = cert_reqs
105 self.ssl_version = ssl_version
106 self.ca_certs = ca_certs
107
108 def read(self, len=1024):
Bill Janssen24bccf22007-08-30 17:07:28 +0000109
110 """Read up to LEN bytes and return them.
111 Return zero-length string on EOF."""
112
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000113 return self._sslobj.read(len)
114
115 def write(self, data):
Bill Janssen24bccf22007-08-30 17:07:28 +0000116
117 """Write DATA to the underlying SSL channel. Returns
118 number of bytes of DATA actually transmitted."""
119
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000120 return self._sslobj.write(data)
121
122 def getpeercert(self):
Bill Janssen24bccf22007-08-30 17:07:28 +0000123
124 """Returns a formatted version of the data in the
125 certificate provided by the other end of the SSL channel.
126 Return None if no certificate was provided, {} if a
127 certificate was provided, but not validated."""
128
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000129 return self._sslobj.peer_certificate()
130
131 def send (self, data, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000132 if self._sslobj:
133 if flags != 0:
134 raise ValueError(
135 "non-zero flags not allowed in calls to send() on %s" %
136 self.__class__)
137 return self._sslobj.write(data)
138 else:
139 return socket.send(self, data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000140
141 def send_to (self, data, addr, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000142 if self._sslobj:
143 raise ValueError("send_to not allowed on instances of %s" %
144 self.__class__)
145 else:
146 return socket.send_to(self, data, addr, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000147
148 def sendall (self, data, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000149 if self._sslobj:
150 if flags != 0:
151 raise ValueError(
152 "non-zero flags not allowed in calls to sendall() on %s" %
153 self.__class__)
154 return self._sslobj.write(data)
155 else:
156 return socket.sendall(self, data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000157
158 def recv (self, buflen=1024, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000159 if self._sslobj:
160 if flags != 0:
161 raise ValueError(
162 "non-zero flags not allowed in calls to sendall() on %s" %
163 self.__class__)
164 return self._sslobj.read(data, buflen)
165 else:
166 return socket.recv(self, buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000167
168 def recv_from (self, addr, buflen=1024, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000169 if self._sslobj:
170 raise ValueError("recv_from not allowed on instances of %s" %
171 self.__class__)
172 else:
173 return socket.recv_from(self, addr, buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000174
Bill Janssen426ea0a2007-08-29 22:35:05 +0000175 def ssl_shutdown(self):
Bill Janssen24bccf22007-08-30 17:07:28 +0000176
177 """Shuts down the SSL channel over this socket (if active),
178 without closing the socket connection."""
179
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000180 if self._sslobj:
181 self._sslobj.shutdown()
182 self._sslobj = None
Bill Janssen426ea0a2007-08-29 22:35:05 +0000183
184 def shutdown(self, how):
185 self.ssl_shutdown()
186 socket.shutdown(self, how)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000187
188 def close(self):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000189 self.ssl_shutdown()
190 socket.close(self)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000191
192 def connect(self, addr):
Bill Janssen24bccf22007-08-30 17:07:28 +0000193
194 """Connects to remote ADDR, and then wraps the connection in
195 an SSL channel."""
196
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000197 # Here we assume that the socket is client-side, and not
198 # connected at the time of the call. We connect it, then wrap it.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000199 if self._sslobj:
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000200 raise ValueError("attempt to connect already-connected sslsocket!")
201 socket.connect(self, addr)
Bill Janssen426ea0a2007-08-29 22:35:05 +0000202 self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000203 self.cert_reqs, self.ssl_version,
204 self.ca_certs)
205
206 def accept(self):
Bill Janssen24bccf22007-08-30 17:07:28 +0000207
208 """Accepts a new connection from a remote client, and returns
209 a tuple containing that new connection wrapped with a server-side
210 SSL channel, and the address of the remote client."""
211
Bill Janssen426ea0a2007-08-29 22:35:05 +0000212 newsock, addr = socket.accept(self)
213 return (sslsocket(newsock, True, self.keyfile, self.certfile,
214 self.cert_reqs, self.ssl_version,
215 self.ca_certs), addr)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000216
217
218# some utility functions
219
220def cert_time_to_seconds(cert_time):
Bill Janssen24bccf22007-08-30 17:07:28 +0000221
222 """Takes a date-time string in standard ASN1_print form
223 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
224 a Python time value in seconds past the epoch."""
225
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000226 import time
227 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
228
229# a replacement for the old socket.ssl function
230
231def sslwrap_simple (sock, keyfile=None, certfile=None):
232
Bill Janssen24bccf22007-08-30 17:07:28 +0000233 """A replacement for the old socket.ssl function. Designed
234 for compability with Python 2.5 and earlier. Will disappear in
235 Python 3.0."""
236
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000237 return _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
238 PROTOCOL_SSLv23, None)