ssl_socket.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. """PyOpenSSL utilities including HTTPSSocket class which wraps PyOpenSSL
  2. SSL connection into a httplib-like interface suitable for use with urllib2
  3. """
  4. __author__ = "P J Kershaw"
  5. __date__ = "21/12/10"
  6. __copyright__ = "(C) 2012 Science and Technology Facilities Council"
  7. __license__ = "BSD - see LICENSE file in top-level directory"
  8. __contact__ = "Philip.Kershaw@stfc.ac.uk"
  9. __revision__ = '$Id$'
  10. from datetime import datetime
  11. import logging
  12. import socket
  13. from cStringIO import StringIO
  14. from OpenSSL import SSL
  15. log = logging.getLogger(__name__)
  16. class SSLSocket(object):
  17. """SSL Socket class wraps pyOpenSSL's SSL.Connection class implementing
  18. the makefile method so that it is compatible with the standard socket
  19. interface and usable with httplib.
  20. @cvar default_buf_size: default buffer size for recv operations in the
  21. makefile method
  22. @type default_buf_size: int
  23. """
  24. default_buf_size = 8192
  25. def __init__(self, ctx, sock=None):
  26. """Create SSL socket object
  27. @param ctx: SSL context
  28. @type ctx: OpenSSL.SSL.Context
  29. @param sock: underlying socket object
  30. @type sock: socket.socket
  31. """
  32. if sock is not None:
  33. self.socket = sock
  34. else:
  35. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  36. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  37. self.__ssl_conn = SSL.Connection(ctx, self.socket)
  38. self.buf_size = self.__class__.default_buf_size
  39. def __del__(self):
  40. """Close underlying socket when this object goes out of scope
  41. """
  42. self.close()
  43. @property
  44. def buf_size(self):
  45. """Buffer size for makefile method recv() operations"""
  46. return self.__buf_size
  47. @buf_size.setter
  48. def buf_size(self, value):
  49. """Buffer size for makefile method recv() operations"""
  50. if not isinstance(value, (int, long)):
  51. raise TypeError('Expecting int or long type for "buf_size"; '
  52. 'got %r instead' % type(value))
  53. self.__buf_size = value
  54. def close(self):
  55. """Shutdown the SSL connection and call the close method of the
  56. underlying socket"""
  57. try:
  58. self.__ssl_conn.shutdown()
  59. except SSL.Error, e:
  60. # Make errors on shutdown non-fatal
  61. log.warning('Connection shutdown failed: %r', e)
  62. self.__ssl_conn.close()
  63. def set_shutdown(self, mode):
  64. """Set the shutdown state of the Connection.
  65. @param mode: bit vector of either or both of SENT_SHUTDOWN and
  66. RECEIVED_SHUTDOWN
  67. """
  68. self.__ssl_conn.set_shutdown(mode)
  69. def get_shutdown(self):
  70. """Get the shutdown state of the Connection.
  71. @return: bit vector of either or both of SENT_SHUTDOWN and
  72. RECEIVED_SHUTDOWN
  73. """
  74. return self.__ssl_conn.get_shutdown()
  75. def bind(self, addr):
  76. """bind to the given address - calls method of the underlying socket
  77. @param addr: address/port number tuple
  78. @type addr: tuple"""
  79. self.__ssl_conn.bind(addr)
  80. def listen(self, backlog):
  81. """Listen for connections made to the socket.
  82. @param backlog: specifies the maximum number of queued connections and
  83. should be at least 1; the maximum value is system-dependent (usually 5).
  84. @param backlog: int
  85. """
  86. self.__ssl_conn.listen(backlog)
  87. def set_accept_state(self):
  88. """Set the connection to work in server mode. The handshake will be
  89. handled automatically by read/write"""
  90. self.__ssl_conn.set_accept_state()
  91. def accept(self):
  92. """Accept an SSL connection.
  93. @return: pair (ssl, addr) where ssl is a new SSL connection object and
  94. addr is the address bound to the other end of the SSL connection.
  95. @rtype: tuple
  96. """
  97. return self.__ssl_conn.accept()
  98. def set_connect_state(self):
  99. """Set the connection to work in client mode. The handshake will be
  100. handled automatically by read/write"""
  101. self.__ssl_conn.set_connect_state()
  102. def connect(self, addr):
  103. """Call the connect method of the underlying socket and set up SSL on
  104. the socket, using the Context object supplied to this Connection object
  105. at creation.
  106. @param addr: address/port number pair
  107. @type addr: tuple
  108. """
  109. self.__ssl_conn.connect(addr)
  110. def shutdown(self, how):
  111. """Send the shutdown message to the Connection.
  112. @param how: for socket.socket this flag determines whether read, write
  113. or both type operations are supported. OpenSSL.SSL.Connection doesn't
  114. support this so this parameter is IGNORED
  115. @return: true if the shutdown message exchange is completed and false
  116. otherwise (in which case you call recv() or send() when the connection
  117. becomes readable/writeable.
  118. @rtype: bool
  119. """
  120. return self.__ssl_conn.shutdown()
  121. def renegotiate(self):
  122. """Renegotiate this connection's SSL parameters."""
  123. return self.__ssl_conn.renegotiate()
  124. def pending(self):
  125. """@return: numbers of bytes that can be safely read from the SSL
  126. buffer.
  127. @rtype: int
  128. """
  129. return self.__ssl_conn.pending()
  130. def send(self, data, *flags_arg):
  131. """Send data to the socket. Nb. The optional flags argument is ignored.
  132. - retained for compatibility with socket.socket interface
  133. @param data: data to send down the socket
  134. @type data: string
  135. """
  136. return self.__ssl_conn.send(data)
  137. def sendall(self, data):
  138. self.__ssl_conn.sendall(data)
  139. def recv(self, size=default_buf_size):
  140. """Receive data from the Connection.
  141. @param size: The maximum amount of data to be received at once
  142. @type size: int
  143. @return: data received.
  144. @rtype: string
  145. """
  146. return self.__ssl_conn.recv(size)
  147. def setblocking(self, mode):
  148. """Set this connection's underlying socket blocking _mode_.
  149. @param mode: blocking mode
  150. @type mode: int
  151. """
  152. self.__ssl_conn.setblocking(mode)
  153. def fileno(self):
  154. """
  155. @return: file descriptor number for the underlying socket
  156. @rtype: int
  157. """
  158. return self.__ssl_conn.fileno()
  159. def getsockopt(self, *args):
  160. """See socket.socket.getsockopt
  161. """
  162. return self.__ssl_conn.getsockopt(*args)
  163. def setsockopt(self, *args):
  164. """See socket.socket.setsockopt
  165. @return: value of the given socket option
  166. @rtype: int/string
  167. """
  168. return self.__ssl_conn.setsockopt(*args)
  169. def state_string(self):
  170. """Return the SSL state of this connection."""
  171. return self.__ssl_conn.state_string()
  172. def makefile(self, *args):
  173. """Specific to Python socket API and required by httplib: convert
  174. response into a file-like object. This implementation reads using recv
  175. and copies the output into a StringIO buffer to simulate a file object
  176. for consumption by httplib
  177. Nb. Ignoring optional file open mode (StringIO is generic and will
  178. open for read and write unless a string is passed to the constructor)
  179. and buffer size - httplib set a zero buffer size which results in recv
  180. reading nothing
  181. @return: file object for data returned from socket
  182. @rtype: cStringIO.StringO
  183. """
  184. # Optimisation
  185. _buf_size = self.buf_size
  186. i=0
  187. stream = StringIO()
  188. startTime = datetime.utcnow()
  189. try:
  190. dat = self.__ssl_conn.recv(_buf_size)
  191. while dat:
  192. i+=1
  193. stream.write(dat)
  194. dat = self.__ssl_conn.recv(_buf_size)
  195. except (SSL.ZeroReturnError, SSL.SysCallError):
  196. # Connection is closed - assuming here that all is well and full
  197. # response has been received. httplib will catch an error in
  198. # incomplete content since it checks the content-length header
  199. # against the actual length of data received
  200. pass
  201. if log.getEffectiveLevel() <= logging.DEBUG:
  202. log.debug("Socket.makefile %d recv calls completed in %s", i,
  203. datetime.utcnow() - startTime)
  204. # Make sure to rewind the buffer otherwise consumers of the content will
  205. # read from the end of the buffer
  206. stream.seek(0)
  207. return stream
  208. def getsockname(self):
  209. """
  210. @return: the socket's own address
  211. @rtype:
  212. """
  213. return self.__ssl_conn.getsockname()
  214. def getpeername(self):
  215. """
  216. @return: remote address to which the socket is connected
  217. """
  218. return self.__ssl_conn.getpeername()
  219. def get_context(self):
  220. '''Retrieve the Context object associated with this Connection. '''
  221. return self.__ssl_conn.get_context()
  222. def get_peer_certificate(self):
  223. '''Retrieve the other side's certificate (if any) '''
  224. return self.__ssl_conn.get_peer_certificate()