Esempio n. 1
0
 def _get_socket(self, host, port, timeout):
     if self.debuglevel > 0:
         print('connect:', (host, port), file=sys.stderr)
     new_socket = socket.create_connection((host, port), timeout)
     new_socket = sslutil.wrapsocket(new_socket,
                                     self.keyfile, self.certfile,
                                     ui=self._ui,
                                     serverhostname=self._host)
     self.file = smtplib.SSLFakeFile(new_socket)
     return new_socket
Esempio n. 2
0
        def _get_socket(self, host, port, timeout):
            new_socket = self.socket()
            new_socket.connect((host, port))

            if SSL and ssl is not None:
                new_socket = ssl.wrap_socket(new_socket,
                                             self.keyfile, self.certfile)
                self.file = smtplib.SSLFakeFile(new_socket)

            return new_socket
Esempio n. 3
0
 def _get_socket(self, host, port, timeout):
     """ Code copied directly from Python 2.7.(3-9) (same code) with
         modifications to verify certificates.
     """
     if self.debuglevel > 0:
         print >> sys.stderr, 'connect:', (host, port)
     new_socket = socket.create_connection((host, port), timeout)
     new_socket = ssl_wrap_socket(new_socket,
                                  server_hostname=self._server_hostname)
     self.file = smtplib.SSLFakeFile(new_socket)
     return new_socket
Esempio n. 4
0
 def _get_socket(self, host, port, timeout):
     if self.debuglevel > 0:
         print >> sys.stderr, 'connect:', (host, port)
     new_socket = socket.create_connection((host, port), timeout)
     new_socket = ssl.ssl_wrap_socket(
         new_socket,
         self.keyfile,
         self.certfile,
         **self._sslkwargs
     )
     self.file = smtplib.SSLFakeFile(new_socket)
     return new_socket
Esempio n. 5
0
        def _get_socket(self, host, port, timeout):
            print('Creating socket -> %s:%s/%s using %s, SSL=%s') % (
                host, port, timeout, self.socket, SSL)

            new_socket = self.socket()
            new_socket.connect((host, port))

            if SSL and ssl is not None:
                new_socket = ssl.wrap_socket(new_socket, self.keyfile,
                                             self.certfile)
                self.file = smtplib.SSLFakeFile(new_socket)

            return new_socket
Esempio n. 6
0
 def _get_socket(self, host, port, timeout):
     if self.debuglevel > 0:
         self._ui.debug("connect: %r\n" % (host, port))
     new_socket = socket.create_connection((host, port), timeout)
     new_socket = sslutil.wrapsocket(
         new_socket,
         self.keyfile,
         self.certfile,
         ui=self._ui,
         serverhostname=self._host,
     )
     self.file = smtplib.SSLFakeFile(new_socket)
     return new_socket
Esempio n. 7
0
class SMTP_SSL(smtplib.SMTP):
    def __init__(self,
                 host='',
                 port=465,
                 local_hostname=None,
                 key=None,
                 cert=None):
        self.cert = cert
        self.key = key
        smtplib.SMTP.__init__(self, host, port, local_hostname)

    def connect(self, host='localhost', port=465):
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i + 1:]
                try:
                    port = int(port)
                except ValueError:
                    raise socket.error, "nonnumeric port"
        if not port: port = 654
        if self.debuglevel > 0: print >> stderr, 'connect:', (host, port)
        msg = "getaddrinfo returns an empty list"
        self.sock = None
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                if self.debuglevel > 0:
                    print >> stderr, 'connect:', (host, port)
                self.sock.connect(sa)
                # 新增加的创建ssl连接
                sslobj = socket.ssl(self.sock, self.key, self.cert)
            except socket.error, msg:
                if self.debuglevel > 0:
                    print >> stderr, 'connect fail:', (host, port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg

        # 设置ssl
        self.sock = smtplib.SSLFakeSocket(self.sock, sslobj)
        self.file = smtplib.SSLFakeFile(sslobj)

        (code, msg) = self.getreply()
        if self.debuglevel > 0: print >> stderr, "connect:", msg
        return (code, msg)
Esempio n. 8
0
 def starttls(self, keyfile=None, certfile=None):
     if not self.has_extn("starttls"):
         msg = "STARTTLS extension not supported by server"
         raise smtplib.SMTPException(msg)
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = sslutil.wrapsocket(self.sock, keyfile, certfile,
                                        **self._sslkwargs)
         self.file = smtplib.SSLFakeFile(self.sock)
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)
Esempio n. 9
0
 def starttls(self, keyfile=None, certfile=None):
     if not self.has_extn("starttls"):
         msg = "STARTTLS extension not supported by server"
         raise smtplib.SMTPException(msg)
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = sslutil.wrapsocket(self.sock, keyfile, certfile,
                                        **self._sslkwargs)
         if not util.safehasattr(self.sock, "read"):
             # using httplib.FakeSocket with Python 2.5.x or earlier
             self.sock.read = self.sock.recv
         self.file = smtplib.SSLFakeFile(self.sock)
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)
Esempio n. 10
0
    def starttls(self, context):
        """Start a TLS session.  The SSL parameters are taken from the
        `context` parameter.

        Don’t forget to re-EHLO afterwards, some servers will refuse to
        continue if this step is missing."""
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            self.sock = SSL.Connection(context, self.sock)
            self.file = smtplib.SSLFakeFile(self.sock)
            self.sock.set_connect_state()
            self.sock.do_handshake()
            # and suddenly, the server is a stranger again (RFC 3207, 4.2)
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        return (resp, reply)
Esempio n. 11
0
    def starttls(self, keyfile=None, certfile=None, **sslargs):
        """Puts the connection to the SMTP server into TLS mode.

        If there has been no previous EHLO or HELO command this session, this
        method tries ESMTP EHLO first.

        If the server supports TLS, this will encrypt the rest of the SMTP
        session. If you provide the keyfile and certfile parameters,
        the identity of the SMTP server and client can be checked. This,
        however, depends on whether the socket module really checks the
        certificates.

        :param sslargs: a dict with further SSL arguments, see ssl module (default: {});
        :param ca_certs: PEM formatted file for permitted certificates (default: None), if specified, and the default for cert_reqs is CERT_REQUIRED;

        This method may raise the following exceptions:

         SMTPHeloError            The server didn't reply properly to
                                  the helo greeting.
        """
        import ssl
        self.ehlo_or_helo_if_needed()
        if not self.has_extn("starttls"):
            raise smtplib.SMTPException(
                "STARTTLS extension not supported by server.")
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            if not sslargs.get('ssl_version'):
                sslargs['ssl_version'] = ssl.PROTOCOL_TLSv1
            if not sslargs.get('cert_reqs'):
                sslargs['cert_reqs'] = ssl.CERT_REQUIRED if sslargs.get(
                    'ca_certs') else ssl.CERT_NONE
            self.sock = ssl.wrap_socket(self.sock, keyfile, certfile,
                                        **sslargs)
            self.file = smtplib.SSLFakeFile(self.sock)
            # RFC 3207:
            # The client MUST discard any knowledge obtained from
            # the server, such as the list of SMTP service extensions,
            # which was not obtained from the TLS negotiation itself.
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        return (resp, reply)
Esempio n. 12
0
    def authenticate(self, auth):
        """Open a connection to an SMTPS server."""
        c = self.config

        self.host = host = c.get_method(str, self.method, "host")
        port = c.get_method(int, self.method, "port", SMTPS_PORT)
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            ssl = SSL.Connection(
                self.init_ssl_context(auth, SSL.SSLv23_METHOD), sock)
            ssl.connect((host, port))
            conn = self.conn = smtplib.SMTP()
            conn.sock = ssl
            conn.file = smtplib.SSLFakeFile(ssl)
        except (SSL.Error, crypto.Error), e:
            raise AuthenticationFailedError(n_(
                "Error while trying to establish an encrypted "
                "connection to %(host)s: %(details)s."),
                                            host=self.host,
                                            details=e.message[0][2])
Esempio n. 13
0
 def starttls(self):
     """ Code copied directly from Python 2.7.(3-9) (same code) with
         modifications to verify certificates.
     """
     self.ehlo_or_helo_if_needed()
     if not self.has_extn("starttls"):
         raise smtplib.SMTPException(
             "STARTTLS extension not supported by server.")
     (resp, reply) = self.docmd("STARTTLS")
     if resp == 220:
         self.sock = ssl_wrap_socket(self.sock, self._server_hostname)
         self.file = smtplib.SSLFakeFile(self.sock)
         # RFC 3207:
         # The client MUST discard any knowledge obtained from
         # the server, such as the list of SMTP service extensions,
         # which was not obtained from the TLS negotiation itself.
         self.helo_resp = None
         self.ehlo_resp = None
         self.esmtp_features = {}
         self.does_esmtp = 0
     return (resp, reply)
Esempio n. 14
0
    def starttls(self, keyfile=None, certfile=None):
        self.ehlo_or_helo_if_needed()
        if not self.has_extn("starttls"):
            raise smtplib.SMTPException("server doesn't support STARTTLS")

        response, reply = self.docmd("STARTTLS")
        if response == 220:
            with ca_certs(self._ca_certs) as certs:
                self.sock = ssl.wrap_socket(
                    self.sock,
                    certfile=certfile,
                    keyfile=keyfile,
                    ca_certs=certs,
                    cert_reqs=ssl.CERT_REQUIRED
                )
            cert = self.sock.getpeercert()
            match_hostname(cert, self._host)

            self.file = smtplib.SSLFakeFile(self.sock)
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        return response, reply
Esempio n. 15
0
class SMTP_SSL(smtplib.SMTP):
    """This class provides SSL access to an SMTP server.
    
    SMTP over SSL typical listens on port 465. Unlike StartTLS, SMTP over SSL
    makes an SSL connection before doing a helo/ehlo. All transactions, then,
    are done over an encrypted channel.
    
    This class is a simple subclass of the smtplib.SMTP class that comes with
    Python. It overrides the :meth:`connect()` method to use an SSL socket, and it
    overrides the :meth:`starttls()` function to throw an error (you can't do 
    starttls within an SSL session)"""
    certfile = None
    keyfile = None

    def __init__(self,
                 host='',
                 port=0,
                 local_hostname=None,
                 keyfile=None,
                 certfile=None):
        """Initialize a new SSL SMTP object.
        
        If specified, *host* is the name of the remote host to which this object
        will connect. If specified, *port* specifies the port (on `host') to
        which this object will connect. *local_hostname* is the name of the
        localhost. By default, the value of socket.getfqdn() is used.
        
        An SMTPConnectError is raised if the SMTP host does not respond 
        correctly.
        
        An SMTPSSLError is raised if SSL negotiation fails
        
        .. warning:: This object uses socket.ssl(), which does not do client-side
                     verification of the server's cert"""
        self.certfile = certfile
        self.keyfile = keyfile
        smtplib.SMTP.__init__(self, host, port, local_hostname)

    def connect(self, host='localhost', port=0):
        """Connect to an SMTP server using SSL.
        
        'host' is localhost by default. Port will be set to 465 (the default
        SSL SMTP port) if no port is specified.
        
        If the host name ends with a colon (':') followed by a number, 
        that suffix will be stripped off and the
        number interpreted as the port number to use. This will override the 
        'port' parameter.
        
        .. note:: this method is automatically invoked by __init__, if a host is
                  specified during the instantiation"""
        # MB: Most of this (Except for the socket connection code) is from
        # the SMTP.connect() method. I changed only the bare minimum for the
        # sake of compatibility.
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i + 1:]
                try:
                    port = int(port)
                except ValueError:
                    raise socket.error, "nonnumeric port"
        if not port: port = SSMTP_PORT
        if self.debuglevel > 0: print >> stderr, 'connect:', (host, port)
        msg = "getaddrinfo returns an empty list"
        self.sock = None
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                if self.debuglevel > 0:
                    print >> stderr, 'connect:', (host, port)
                self.sock.connect(sa)
                # MB: Make the SSL connection.
                sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
            except socket.error, msg:
                if self.debuglevel > 0:
                    print >> stderr, 'connect fail:', (host, port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg

        # MB: Now set up fake socket and fake file classes.
        # Thanks to the design of smtplib, this is all we need to do
        # to get SSL working with all other methods.
        self.sock = smtplib.SSLFakeSocket(self.sock, sslobj)
        self.file = smtplib.SSLFakeFile(sslobj)

        (code, msg) = self.getreply()
        if self.debuglevel > 0: print >> stderr, "connect:", msg
        return (code, msg)