Example #1
0
    def __init__(self,
                 host,
                 port=None,
                 key_file=None,
                 cert_file=None,
                 strict=None,
                 context=None,
                 source_address=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                 check_hostname=False,
                 **kw):

        HTTPConnection.__init__(self,
                                host,
                                port,
                                timeout=timeout,
                                source_address=source_address,
                                **kw)

        self.key_file = key_file
        self.cert_file = cert_file

        if context is None:
            context = ssl._create_stdlib_context()
        self._context = context
        self._check_hostname = check_hostname

        self.is_verified = False
Example #2
0
def ftp_connect(host, port, connection_type, ftp_user, ftp_pwd):

    if connection_type == "tls-implicit":
        ftp = ImplicitFTP_TLS()
        ftp.connect(host=host, port=port, timeout=40)
        ftp.login(user=ftp_user, passwd=ftp_pwd)
        ftp.prot_p()
        return ftp

    elif connection_type == "tls-explicit":
        ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1)
        ftp = ftplib.FTP_TLS(context=ctx)
        ftp.connect(host=host, port=port, timeout=40)
        ftp.login(user=ftp_user, passwd=ftp_pwd)
        ftp.prot_p()
        return ftp

    elif connection_type == "passive":
        ftp = ftplib.FTP()
        ftp.connect(host=host, port=port, timeout=40)
        ftp.login(user=ftp_user, passwd=ftp_pwd)
        ftp.set_pasv(True)
        return ftp

    else:
        ftp = ftplib.FTP()
        ftp.connect(host=host, port=port, timeout=40)
        ftp.login(user=ftp_user, passwd=ftp_pwd)
        ftp.set_pasv(False)
        return ftp
    def __init__(self, url, username=None, password=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        super().__init__(url, username, password, timeout)

        # Setting ssl key verificationas false
        context = ssl._create_stdlib_context(check_hostname=False)
        unverified_handler = HTTPSHandler(context=context, check_hostname=False)
        install_opener(build_opener(unverified_handler))
Example #4
0
 def __init__(self,
              host='',
              port=IMAP4_SSL_PORT,
              keyfile=None,
              certfile=None,
              ssl_context=None):
     if ssl_context is not None and keyfile is not None:
         raise ValueError(
             'ssl_context and keyfile arguments are mutually exclusive')
     if ssl_context is not None and certfile is not None:
         raise ValueError(
             'ssl_context and certfile arguments are mutually exclusive'
         )
     if keyfile is not None or certfile is not None:
         import warnings
         warnings.warn(
             'keyfile and certfile are deprecated, use acustom ssl_context instead',
             DeprecationWarning, 2)
     self.keyfile = keyfile
     self.certfile = certfile
     if ssl_context is None:
         ssl_context = ssl._create_stdlib_context(certfile=certfile,
                                                  keyfile=keyfile)
     self.ssl_context = ssl_context
     IMAP4.__init__(self, host, port)
Example #5
0
 def __init__(
     self,
     host,
     port=None,
     key_file=None,
     cert_file=None,
     timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
     source_address=None,
     *,
     context=None,
     check_hostname=None
 ):
     super(HTTPSConnection, self).__init__(host, port, timeout, source_address)
     self.key_file = key_file
     self.cert_file = cert_file
     if context is None:
         context = ssl._create_stdlib_context()
     will_verify = context.verify_mode != ssl.CERT_NONE
     if check_hostname is None:
         check_hostname = will_verify
     elif check_hostname and not will_verify:
         raise ValueError("check_hostname needs a SSL context with " "either CERT_OPTIONAL or CERT_REQUIRED")
     if key_file or cert_file:
         context.load_cert_chain(cert_file, key_file)
     self._context = context
     self._check_hostname = check_hostname
Example #6
0
    def test_https(self, url):
        parsed = urlparse(url)
        protocol = parsed[0]
        hostname = parsed[1]
        path = parsed[2]
        sslerror = False

        conn = http.client.HTTPSConnection(
            hostname, context=ssl.create_default_context())
        try:
            conn.request('GET', '/')
            res = conn.getresponse()
        except socket.gaierror:
            return {'supported': False, 'certvalid': False}
        except ssl.CertificateError:
            return {'supported': True, 'certvalid': False}
        except:
            sslerror = True

        # if tls connection fails for unexcepted error, retry without verifying cert
        if sslerror:
            conn = http.client.HTTPSConnection(
                hostname, timeout=5, context=ssl._create_stdlib_context())
            try:
                conn.request('GET', '/')
                res = conn.getresponse()
                return {'supported': True, 'certvalid': False}
            except:
                return {'supported': False, 'certvalid': False}

        return {'supported': True, 'certvalid': True}
Example #7
0
 def request(url, headers={}, method=None):
     if method:
         if sys.version_info.major >= 3:
             req = Request(url, headers=headers, method=method)
         else:
             req = Request(url, headers=headers)
             req.get_method = lambda: method
     else:
         req = Request(url, headers=headers)
     if hasattr(ssl, '_create_unverified_context'):
         context = ssl._create_unverified_context()
     elif hasattr(ssl, '_create_stdlib_context'):
         context = ssl._create_stdlib_context()
     elif hasattr(ssl, 'SSLContext'):
         context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
     else:
         context = None
     if context:
         res = urlopen(req, context=context)
     else:
         res = urlopen(req)
     if not hasattr(res, 'getheader'):
         # urllib2 does not have getheader
         res.getheader = lambda name, self=res: self.info().getheader(name)
     return res
def multipleCtxReinitializationsWithFinalBadSetting():
    import ssl
    ctx = ssl._create_unverified_context()
    ctx.verify_mode = ssl.CERT_REQUIRED  # Compliant (S4830)

    ctx = ssl._create_stdlib_context()
    ctx.verify_mode = ssl.CERT_NONE  # Noncompliant {{Enable server certificate validation on this SSL/TLS connection.}}
Example #9
0
        def __init__(
            self,
            host="",
            user="",
            passwd="",
            acct="",
            keyfile=None,
            certfile=None,
            context=None,
            timeout=_GLOBAL_DEFAULT_TIMEOUT,
            source_address=None,
        ):
            if context is not None and keyfile is not None:
                raise ValueError("context and keyfile arguments are mutually " "exclusive")
            if context is not None and certfile is not None:
                raise ValueError("context and certfile arguments are mutually " "exclusive")
            if keyfile is not None or certfile is not None:
                import warnings

                warnings.warn(
                    "keyfile and certfile are deprecated, use a" "custom context instead", DeprecationWarning, 2
                )
            self.keyfile = keyfile
            self.certfile = certfile
            if context is None:
                context = ssl._create_stdlib_context(self.ssl_version, certfile=certfile, keyfile=keyfile)
            self.context = context
            self._prot_p = False
            FTP.__init__(self, host, user, passwd, acct, timeout, source_address)
Example #10
0
 def __init__(self,
              host,
              port=POP3_SSL_PORT,
              keyfile=None,
              certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
              context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     if keyfile is not None or certfile is not None:
         import warnings
         warnings.warn(
             "keyfile and certfile are deprecated, use a "
             "custom context instead", DeprecationWarning, 2)
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     POP3.__init__(self, host, port, timeout)
Example #11
0
def starttls(con, ssl_context=None):
    """Python3's imaplib starttls port for Python2."""
    name = 'STARTTLS'
    if getattr(con, '_tls_established', False):
        raise con.abort('TLS session already established')
    if name not in con.capabilities:
        raise con.abort('TLS not supported by server')
    # Generate a default SSL context if none was passed.
    if ssl_context is None:
        ssl_context = ssl._create_stdlib_context()
    tag = con._new_tag()
    _send(con, '%s %s' % (tag, name))
    token = None
    while token != tag:
        token, resp, text = _recv(con)
    if resp == 'OK':
        con.sock = ssl_context.wrap_socket(con.sock, server_hostname=con.host)
        con.file = con.sock.makefile('rb')
        con._tls_established = True
        # update capabilities
        typ, dat = con.capability()
        if dat == [None]:
            raise con.error('no CAPABILITY response from server')
        con.capabilities = tuple(dat[-1].upper().split())
    else:
        raise con.error("Couldn't establish TLS session")
Example #12
0
def script_setup(parser):
    args = parser.parse_args()

    if any(getattr(args, name)!= parser.get_default(name)
            for name in ('protocol', 'domain', 'version')) and args.url:
        parser.error('--url can not be used with '
                     '--protocol, --domain or --version')

    logging.basicConfig(level=args.log_level)

    if args.unsafe_certs:
        ssl_context = ssl._create_stdlib_context()
    else:
        ssl_context = None

    if args.url:
        session = Session(None,
                          url_template=args.url,
                          ssl_context=ssl_context)
    else:
        session = Session(protocol=args.protocol,
                          domain=args.domain,
                          api_version=args.version,
                          ssl_context=ssl_context)

    return args, session
    def connect(self):
        log.debug('In SecureWebSocketClient.connect()')

        import ssl
        import socket
        from .tunnel import tunnel

        if self.use_ssl:
            self.login_url = "https://{host}:{port}/login".format(host=self.host, port=self.port)
            self.version_url = "https://{host}:{port}/version".format(host=self.host, port=self.port)
            self.ssl_options = {'ca_certs': self._ca_file}
            context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED, cafile=self._ca_file)
            self.https_handler = urllib.request.HTTPSHandler(context=context, check_hostname=False)
        else:
            self.login_url = "http://{host}:{port}/login".format(host=self.host, port=self.port)
            self.version_url = "http://{host}:{port}/version".format(host=self.host, port=self.port)
            self.ssl_options = {}
            self.https_handler = urllib.request.HTTPHandler()

        self.cookie_processor = urllib.request.HTTPCookieProcessor()
        self.opener = urllib.request.build_opener(self.https_handler, self.cookie_processor)

        self.check_server_version()
        data = urllib.parse.urlencode({'name': self._auth_user, 'password': self._auth_password}).encode('utf-8')
        f = self.opener.open(self.login_url, data, socket._GLOBAL_DEFAULT_TIMEOUT)
        log.debug('login result: {}'.format(f.read()))

        self._connect()
        log.debug(self.sock)

        self._tunnel = tunnel.Tunnel(self.host, 22, username='******', client_key=self._ssh_pkey)
        log.debug('tunnel status: {}'.format(self._tunnel.is_connected()))
Example #14
0
 def __init__(self,
              host='',
              user='',
              passwd='',
              acct='',
              keyfile=None,
              certfile=None,
              context=None,
              timeout=_GLOBAL_DEFAULT_TIMEOUT,
              source_address=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     if keyfile is not None or certfile is not None:
         import warnings
         warnings.warn(
             "keyfile and certfile are deprecated, use a"
             "custom context instead", DeprecationWarning, 2)
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(self.ssl_version,
                                              certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     self._prot_p = False
     FTP.__init__(self, host, user, passwd, acct, timeout,
                  source_address)
Example #15
0
def script_setup(parser):
    args = parser.parse_args()

    if any(
            getattr(args, name) != parser.get_default(name)
            for name in ('protocol', 'domain', 'version')) and args.url:
        parser.error('--url can not be used with '
                     '--protocol, --domain or --version')

    logging.basicConfig(level=args.log_level)

    if args.unsafe_certs:
        ssl_context = ssl._create_stdlib_context()
    else:
        ssl_context = None

    if args.url:
        session = Session(None, url_template=args.url, ssl_context=ssl_context)
    else:
        session = Session(protocol=args.protocol,
                          domain=args.domain,
                          api_version=args.version,
                          ssl_context=ssl_context)

    return args, session
Example #16
0
 def __init__(self,
              host,
              port=None,
              key_file=None,
              cert_file=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
              source_address=None,
              *,
              context=None,
              check_hostname=None):
     super(HTTPSConnection, self).__init__(host, port, timeout,
                                           source_address)
     self.key_file = key_file
     self.cert_file = cert_file
     if context is None:
         context = ssl._create_stdlib_context()
     will_verify = context.verify_mode != ssl.CERT_NONE
     if check_hostname is None:
         check_hostname = will_verify
     elif check_hostname and not will_verify:
         raise ValueError("check_hostname needs a SSL context with "
                          "either CERT_OPTIONAL or CERT_REQUIRED")
     if key_file or cert_file:
         context.load_cert_chain(cert_file, key_file)
     self._context = context
     self._check_hostname = check_hostname
Example #17
0
 def __init__(self,
              host='',
              user='',
              passwd='',
              acct='',
              keyfile=None,
              certfile=None,
              context=None,
              timeout=_GLOBAL_DEFAULT_TIMEOUT,
              source_address=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(self.ssl_version,
                                              certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     self._prot_p = False
     FTP.__init__(self, host, user, passwd, acct, timeout)
Example #18
0
    def __init__(self,
                 loop,
                 rawsock,
                 protocol,
                 sslcontext,
                 waiter=None,
                 server_side=False,
                 server_hostname=None,
                 extra=None,
                 server=None):
        if ssl is None:
            raise RuntimeError('stdlib ssl module not available')

        if server_side:
            if not sslcontext:
                raise ValueError('Server side ssl needs a valid SSLContext')
        else:
            if not sslcontext:
                # Client side may pass ssl=True to use a default
                # context; in that case the sslcontext passed is None.
                # The default is the same as used by urllib with
                # cadefault=True.
                if hasattr(ssl, '_create_stdlib_context'):
                    sslcontext = ssl._create_stdlib_context(
                        cert_reqs=ssl.CERT_REQUIRED,
                        check_hostname=bool(server_hostname))
                else:
                    # Fallback for Python 3.3.
                    sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                    sslcontext.options |= ssl.OP_NO_SSLv2
                    sslcontext.set_default_verify_paths()
                    sslcontext.verify_mode = ssl.CERT_REQUIRED

        wrap_kwargs = {
            'server_side': server_side,
            'do_handshake_on_connect': False,
        }
        if server_hostname and not server_side and ssl.HAS_SNI:
            wrap_kwargs['server_hostname'] = server_hostname
        sslsock = sslcontext.wrap_socket(rawsock, **wrap_kwargs)

        super().__init__(loop, sslsock, protocol, extra, server)

        self._server_hostname = server_hostname
        self._waiter = waiter
        self._rawsock = rawsock
        self._sslcontext = sslcontext
        self._paused = False

        # SSL-specific extra info.  (peercert is set later)
        self._extra.update(sslcontext=sslcontext)

        if self._loop.get_debug():
            logger.debug("%r starts SSL handshake", self)
            start_time = self._loop.time()
        else:
            start_time = None
        self._on_handshake(start_time)
Example #19
0
 def test_insecure_context(self):
     context = ssl._create_stdlib_context()
     session = Session('test', ssl_context=context)
     self.server.add(url='/login',
                     params='method=GET',
                     response='{"data": "foo"}',
                     ssl_context=context)
     compare(session.get('/login'), expected='foo')
     self.server.assert_called(times=1)
Example #20
0
 def __init__(self, port, host='', keyfile=None,
              certfile=None, ssl_context=None):
     self.keyfile = keyfile
     self.certfile = certfile
     if ssl_context is None:
         ssl_context = ssl._create_stdlib_context(certfile=certfile,
                                                  keyfile=keyfile)
     self.ssl_context = ssl_context
     IMAP4.__init__(self, host, port)
Example #21
0
    def starttls(self, keyfile=None, certfile=None, context=None):
        """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.

        This method may raise the following exceptions:

         SMTPHeloError            The server didn't reply properly to
                                  the helo greeting.
        """
        self.ehlo_or_helo_if_needed()
        if not self.has_extn("starttls"):
            raise SMTPNotSupportedError(
                "STARTTLS extension not supported by server.")
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            if not _have_ssl:
                raise RuntimeError("No SSL support included in this Python")
            if context is not None and keyfile is not None:
                raise ValueError("context and keyfile arguments are mutually "
                                 "exclusive")
            if context is not None and certfile is not None:
                raise ValueError("context and certfile arguments are mutually "
                                 "exclusive")
            if keyfile is not None or certfile is not None:
                import warnings
                warnings.warn(
                    "keyfile and certfile are deprecated, use a"
                    "custom context instead", DeprecationWarning, 2)
            if context is None:
                context = ssl._create_stdlib_context(certfile=certfile,
                                                     keyfile=keyfile)
            self.sock = context.wrap_socket(self.sock,
                                            server_hostname=self._host)
            self.file = None
            # 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
        else:
            # RFC 3207:
            # 501 Syntax error (no parameters allowed)
            # 454 TLS not available due to temporary reason
            raise SMTPResponseException(resp, reply)
        return (resp, reply)
Example #22
0
    def __init__(
        self,
        loop,
        rawsock,
        protocol,
        sslcontext,
        waiter=None,
        server_side=False,
        server_hostname=None,
        extra=None,
        server=None,
    ):
        if ssl is None:
            raise RuntimeError("stdlib ssl module not available")

        if server_side:
            if not sslcontext:
                raise ValueError("Server side ssl needs a valid SSLContext")
        else:
            if not sslcontext:
                # Client side may pass ssl=True to use a default
                # context; in that case the sslcontext passed is None.
                # The default is the same as used by urllib with
                # cadefault=True.
                if hasattr(ssl, "_create_stdlib_context"):
                    sslcontext = ssl._create_stdlib_context(
                        cert_reqs=ssl.CERT_REQUIRED, check_hostname=bool(server_hostname)
                    )
                else:
                    # Fallback for Python 3.3.
                    sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                    sslcontext.options |= ssl.OP_NO_SSLv2
                    sslcontext.set_default_verify_paths()
                    sslcontext.verify_mode = ssl.CERT_REQUIRED

        wrap_kwargs = {"server_side": server_side, "do_handshake_on_connect": False}
        if server_hostname and not server_side and ssl.HAS_SNI:
            wrap_kwargs["server_hostname"] = server_hostname
        sslsock = sslcontext.wrap_socket(rawsock, **wrap_kwargs)

        super().__init__(loop, sslsock, protocol, extra, server)

        self._server_hostname = server_hostname
        self._waiter = waiter
        self._sslcontext = sslcontext
        self._paused = False

        # SSL-specific extra info.  (peercert is set later)
        self._extra.update(sslcontext=sslcontext)

        if self._loop.get_debug():
            logger.debug("%r starts SSL handshake", self)
            start_time = self._loop.time()
        else:
            start_time = None
        self._on_handshake(start_time)
Example #23
0
 def _encrypt_on(sock, context, hostname):
     """Wrap a socket in SSL/TLS. Arguments:
     - sock: Socket to wrap
     - context: SSL context to use for the encrypted connection
     Returns:
     - sock: New, encrypted socket.
     """
     if context is None:
         context = ssl._create_stdlib_context()
     return context.wrap_socket(sock, server_hostname=hostname)
Example #24
0
def callWebService(pURL,pSOAPEnvelope,pMethod,pSOAPAction):
    encoded_request = pSOAPEnvelope.encode('utf-8')
    headers={"Content-Type":"text/xml; charset=UTF-8","Content-Length":len(encoded_request),"SOAPAction":pSOAPAction}
    request = uc.Request(pURL,encoded_request,headers)
    context = ssl._create_stdlib_context()
    response = uc.urlopen(request,context=context)
    data = response.read()
    #print (data)
    response.close()
    return data.decode()
Example #25
0
    def starttls(self, keyfile=None, certfile=None, context=None):
        """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.

        This method may raise the following exceptions:

         SMTPHeloError            The server didn't reply properly to
                                  the helo greeting.
        """
        self.ehlo_or_helo_if_needed()
        if not self.has_extn("starttls"):
            raise SMTPNotSupportedError(
                "STARTTLS extension not supported by server.")
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            if not _have_ssl:
                raise RuntimeError("No SSL support included in this Python")
            if context is not None and keyfile is not None:
                raise ValueError("context and keyfile arguments are mutually "
                                 "exclusive")
            if context is not None and certfile is not None:
                raise ValueError("context and certfile arguments are mutually "
                                 "exclusive")
            if keyfile is not None or certfile is not None:
                import warnings
                warnings.warn("keyfile and certfile are deprecated, use a "
                              "custom context instead", DeprecationWarning, 2)
            if context is None:
                context = ssl._create_stdlib_context(certfile=certfile,
                                                     keyfile=keyfile)
            self.sock = context.wrap_socket(self.sock,
                                            server_hostname=self._host)
            self.file = None
            # 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
        else:
            # RFC 3207:
            # 501 Syntax error (no parameters allowed)
            # 454 TLS not available due to temporary reason
            raise SMTPResponseException(resp, reply)
        return (resp, reply)
Example #26
0
 def test_insecure_context(self):
     context = ssl._create_stdlib_context()
     session = Session('test', ssl_context=context)
     self.server.add(
         url='/login',
         params='method=GET',
         response='{"data": "foo"}',
         ssl_context=context
     )
     compare(session.get('/login'), expected='foo')
     self.server.assert_called(times=1)
Example #27
0
 def _encrypt_on(sock, context):
     """Wrap a socket in SSL/TLS. Arguments:
     - sock: Socket to wrap
     - context: SSL context to use for the encrypted connection
     Returns:
     - sock: New, encrypted socket.
     """
     # Generate a default SSL context if none was passed.
     if context is None:
         context = ssl._create_stdlib_context()
     return context.wrap_socket(sock)
Example #28
0
 def _encrypt_on(sock, context, hostname):
     """Wrap a socket in SSL/TLS. Arguments:
     - sock: Socket to wrap
     - context: SSL context to use for the encrypted connection
     Returns:
     - sock: New, encrypted socket.
     """
     # Generate a default SSL context if none was passed.
     if context is None:
         context = ssl._create_stdlib_context()
     return context.wrap_socket(sock, server_hostname=hostname)
Example #29
0
 def __init__(self, host,
              ssl=True,
              port=None,
              timeout=_GLOBAL_DEFAULT_TIMEOUT):
     if port is None:
         port = POP3PORTSSL if ssl else POP3PORT
     self.sock = create_connection((host, port), timeout)
     if ssl:
         self.sock = _create_stdlib_context().wrap_socket(self.sock)
     self.read_sock = self.sock.makefile('rb')
     self.first_message = self.get_answer()
 def test_networked_noverification(self):
     # Switch off cert verification
     import ssl
     test_support.requires('network')
     with test_support.transient_internet('self-signed.pythontest.net'):
         context = ssl._create_stdlib_context()
         h = httplib.HTTPSConnection('self-signed.pythontest.net', 443,
                                     context=context)
         h.request('GET', '/')
         resp = h.getresponse()
         self.assertIn('nginx', resp.getheader('server'))
Example #31
0
def smtp_connect():
    global file_smtp, sock_smtp, sock_smtp_ssl
    #SMTP Verification

    ssl_context = ssl._create_stdlib_context(certfile=None, keyfile=None)

    sock_smtp = socket.create_connection(("smtp.gmail.com", 465),
                                         socket._GLOBAL_DEFAULT_TIMEOUT, None)
    sock_smtp_ssl = ssl_context.wrap_socket(sock_smtp,
                                            server_hostname="smtp.gmail.com")
    file_smtp = sock_smtp_ssl.makefile('rb')
    rcode, rstatus = message_smtp()
Example #32
0
 def _encrypt_on(sock, context, hostname):
     """Wrap a socket in SSL/TLS. Arguments:
     - sock: Socket to wrap
     - context: SSL context to use for the encrypted connection
     Returns:
     - sock: New, encrypted socket.
     """
     # Generate a default SSL context if none was passed.
     if context is None:
         context = ssl._create_stdlib_context()
     server_hostname = hostname if ssl.HAS_SNI else None
     return context.wrap_socket(sock, server_hostname=server_hostname)
Example #33
0
def imap_connect():
    global file_imap, sock_imap, sock_imap_ssl, pend_tag
    host = "imap.gmail.com"
    #port = 143
    port = 993
    ssl_context = ssl._create_stdlib_context(certfile=None, keyfile=None)
    pend_tag = {"a"}
    sock_imap = socket.create_connection((host, port))
    sock_imap_ssl = ssl_context.wrap_socket(sock_imap, server_hostname=host)
    #fileI = sockI.makefile('rb')
    file_imap = sock_imap_ssl.makefile('rb')
    print "reading"
Example #34
0
    def __init__(
        self,
        host: str = "",
        port: int = 993,
        keyfile=None,
        certfile=None,
        ssl_context=None,
        p_timeout: int = None,
        p_source_address: tuple = None,
        p_proxy_type: socks.PROXY_TYPES = socks.HTTP,
        p_proxy_addr: str = None,
        p_proxy_port: int = None,
        p_proxy_rdns=True,
        p_proxy_username: str = None,
        p_proxy_password: str = None,
        p_socket_options: iter = None,
    ):
        self._host = host
        self._port = port
        self._p_timeout = p_timeout
        self._p_source_address = p_source_address
        self._p_proxy_type = p_proxy_type
        self._p_proxy_addr = p_proxy_addr
        self._p_proxy_port = p_proxy_port
        self._p_proxy_rdns = p_proxy_rdns
        self._p_proxy_username = p_proxy_username
        self._p_proxy_password = p_proxy_password
        self._p_socket_options = p_socket_options

        if ssl_context is not None and keyfile is not None:
            raise ValueError(
                "ssl_context and keyfile arguments are mutually exclusive")
        if ssl_context is not None and certfile is not None:
            raise ValueError(
                "ssl_context and certfile arguments are mutually exclusive")
        if keyfile is not None or certfile is not None:
            import warnings
            warnings.warn(
                "keyfile and certfile are deprecated, use ssl_context instead",
                DeprecationWarning, 2)

        if ssl_context is None:
            ssl_context = ssl._create_stdlib_context(certfile=certfile,
                                                     keyfile=keyfile)  # noqa

        self.keyfile = keyfile
        self.certfile = certfile
        self.ssl_context = ssl_context

        super().__init__(host, port, p_timeout, p_source_address, p_proxy_type,
                         p_proxy_addr, p_proxy_port, p_proxy_rdns,
                         p_proxy_username, p_proxy_password, p_socket_options)
Example #35
0
def collect_ssl(info_add):
    import os
    try:
        import ssl
    except ImportError:
        return
    try:
        import _ssl
    except ImportError:
        _ssl = None

    def format_attr(attr, value):
        if attr.startswith('OP_'):
            return '%#8x' % value
        else:
            return value

    attributes = (
        'OPENSSL_VERSION',
        'OPENSSL_VERSION_INFO',
        'HAS_SNI',
        'OP_ALL',
        'OP_NO_TLSv1_1',
    )
    copy_attributes(info_add, ssl, 'ssl.%s', attributes, formatter=format_attr)

    for name, ctx in (
        ('SSLContext', ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)),
        ('default_https_context', ssl._create_default_https_context()),
        ('stdlib_context', ssl._create_stdlib_context()),
    ):
        attributes = (
            'minimum_version',
            'maximum_version',
            'protocol',
            'options',
            'verify_mode',
        )
        copy_attributes(info_add, ctx, f'ssl.{name}.%s', attributes)

    env_names = ["OPENSSL_CONF", "SSLKEYLOGFILE"]
    if _ssl is not None and hasattr(_ssl, 'get_default_verify_paths'):
        parts = _ssl.get_default_verify_paths()
        env_names.extend((parts[0], parts[2]))

    for name in env_names:
        try:
            value = os.environ[name]
        except KeyError:
            continue
        info_add('ssl.environ[%s]' % name, value)
Example #36
0
        def getcert(addr, timeout=None):
                """Retrieve server's certificate at the specified address (host, port)."""
                # it is similar to ssl.get_server_certificate() but it returns a dict
                # and it verifies ssl unconditionally, assuming create_default_context does
                context = ssl._create_stdlib_context()
                context.set_ciphers(("HIGH:-aNULL:-eNULL:-PSK:RC4-SHA:RC4-MD5"))
                context.verify_mode = ssl.CERT_REQUIRED
                context.load_verify_locations(CA_CERTS)

                sock = socket.create_connection(addr, timeout=timeout)
                sslsock = context.wrap_socket(sock, server_hostname=addr[0])
                cert = sslsock.getpeercert()
                sock.close()
                return cert
Example #37
0
    def getcert(addr, timeout=None):
        """Retrieve server's certificate at the specified address (host, port)."""
        # it is similar to ssl.get_server_certificate() but it returns a dict
        # and it verifies ssl unconditionally, assuming create_default_context does
        context = ssl._create_stdlib_context()
        context.set_ciphers(("HIGH:-aNULL:-eNULL:-PSK:RC4-SHA:RC4-MD5"))
        context.verify_mode = ssl.CERT_REQUIRED
        context.load_verify_locations(CA_CERTS)

        sock = socket.create_connection(addr, timeout=timeout)
        sslsock = context.wrap_socket(sock, server_hostname=addr[0])
        cert = sslsock.getpeercert()
        sock.close()
        return cert
Example #38
0
    def Create_SessionFTPS(self,
                           host,
                           account,
                           password,
                           Mode_PASV="true",
                           PORT=21):

        try:
            #save host,port
            self.port = PORT
            self.host = host

            #create context use TLS v1.2
            ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1_2)

            #open connection.
            self.ftp_session = ftplib.FTP_TLS(host, context=ctx)

            #for debug
            #self.ftp_session.set_debuglevel(2)

            #Login
            self.ftp_session.login(account, password)
            #ftp mode.
            self.ftp_session.set_pasv(Mode_PASV)
            #secure data connection.
            self.ftp_session.prot_p()

            return 0
        except ftplib.error_reply as e:
            #unexpected response.
            self.Output_Error(sys._getframe().f_code.co_name, e)
            return -1
        except ftplib.error_temp as e:
            #temporary error.(code 400--499)
            self.Output_Error(sys._getframe().f_code.co_name, e)
            return -1
        except ftplib.error_perm as e:
            #permanent error.(code 500--599)
            self.Output_Error(sys._getframe().f_code.co_name, e)
            return -1
        except ftplib.error_proto as e:
            #Unknown response code.
            self.Output_Error(sys._getframe().f_code.co_name, e)
            return -1
        except Exception as e:
            #Other error.
            self.Output_Error(sys._getframe().f_code.co_name, e)
            return -1
Example #39
0
    def starttls(self, keyfile=None, certfile=None, context=None):
        """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.

        This method may raise the following exceptions:

         SMTPHeloError            The server didn't reply properly to
                                  the helo greeting.
        """
        self.ehlo_or_helo_if_needed()
        if not self.has_extn('starttls'):
            raise SMTPNotSupportedError(
                'STARTTLS extension not supported by server.')
        resp, reply = self.docmd('STARTTLS')
        if resp == 220:
            if not _have_ssl:
                raise RuntimeError('No SSL support included in this Python')
            if context is not None and keyfile is not None:
                raise ValueError(
                    'context and keyfile arguments are mutually exclusive')
            if context is not None and certfile is not None:
                raise ValueError(
                    'context and certfile arguments are mutually exclusive')
            if keyfile is not None or certfile is not None:
                import warnings
                warnings.warn(
                    'keyfile and certfile are deprecated, use acustom context instead'
                    , DeprecationWarning, 2)
            if context is None:
                context = ssl._create_stdlib_context(certfile=certfile,
                    keyfile=keyfile)
            self.sock = context.wrap_socket(self.sock, server_hostname=self
                ._host)
            self.file = None
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        else:
            raise SMTPResponseException(resp, reply)
        return resp, reply
Example #40
0
 def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     POP3.__init__(self, host, port, timeout)
Example #41
0
 def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     POP3.__init__(self, host, port, timeout)
Example #42
0
    def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, context=None,
                  source_address=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, check_hostname=False,
                  **kw):

        HTTPConnection.__init__(self, host, port, timeout=timeout, source_address=source_address, **kw)

        self.key_file = key_file
        self.cert_file = cert_file

        if context is None:
            context = ssl._create_stdlib_context()
        self._context = context
        self._check_hostname = check_hostname

        self.is_verified = False
Example #43
0
 def stls(self, context=None):
     if not HAVE_SSL:
         raise ErrorProto('-ERR TLS support missing')
     if self._tls_established:
         raise ErrorProto('-ERR TLS session already established')
     caps = self.capa()
     if 'STLS' not in caps:
         raise ErrorProto('-ERR STLS not supported by server')
     if context is None:
         context = ssl._create_stdlib_context()
     resp = self._shortcmd('STLS')
     self.sock = context.wrap_socket(self.sock, server_hostname=self.host)
     self.file = self.sock.makefile('rb')
     self._tls_established = True
     return resp
Example #44
0
        def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None):
            if ssl_context is not None and keyfile is not None:
                raise ValueError("ssl_context and keyfile arguments are mutually "
                                 "exclusive")
            if ssl_context is not None and certfile is not None:
                raise ValueError("ssl_context and certfile arguments are mutually "
                                 "exclusive")

            self.keyfile = keyfile
            self.certfile = certfile
            if ssl_context is None:
                ssl_context = ssl._create_stdlib_context(certfile=certfile,
                                                         keyfile=keyfile)
            self.ssl_context = ssl_context
            IMAP4.__init__(self, host, port)
Example #45
0
def urlopen(url, data = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT,
            *, cafile = None, capath = None, cadefault = False):
    global _opener
    if cafile or capath or cadefault:
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl._create_stdlib_context(cert_regs = ssl.CRET_REQUIRED,
                                             cafile = cafile,
                                             capath = capath)
        https_handler = HTTPHandler(context = context, check_hostname = True)
        opener = buile_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout)
Example #46
0
    def test_ssl(self):
        def application(environ, start_response):
            status = "200 OK"
            headers = [("Content-type", "text/plain; charset=utf-8")]
            start_response(status, headers)
            return [b"hello ssl"]

        server_ssl_context = make_adhoc_ssl_context()
        client_ssl_context = ssl._create_stdlib_context()  # TODO

        with TestServer(application, ssl_context=server_ssl_context) as server:
            client = HTTPSConnection(server.host, server.port, context=client_ssl_context)

            client.request("GET", "/")
            resp = client.getresponse()
            self.assertEqual(resp.status, 200)
Example #47
0
    def __init__(self, loop, rawsock, protocol, sslcontext, waiter=None,
                 server_side=False, server_hostname=None,
                 extra=None, server=None):
        if ssl is None:
            raise RuntimeError('stdlib ssl module not available')

        if server_side:
            if not sslcontext:
                raise ValueError('Server side ssl needs a valid SSLContext')
        else:
            if not sslcontext:
                # Client side may pass ssl=True to use a default
                # context; in that case the sslcontext passed is None.
                # The default is the same as used by urllib with
                # cadefault=True.
                if hasattr(ssl, '_create_stdlib_context'):
                    sslcontext = ssl._create_stdlib_context(
                        cert_reqs=ssl.CERT_REQUIRED,
                        check_hostname=bool(server_hostname))
                else:
                    # Fallback for Python 3.3.
                    sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                    sslcontext.options |= ssl.OP_NO_SSLv2
                    sslcontext.set_default_verify_paths()
                    sslcontext.verify_mode = ssl.CERT_REQUIRED

        wrap_kwargs = {
            'server_side': server_side,
            'do_handshake_on_connect': False,
        }
        if server_hostname and not server_side and ssl.HAS_SNI:
            wrap_kwargs['server_hostname'] = server_hostname
        sslsock = sslcontext.wrap_socket(rawsock, **wrap_kwargs)

        super(_SelectorSslTransport, self).__init__(
            loop, sslsock, protocol, extra, server)

        self._server_hostname = server_hostname
        self._waiter = waiter
        self._rawsock = rawsock
        self._sslcontext = sslcontext
        self._paused = False

        # SSL-specific extra info.  (peercert is set later)
        self._extra.update(sslcontext=sslcontext)

        self._on_handshake()
Example #48
0
 def __init__(self, host='', port=0, local_hostname=None,
              keyfile=None, certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
              source_address=None, context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     SMTP.__init__(self, host, port, local_hostname, timeout,
             source_address)
Example #49
0
  def __init__(self, host='', port=SMTP_SSL_PORT, keyfile=None, certfile=None,
               ssl_context=None, proxy_addr=None, proxy_port=None, rdns=True,
               username=None, password=None, proxy_type="socks5"):

    if ssl_context is not None and keyfile is not None:
      raise ValueError("ssl_context and keyfile arguments are mutually exclusive")
    if ssl_context is not None and certfile is not None:
      raise ValueError("ssl_context and certfile arguments are mutually exclusive")

    self.keyfile = keyfile
    self.certfile = certfile
    if ssl_context is None:
      ssl_context = ssl._create_stdlib_context(certfile=certfile, keyfile=keyfile)

    self.ssl_context = ssl_context

    Socks_SMTP.__init__(self, host, port, proxy_addr=proxy_addr, proxy_port=proxy_port,
		        rdns=rdns, username=username, password=password, proxy_type=proxy_type)
Example #50
0
 def __init__(self, host='', port=0, local_hostname=None,
              keyfile=None, certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
              source_address=None, context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     SMTP.__init__(self, host, port, local_hostname, timeout,
             source_address)
Example #51
0
 def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
              certfile=None, context=None,
              timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(self.ssl_version,
                                              certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     self._prot_p = False
     FTP.__init__(self, host, user, passwd, acct, timeout, source_address)
Example #52
0
 def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None):
     if context is not None and keyfile is not None:
         raise ValueError("context and keyfile arguments are mutually "
                          "exclusive")
     if context is not None and certfile is not None:
         raise ValueError("context and certfile arguments are mutually "
                          "exclusive")
     if keyfile is not None or certfile is not None:
         import warnings
         warnings.warn("keyfile and certfile are deprecated, use a"
                       "custom context instead", DeprecationWarning, 2)
     self.keyfile = keyfile
     self.certfile = certfile
     if context is None:
         context = ssl._create_stdlib_context(certfile=certfile,
                                              keyfile=keyfile)
     self.context = context
     POP3.__init__(self, host, port, timeout)
Example #53
0
    def __init__(self, *args, **kwargs):
        try:
            keyfile         = kwargs.pop('keyfile')
            certfile        = kwargs.pop('certfile')
            SSL             = kwargs.pop('ssl')
            self.sslContext = kwargs.pop('sslContext')
        except KeyError:
            SSL = False
            self.sslContext = None

        self.loop = kwargs.get('loop') or asyncio.get_event_loop()
        self.sock = socket.socket(*args, **kwargs)
        self.sock.setblocking(False)

        if not SSL:
            return

        if self.sslContext is None:
            self.sslContext = ssl._create_stdlib_context(certfile = certfile, keyfile = keyfile)
Example #54
0
    def stls(self, context=None):
        """Start a TLS session on the active connection as specified in RFC 2595.

                context - a ssl.SSLContext
        """
        if not HAVE_SSL:
            raise error_proto('-ERR TLS support missing')
        if self._tls_established:
            raise error_proto('-ERR TLS session already established')
        caps = self.capa()
        if not 'STLS' in caps:
            raise error_proto('-ERR STLS not supported by server')
        if context is None:
            context = ssl._create_stdlib_context()
        resp = self._shortcmd('STLS')
        self.sock = context.wrap_socket(self.sock)
        self.file = self.sock.makefile('rb')
        self._tls_established = True
        return resp
Example #55
0
    def stls(self, context=None):
        """Start a TLS session on the active connection as specified in RFC 2595.

                context - a ssl.SSLContext
        """
        if not HAVE_SSL:
            raise error_proto("-ERR TLS support missing")
        if self._tls_established:
            raise error_proto("-ERR TLS session already established")
        caps = self.capa()
        if not "STLS" in caps:
            raise error_proto("-ERR STLS not supported by server")
        if context is None:
            context = ssl._create_stdlib_context()
        resp = self._shortcmd("STLS")
        server_hostname = self.host if ssl.HAS_SNI else None
        self.sock = context.wrap_socket(self.sock, server_hostname=server_hostname)
        self.file = self.sock.makefile("rb")
        self._tls_established = True
        return resp
Example #56
0
 def starttls(self, ssl_context=None):
     name = 'STARTTLS'
     if not HAVE_SSL:
         raise self.error('SSL support missing')
     if self._tls_established:
         raise self.abort('TLS session already established')
     if name not in self.capabilities:
         raise self.abort('TLS not supported by server')
     # Generate a default SSL context if none was passed.
     if ssl_context is None:
         ssl_context = ssl._create_stdlib_context()
     typ, dat = self._simple_command(name)
     if typ == 'OK':
         self.sock = ssl_context.wrap_socket(self.sock)
         self.file = self.sock.makefile('rb')
         self._tls_established = True
         self._get_capabilities()
     else:
         raise self.error("Couldn't establish TLS session")
     return self._untagged_response(typ, dat, name)
Example #57
0
 def create_connection(self):
     yield from self.loop.create_connection(lambda : self, self.host, self.port, ssl = ssl._create_stdlib_context())