File: socklib.py

package info (click to toggle)
m2crypto 0.46.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,964 kB
  • sloc: python: 22,936; makefile: 213; ansic: 94; sh: 17
file content (52 lines) | stat: -rw-r--r-- 1,363 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
socklib provides a way to transparently replace socket.ssl with
M2Crypto.SSL.Connection.

Usage: Import socklib before the 3rd party module that uses socket.ssl. Also,
       call socketlib.setSSLContextFactory() to set it up with a way to get
       secure SSL contexts.

Copyright (c) 2007 Open Source Applications Foundation.
All rights reserved.
"""

sslContextFactory = None


def setSSLContextFactory(factory):
    global sslContextFactory
    sslContextFactory = factory


from M2Crypto.SSL import Connection, Checker
import socket


class ssl_socket(socket.socket):
    def connect(self, addr, *args):
        self.addr = addr
        return super(ssl_socket, self).connect(addr, *args)

    def close(self):
        if hasattr(self, "conn"):
            self.conn.close()
        socket.socket.close(self)


def ssl(sock):
    sock.conn = Connection(ctx=sslContextFactory(), sock=sock)
    sock.conn.addr = sock.addr
    sock.conn.setup_ssl()
    sock.conn.set_connect_state()
    sock.conn.connect_ssl()
    check = getattr(
        sock.conn, "postConnectionCheck", sock.conn.clientPostConnectionCheck
    )
    if check is not None:
        if not check(sock.conn.get_peer_cert(), sock.conn.addr[0]):
            raise Checker.SSLVerificationError("post connection check failed")
    return sock.conn


socket.socket = ssl_socket
socket.ssl = ssl