示例#1
0
    def serverParamsTest (certfile, protocol, certreqs, cacertsfile,
                          client_certfile, client_protocol=None, indata="FOO\n",
                          chatty=True, connectionchatty=False,
                          wrap_accepting_socket=False):

        server = ThreadedEchoServer(certfile,
                                    certreqs=certreqs,
                                    ssl_version=protocol,
                                    cacerts=cacertsfile,
                                    chatty=chatty,
                                    connectionchatty=connectionchatty,
                                    wrap_accepting_socket=wrap_accepting_socket)
        flag = threading.Event()
        server.start(flag)
        # wait for it to start
        flag.wait()
        # try to connect
        if client_protocol is None:
            client_protocol = protocol
        try:
            try:
                s = ssl.wrap_socket(socket.socket(),
                                    certfile=client_certfile,
                                    ca_certs=cacertsfile,
                                    cert_reqs=certreqs,
                                    ssl_version=client_protocol)
                s.connect((HOST, server.port))
            except ssl.SSLError, x:
                raise test_support.TestFailed("Unexpected SSL error:  " + str(x))
            except Exception, x:
                raise test_support.TestFailed("Unexpected exception:  " + str(x))
示例#2
0
    def testFetchServerCert(self):

        pem = ssl.get_server_certificate(("svn.python.org", 443))
        if not pem:
            raise test_support.TestFailed(
                "No server certificate on svn.python.org:443!")

        try:
            pem = ssl.get_server_certificate(("svn.python.org", 443),
                                             ca_certs=CERTFILE)
        except ssl.SSLError:
            #should fail
            pass
        else:
            raise test_support.TestFailed(
                "Got server certificate %s for svn.python.org!" % pem)

        pem = ssl.get_server_certificate(("svn.python.org", 443),
                                         ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
        if not pem:
            raise test_support.TestFailed(
                "No server certificate on svn.python.org:443!")
        if test_support.verbose:
            sys.stdout.write(
                "\nVerified certificate for svn.python.org:443 is\n%s\n" % pem)
示例#3
0
def test_main(verbose=False):
    if skip_expected:
        raise test_support.TestSkipped("No SSL support")

    global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT
    CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
                            "keycert.pem")
    SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
        os.path.dirname(__file__) or os.curdir,
        "https_svn_python_org_root.pem")

    if (not os.path.exists(CERTFILE) or
        not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)):
        raise test_support.TestFailed("Can't read certificate files!")

    TESTPORT = test_support.find_unused_port()
    if not TESTPORT:
        raise test_support.TestFailed("Can't find open port to test servers on!")

    tests = [BasicTests]

    if test_support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        thread_info = test_support.threading_setup()
        if thread_info and test_support.is_resource_enabled('network'):
            tests.append(ThreadedTests)

    test_support.run_unittest(*tests)

    if _have_threads:
        test_support.threading_cleanup(*thread_info)
示例#4
0
    def testConnect(self):
        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                            cert_reqs=ssl.CERT_NONE)
        s.connect(("pop.gmail.com", 995))
        c = s.getpeercert()
        if c:
            raise test_support.TestFailed("Peer cert %s shouldn't be here!")
        s.close()

        # this should fail because we have no verification certs
        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                            cert_reqs=ssl.CERT_REQUIRED)
        try:
            try:
                s.connect(("pop.gmail.com", 995))
            except ssl.SSLError:
                pass
        finally:
            s.close()

        # this should succeed because we specify the root cert
        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
        try:
            try:
                s.connect(("svn.python.org", 443))
            except ssl.SSLError, x:
                raise test_support.TestFailed("Unexpected exception %s" % x)
        finally:
            s.close()
示例#5
0
        def testReadCert(self):

            if test_support.verbose:
                sys.stdout.write("\n")
            s2 = socket.socket()
            server = ThreadedEchoServer(TESTPORT,
                                        CERTFILE,
                                        certreqs=ssl.CERT_NONE,
                                        ssl_version=ssl.PROTOCOL_SSLv23,
                                        cacerts=CERTFILE,
                                        chatty=False)
            flag = threading.Event()
            server.start(flag)
            # wait for it to start
            flag.wait()
            # try to connect
            try:
                try:
                    s = ssl.wrap_socket(socket.socket(),
                                        certfile=CERTFILE,
                                        ca_certs=CERTFILE,
                                        cert_reqs=ssl.CERT_REQUIRED,
                                        ssl_version=ssl.PROTOCOL_SSLv23)
                    s.connect(('127.0.0.1', TESTPORT))
                except ssl.SSLError, x:
                    raise test_support.TestFailed("Unexpected SSL error:  " +
                                                  str(x))
                except Exception, x:
                    raise test_support.TestFailed("Unexpected exception:  " +
                                                  str(x))
示例#6
0
def test_main(verbose=False):
    if skip_expected:
        raise test_support.TestSkipped("No SSL support")

    global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT
    CERTFILE = os.path.join(
        os.path.dirname(__file__) or os.curdir, "keycert.pem")
    SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
        os.path.dirname(__file__) or os.curdir, "root.crt")

    if (not os.path.exists(CERTFILE)
            or not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)):
        raise test_support.TestFailed("Can't read certificate files!")

    TESTPORT = findtestsocket(10025, 12000)
    if not TESTPORT:
        raise test_support.TestFailed(
            "Can't find open port to test servers on!")

    tests = [BasicTests]

    if test_support.is_resource_enabled('network'):
        tests.append(NetworkedTests)

    if _have_threads:
        if CERTFILE and test_support.is_resource_enabled('network'):
            tests.append(ThreadedTests)

    test_support.run_unittest(*tests)
示例#7
0
 def _apply_failure(self, fn, filename, expected_exception,
                    check_fn_in_exception = True):
     try:
         fn(filename)
         raise test_support.TestFailed("Expected to fail calling '%s(%r)'"
                          % (fn.__name__, filename))
     except expected_exception, details:
         if check_fn_in_exception and details.filename != filename:
             raise test_support.TestFailed("Function '%s(%r) failed with "
                              "bad filename in the exception: %r"
                              % (fn.__name__, filename,
                                 details.filename))
示例#8
0
def raises(exc, expected, callable, *args):
    """Ensure the expected exception is raised"""
    try:
        callable(*args)
    except exc, msg:
        if expected is not None:
            if isinstance(expected, str):
                if str(msg) != expected:
                    raise test_support.TestFailed("Message %r, expected %r" %
                                                  (str(msg), expected))
            elif isinstance(expected, int):
                if msg.errno != expected:
                    raise test_support.TestFailed("errno %r, expected %r" %
                                                  (msg, expected))
示例#9
0
        def testSTARTTLS(self):

            msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4", "ENDTLS",
                    "msg 5", "msg 6")

            server = ThreadedEchoServer(TESTPORT,
                                        CERTFILE,
                                        ssl_version=ssl.PROTOCOL_TLSv1,
                                        starttls_server=True,
                                        chatty=True,
                                        connectionchatty=True)
            flag = threading.Event()
            server.start(flag)
            # wait for it to start
            flag.wait()
            # try to connect
            wrapped = False
            try:
                try:
                    s = socket.socket()
                    s.setblocking(1)
                    s.connect(('127.0.0.1', TESTPORT))
                except Exception, x:
                    raise test_support.TestFailed("Unexpected exception:  " +
                                                  str(x))
                else:
示例#10
0
def test_main():
    from test import test_doctest2
    EXPECTED = 19
    f, t = test_support.run_doctest(test_doctest2)
    if t != EXPECTED:
        raise test_support.TestFailed("expected %d tests to run, not %d" %
                                      (EXPECTED, t))
示例#11
0
    def tryProtocolCombo (server_protocol,
                          client_protocol,
                          expectedToWork,
                          certsreqs=None):

        if certsreqs is None:
            certsreqs = ssl.CERT_NONE

        if certsreqs == ssl.CERT_NONE:
            certtype = "CERT_NONE"
        elif certsreqs == ssl.CERT_OPTIONAL:
            certtype = "CERT_OPTIONAL"
        elif certsreqs == ssl.CERT_REQUIRED:
            certtype = "CERT_REQUIRED"
        if test_support.verbose:
            formatstr = (expectedToWork and " %s->%s %s\n") or " {%s->%s} %s\n"
            sys.stdout.write(formatstr %
                             (ssl.get_protocol_name(client_protocol),
                              ssl.get_protocol_name(server_protocol),
                              certtype))
        try:
            serverParamsTest(CERTFILE, server_protocol, certsreqs,
                             CERTFILE, CERTFILE, client_protocol, chatty=False)
        except test_support.TestFailed:
            if expectedToWork:
                raise
        else:
            if not expectedToWork:
                raise test_support.TestFailed(
                    "Client protocol %s succeeded with server protocol %s!"
                    % (ssl.get_protocol_name(client_protocol),
                       ssl.get_protocol_name(server_protocol)))
示例#12
0
 def testDERtoPEM(self):
     pem = open(SVN_PYTHON_ORG_ROOT_CERT, 'r').read()
     d1 = ssl.PEM_cert_to_DER_cert(pem)
     p2 = ssl.DER_cert_to_PEM_cert(d1)
     d2 = ssl.PEM_cert_to_DER_cert(p2)
     if (d1 != d2):
         raise test_support.TestFailed(
             "PEM-to-DER or DER-to-PEM translation failed")
示例#13
0
        def testAsyncoreServer (self):

            indata = "TEST MESSAGE of mixed case\n"

            if test_support.verbose:
                sys.stdout.write("\n")
            server = AsyncoreEchoServer(CERTFILE)
            flag = threading.Event()
            server.start(flag)
            # wait for it to start
            flag.wait()
            # try to connect
            try:
                try:
                    s = ssl.wrap_socket(socket.socket())
                    s.connect(('127.0.0.1', server.port))
                except ssl.SSLError, x:
                    raise test_support.TestFailed("Unexpected SSL error:  " + str(x))
                except Exception, x:
                    raise test_support.TestFailed("Unexpected exception:  " + str(x))
示例#14
0
 def connector():
     listener_ready.wait()
     s = socket.socket()
     s.connect((HOST, port))
     listener_gone.wait()
     try:
         ssl_sock = ssl.wrap_socket(s)
     except IOError:
         pass
     else:
         raise test_support.TestFailed(
               'connecting to closed SSL socket should have failed')
示例#15
0
 def connector():
     listener_ready.wait()
     s = socket.socket()
     s.connect(('localhost', PORT[0]))
     listener_gone.wait()
     try:
         ssl_sock = socket.ssl(s)
     except socket.sslerror:
         pass
     else:
         raise test_support.TestFailed(
             'connecting to closed SSL socket should have failed')
示例#16
0
 def connector():
     listener_ready.wait()
     s = socket.socket()
     s.connect(('127.0.0.1', TESTPORT))
     listener_gone.wait()
     try:
         ssl.wrap_socket(s)
     except socket.error:
         pass
     else:
         raise test_support.TestFailed(
             'connecting to closed SSL socket should have failed')
示例#17
0
def test_main():
    from test import test_doctest2
    if sys.flags.optimize >= 2:
        print >> sys.stderr, "test_doctest2 --",
        print >> sys.stderr, "skipping some tests due to -O flag."
        sys.stderr.flush()
        EXPECTED = 3
    else:
        EXPECTED = 19
    f, t = test_support.run_doctest(test_doctest2)
    if t != EXPECTED:
        raise test_support.TestFailed("expected %d tests to run, not %d" %
                                      (EXPECTED, t))
示例#18
0
def test_main():

    tests = [TestImaplib]

    if support.is_resource_enabled('network'):
        if ssl:
            global CERTFILE
            CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
                                    "keycert.pem")
            if not os.path.exists(CERTFILE):
                raise support.TestFailed("Can't read certificate files!")
        tests.extend([ThreadedNetworkedTests, ThreadedNetworkedTestsSSL])

    support.run_unittest(*tests)
示例#19
0
        def testSocketServer(self):

            server = SocketServerHTTPSServer(CERTFILE)
            flag = threading.Event()
            server.start(flag)
            # wait for it to start
            flag.wait()
            # try to connect
            try:
                if test_support.verbose:
                    sys.stdout.write('\n')
                d1 = open(CERTFILE, 'rb').read()
                d2 = ''
                # now fetch the same data from the HTTPS server
                url = 'https://127.0.0.1:%d/%s' % (
                    server.port, os.path.split(CERTFILE)[1])
                f = urllib.urlopen(url)
                dlen = f.info().getheader("content-length")
                if dlen and (int(dlen) > 0):
                    d2 = f.read(int(dlen))
                    if test_support.verbose:
                        sys.stdout.write(
                            " client: read %d bytes from remote server '%s'\n"
                            % (len(d2), server))
                f.close()
            except:
                msg = ''.join(traceback.format_exception(*sys.exc_info()))
                if test_support.verbose:
                    sys.stdout.write('\n' + msg)
                raise test_support.TestFailed(msg)
            else:
                if not (d1 == d2):
                    raise test_support.TestFailed(
                        "Couldn't fetch data from HTTPS server")
            finally:
                server.stop()
                server.join()
示例#20
0
def capture_events(callable, p=None):
    try:
        sys.setprofile()
    except TypeError:
        pass
    else:
        raise test_support.TestFailed(
            'sys.setprofile() did not raise TypeError')

    if p is None:
        p = HookWatcher()
    sys.setprofile(p.callback)
    protect(callable, p)
    sys.setprofile(None)
    return p.get_events()[1:-1]
示例#21
0
 def test_nameprep(self):
     from encodings.idna import nameprep
     for pos, (orig, prepped) in enumerate(nameprep_tests):
         if orig is None:
             # Skipped
             continue
         # The Unicode strings are given in UTF-8
         orig = unicode(orig, "utf-8")
         if prepped is None:
             # Input contains prohibited characters
             self.assertRaises(UnicodeError, nameprep, orig)
         else:
             prepped = unicode(prepped, "utf-8")
             try:
                 self.assertEquals(nameprep(orig), prepped)
             except Exception,e:
                 raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
示例#22
0
    def testSSLconnect(self):
        if not test_support.is_resource_enabled('network'):
            return
        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                            cert_reqs=ssl.CERT_NONE)
        s.connect(("svn.python.org", 443))
        c = s.getpeercert()
        if c:
            raise test_support.TestFailed("Peer cert %s shouldn't be here!")
        s.close()

        # this should fail because we have no verification certs
        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                            cert_reqs=ssl.CERT_REQUIRED)
        try:
            s.connect(("svn.python.org", 443))
        except ssl.SSLError:
            pass
        finally:
            s.close()
示例#23
0
def raises(exc, expected, callable, *args):
    """Ensure the specified call raises exc.

    expected is compared against the exception message if not None. It
    can be a str, an errno or a 2 item tuple of errno/filename. The
    latter two being for comparison against EnvironmentErrors.
    """
    if expected:
        if isinstance(expected, str):
            msg = expected
        else:
            errno = expected[0] if isinstance(expected, tuple) else expected
            msg = '[Errno %d] %s' % (errno, os.strerror(errno))
            if isinstance(expected, tuple):
                msg += ': %r' % expected[1]
    try:
        callable(*args)
    except exc, val:
        if expected and str(val) != msg:
            raise test_support.TestFailed("Message %r, expected %r" %
                                          (str(val), msg))
示例#24
0
    """Ensure the expected exception is raised"""
    try:
        callable(*args)
    except exc, msg:
        if expected is not None:
            if isinstance(expected, str):
                if str(msg) != expected:
                    raise test_support.TestFailed("Message %r, expected %r" %
                                                  (str(msg), expected))
            elif isinstance(expected, int):
                if msg.errno != expected:
                    raise test_support.TestFailed("errno %r, expected %r" %
                                                  (msg, expected))

    else:
        raise test_support.TestFailed("Expected %s" % exc)


def read(filename):
    """Read data from filename"""
    fp = open(filename)
    data = fp.read()
    fp.close()
    return data


def write(filename, data):
    """Write data to filename"""
    fp = open(filename, 'wb')
    fp.write(data)
    fp.close()
示例#25
0
        flag = threading.Event()
        server.start(flag)
        # wait for it to start
        flag.wait()
        # try to connect
        try:
            try:
                s = ssl.wrap_socket(socket.socket(),
                                    certfile=certfile,
                                    ssl_version=ssl.PROTOCOL_TLSv1)
                s.connect(('127.0.0.1', TESTPORT))
            except ssl.SSLError, x:
                if test_support.verbose:
                    sys.stdout.write("\nSSLError is %s\n" % x[1])
            else:
                raise test_support.TestFailed(
                    "Use of invalid cert should have failed!")
        finally:
            server.stop()
            server.join()

    def serverParamsTest(certfile,
                         protocol,
                         certreqs,
                         cacertsfile,
                         client_certfile,
                         client_protocol=None,
                         indata="FOO\n",
                         chatty=True,
                         connectionchatty=False,
                         wrap_accepting_socket=False):