Exemplo n.º 1
0
    def __init__(self,
                 privateKeyFileName,
                 certificateFileName,
                 sslmethod=SSLv23_METHOD,
                 certificateChainFile=None,
                 keychainIdentity=None,
                 passwdCallback=None,
                 ciphers=None,
                 verifyClient=False,
                 requireClientCertificate=False,
                 verifyClientOnce=True,
                 verifyClientDepth=9,
                 clientCACertFileNames=[],
                 sendCAsToClient=True):
        self.certificateChainFile = certificateChainFile
        self.keychainIdentity = keychainIdentity
        self.passwdCallback = passwdCallback
        self.ciphers = ciphers

        self.verifyClient = verifyClient
        self.requireClientCertificate = requireClientCertificate
        self.verifyClientOnce = verifyClientOnce
        self.verifyClientDepth = verifyClientDepth
        self.clientCACertFileNames = clientCACertFileNames
        self.sendCAsToClient = sendCAsToClient

        DefaultOpenSSLContextFactory.__init__(self,
                                              privateKeyFileName,
                                              certificateFileName,
                                              sslmethod=sslmethod)
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
      self.chain = None
      if kwargs.has_key("certificateChainFile"):
        self.chain = kwargs["certificateChainFile"]
        del kwargs["certificateChainFile"]

      DefaultOpenSSLContextFactory.__init__(self, *args, **kwargs)
Exemplo n.º 3
0
 def start(self):
     interface = WebServerConfig.local_ip
     port = WebServerConfig.local_port
     cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None
     cert_chain_path = WebServerConfig.certificate_chain.normalized if WebServerConfig.certificate_chain else None
     if cert_path is not None:
         if not os.path.isfile(cert_path):
             log.error('Certificate file %s could not be found' % cert_path)
             return
         try:
             ssl_ctx_factory = DefaultOpenSSLContextFactory(cert_path, cert_path)
         except Exception:
             log.exception('Creating TLS context')
             log.err()
             return
         if cert_chain_path is not None:
             if not os.path.isfile(cert_chain_path):
                 log.error('Certificate chain file %s could not be found' % cert_chain_path)
                 return
             ssl_ctx = ssl_ctx_factory.getContext()
             try:
                 ssl_ctx.use_certificate_chain_file(cert_chain_path)
             except Exception:
                 log.exception('Setting TLS certificate chain file')
                 log.err()
                 return
         self.listener = reactor.listenSSL(port, self.site, ssl_ctx_factory, backlog=511, interface=interface)
         scheme = 'https'
     else:
         self.listener = reactor.listenTCP(port, self.site, backlog=511, interface=interface)
         scheme = 'http'
     port = self.listener.getHost().port
     self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname or interface.normalized, port)
     log.msg('Web server listening for requests on: %s' % self.url)
Exemplo n.º 4
0
    def cacheContext(self):
        DefaultOpenSSLContextFactory.cacheContext(self)

        # Call a callback if defined to check certificate authentificity.
        if self.verifyCallback[0]:
            self._context.set_verify(VERIFY_PEER, self.verifyCertificate)

        if self.certificateChainFile != None:
            self._context.use_certificate_chain_file(self.certificateChainFile)
Exemplo n.º 5
0
    def __init__(self, privateKeyFileName, certificateFileName,
             sslmethod=SSLv23_METHOD, certificateChainFile=None,
             verifyCallback=None):
        self.privateKeyFileName = privateKeyFileName
        self.certificateFileName = certificateFileName
        self.certificateChainFile = certificateChainFile
        self.verifyCallback       = (verifyCallback, )

        DefaultOpenSSLContextFactory.__init__(self,
                privateKeyFileName,
                certificateFileName,
                sslmethod=sslmethod)
Exemplo n.º 6
0
        def __init__(self, opts, verifyCallback=defaultVerifyCallback):
            if not 'key' in opts or not 'cert' in opts:
                raise ValueError("Cannot create ssl context without key and certificate files")

            DefaultOpenSSLContextFactory.__init__(self, 
                                                  os.path.expanduser(opts["key"]), 
                                                  os.path.expanduser(opts["cert"]))
            ctx = self.getContext()
            if 'verify' in opts and to_bool(opts['verify']):
                ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                               verifyCallback)
            if 'ca' in opts:
                ctx.load_verify_locations(os.path.expanduser(opts["ca"]))
Exemplo n.º 7
0
 def rehash(self):
     oldContext = self.certContext
     try:
         self.certContext = DefaultOpenSSLContextFactory(
             self.ircd.config["starttls_key"],
             self.ircd.config["starttls_cert"])
         self.certContext.getContext().set_verify(
             SSL.VERIFY_PEER,
             lambda connection, x509, errnum, errdepth, ok: True)
     except SSL.Error:
         self.ircd.log.error(
             "Failed to initialize new SSL context for StartTLS; keeping old context"
         )
         self.certContext = oldContext
Exemplo n.º 8
0
    def __init__(
        self, privateKeyFileName, certificateFileName,
        sslmethod=SSLv3_METHOD, certificateChainFile=None,
        passwdCallback=None, ciphers=None
    ):
        self.certificateChainFile = certificateChainFile
        self.passwdCallback = passwdCallback
        self.ciphers = ciphers

        DefaultOpenSSLContextFactory.__init__(
            self,
            privateKeyFileName,
            certificateFileName,
            sslmethod=sslmethod
        )
Exemplo n.º 9
0
 def load(self):
     if "unloading-tls" in self.ircd.dataCache:
         del self.ircd.dataCache["unloading-tls"]
         return
     if "cap-add" in self.ircd.functionCache:
         self.ircd.functionCache["cap-add"]("tls")
     try:
         self.certContext = DefaultOpenSSLContextFactory(
             self.ircd.config["starttls_key"],
             self.ircd.config["starttls_cert"])
         self.certContext.getContext().set_verify(
             SSL.VERIFY_PEER,
             lambda connection, x509, errnum, errdepth, ok: True)
     except SSL.Error:
         raise ModuleLoadError("StartTLS",
                               "Failed to initialize SSL context")
Exemplo n.º 10
0
    def setUp(self):
        super(FlockerDeployTests, self).setUp()
        ca_set, _ = get_credential_sets()
        self.certificate_path = FilePath(self.mktemp())
        self.certificate_path.makedirs()
        ca_set.copy_to(self.certificate_path, user=True)

        self.persistence_service = ConfigurationPersistenceService(
            reactor, FilePath(self.mktemp()))
        self.persistence_service.startService()
        self.cluster_state_service = ClusterStateService(reactor)
        self.cluster_state_service.startService()
        self.cluster_state_service.apply_changes([
            NodeState(uuid=uuid4(), hostname=ip)
            for ip in COMPLEX_DEPLOYMENT_YAML[u"nodes"].keys()
        ])
        self.addCleanup(self.cluster_state_service.stopService)
        self.addCleanup(self.persistence_service.stopService)
        app = ConfigurationAPIUserV1(self.persistence_service,
                                     self.cluster_state_service).app
        api_root = Resource()
        api_root.putChild('v1', app.resource())
        # Simplest possible TLS context that presents correct control
        # service certificate; no need to validate flocker-deploy here.
        self.port = reactor.listenSSL(
            0,
            Site(api_root),
            DefaultOpenSSLContextFactory(
                ca_set.path.child(b"control-127.0.0.1.key").path,
                ca_set.path.child(b"control-127.0.0.1.crt").path),
            interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        self.port_number = self.port.getHost().port
Exemplo n.º 11
0
    def test_handshake(self):
        """
        The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
        connected to a transport.
        """
        clientFactory = ClientFactory()
        clientFactory.protocol = Protocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True,
                                             clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False,
                                             serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol,
                                           sslClientProtocol)

        # Only wait for the handshake to complete.  Anything after that isn't
        # important here.
        return handshakeDeferred
Exemplo n.º 12
0
def makeService(config):
    s = service.MultiService()
    if config['root']:
        root = config['root']
        if config['indexes']:
            config['root'].indexNames = config['indexes']
    else:
        # This really ought to be web.Admin or something
        root = demo.Test()

    if isinstance(root, static.File):
        root.registry.setComponent(interfaces.IServiceCollection, s)

    if config['logfile']:
        site = server.Site(root, logPath=config['logfile'])
    else:
        site = server.Site(root)

    site.displayTracebacks = not config["notracebacks"]

    if config['personal']:
        personal = strports.service(
            config['port'], makePersonalServerFactory(site))
        personal.setServiceParent(s)
    else:
        if config['https']:
            from twisted.internet.ssl import DefaultOpenSSLContextFactory
            i = internet.SSLServer(int(config['https']), site,
                          DefaultOpenSSLContextFactory(config['privkey'],
                                                       config['certificate']))
            i.setServiceParent(s)
        strports.service(config['port'], site).setServiceParent(s)

    return s
Exemplo n.º 13
0
def main(reactor):
    log.startLogging(sys.stdout)
    factory = WebSocketServerFactory()
    factory.protocol = OpenFaceServerProtocol
    ctx_factory = DefaultOpenSSLContextFactory(tls_key, tls_crt)
    reactor.listenSSL(args.port, factory, ctx_factory)
    return defer.Deferred()
Exemplo n.º 14
0
def main(reactor):
    log.startLogging(sys.stdout)
    factory = BroadcastServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = OpenFaceServerProtocol
    ctx_factory = DefaultOpenSSLContextFactory(tls_key, tls_crt)
    reactor.listenSSL(args.port, factory, ctx_factory)
    return defer.Deferred()
Exemplo n.º 15
0
def _toEndpoint(description, certificate=None):
    """
    Create an endpoint based on a description.

    @type description: L{bytes}
    @param description: An endpoint description string or a TCP port
        number.

    @type certificate: L{bytes} or L{None}
    @param certificate: The name of a file containing an SSL certificate.

    @rtype: L{IStreamServerEndpoint
        <twisted.internet.interfaces.IStreamServerEndpoint>} provider
    @return: An endpoint.
    """
    from twisted.internet import reactor
    try:
        port = int(description)
    except ValueError:
        return endpoints.serverFromString(reactor, description)

    warnings.warn(
        "Specifying plain ports and/or a certificate is deprecated since "
        "Twisted 11.0; use endpoint descriptions instead.",
        category=DeprecationWarning,
        stacklevel=3)

    if certificate:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        ctx = DefaultOpenSSLContextFactory(certificate, certificate)
        return endpoints.SSL4ServerEndpoint(reactor, port, ctx)
    return endpoints.TCP4ServerEndpoint(reactor, port)
Exemplo n.º 16
0
    def test_ssl_verification_negative(self):
        """
        If the SSL server provides a key which is not verified by the
        specified public key, then the client should immediately end
        the connection without uploading any message data.
        """
        self.log_helper.ignore_errors(PyCurlError)
        r = DataCollectingResource()
        context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY)
        port = reactor.listenSSL(0,
                                 server.Site(r),
                                 context_factory,
                                 interface="127.0.0.1")
        self.ports.append(port)
        transport = HTTPTransport(None,
                                  "https://localhost:%d/" %
                                  (port.getHost().port, ),
                                  pubkey=PUBKEY)

        result = deferToThread(transport.exchange,
                               "HI",
                               computer_id="34",
                               message_api="X.Y")

        def got_result(ignored):
            self.assertIs(r.request, None)
            self.assertIs(r.content, None)
            self.assertTrue("server certificate verification failed" in
                            self.logfile.getvalue())

        result.addErrback(got_result)
        return result
Exemplo n.º 17
0
    def __init__(self, port, key, crt, ssl_method):
        """
        @param port: port to listen
        @type port: int

        @param key: private key filename
        @type key: str

        @param crt: certificate filename
        @type crt: str

        @param ssl_method: SSL method
        @type: str
        """
        self.port = port
        if ssl_method == "TLSv1_METHOD":
            from OpenSSL.SSL import TLSv1_METHOD
            ssl_method = TLSv1_METHOD
        elif ssl_method == "SSLv23_METHOD":
            from OpenSSL.SSL import SSLv23_METHOD
            ssl_method = SSLv23_METHOD
        elif ssl_method == "SSLv2_METHOD":
            from OpenSSL.SSL import SSLv2_METHOD
            ssl_method = SSLv2_METHOD
        elif ssl_method == "SSLv3_METHOD":
            from OpenSSL.SSL import SSLv3_METHOD
            ssl_method = SSLv3_METHOD
        else:
            raise TypeError

        self.ctx_factory = DefaultOpenSSLContextFactory(key, crt, ssl_method)
Exemplo n.º 18
0
def makeService(config):
    if config['logfile']:
        logObserver = log.FileAccessLoggingObserver(config['logfile'])
    else:
        logObserver = log.DefaultCommonAccessLoggingObserver()

    if config['root']:
        if config['indexes']:
            config['root'].indexNames = config['indexes']

        root = log.LogWrapperResource(config['root'])

    s = Web2Service(logObserver)

    site = server.Site(root)
    chan = channel.HTTPFactory(site)

    if config['https']:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        i = internet.SSLServer(
            int(config['https']), chan,
            DefaultOpenSSLContextFactory(config['privkey'],
                                         config['certificate']))
        i.setServiceParent(s)

    strports.service(config['port'], chan).setServiceParent(s)

    return s
Exemplo n.º 19
0
	def rehash(self):
		oldContext = self.certContext
		try:
			self.certContext = DefaultOpenSSLContextFactory(self.ircd.config["starttls_key"], self.ircd.config["starttls_cert"])
			self.certContext.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True)
		except SSL.Error:
			self.ircd.log.error("Failed to initialize new SSL context for StartTLS; keeping old context")
			self.certContext = oldContext
Exemplo n.º 20
0
 def start(self):
     interface = WebServerConfig.local_ip
     port = WebServerConfig.local_port
     cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None
     cert_chain_path = WebServerConfig.certificate_chain.normalized if WebServerConfig.certificate_chain else None
     if cert_path is not None:
         if not os.path.isfile(cert_path):
             log.error('Certificate file %s could not be found' % cert_path)
             return
         try:
             ssl_ctx_factory = DefaultOpenSSLContextFactory(
                 cert_path, cert_path)
         except Exception:
             log.exception('Creating TLS context')
             return
         if cert_chain_path is not None:
             if not os.path.isfile(cert_chain_path):
                 log.error('Certificate chain file %s could not be found' %
                           cert_chain_path)
                 return
             ssl_ctx = ssl_ctx_factory.getContext()
             try:
                 ssl_ctx.use_certificate_chain_file(cert_chain_path)
             except Exception:
                 log.exception('Setting TLS certificate chain file')
                 return
         self.listener = reactor.listenSSL(port,
                                           self.site,
                                           ssl_ctx_factory,
                                           backlog=511,
                                           interface=interface)
         scheme = 'https'
     else:
         self.listener = reactor.listenTCP(port,
                                           self.site,
                                           backlog=511,
                                           interface=interface)
         scheme = 'http'
     port = self.listener.getHost().port
     self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname
                                            or interface.normalized, port)
     log.info('Web server listening for requests on: %s' % self.url)
Exemplo n.º 21
0
	def load(self):
		if "unloading-tls" in self.ircd.dataCache:
			del self.ircd.dataCache["unloading-tls"]
			return
		if "cap-add" in self.ircd.functionCache:
			self.ircd.functionCache["cap-add"]("tls")
		try:
			self.certContext = DefaultOpenSSLContextFactory(self.ircd.config["starttls_key"], self.ircd.config["starttls_cert"])
			self.certContext.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True)
		except SSL.Error:
			raise ModuleLoadError("StartTLS", "Failed to initialize SSL context")
Exemplo n.º 22
0
Arquivo: demon.py Projeto: Ri0n/Hermes
def init():
    if int(config()['daemon'].get("ssl", 0)):
        reactor.listenSSL(int(config()['daemon']['port']),
                          HermesSite(),
                          DefaultOpenSSLContextFactory(
                              config()['ssl']['private'],
                              config()['ssl']['cert']),
                          interface=config()['daemon'].get("if", "127.0.0.1"))
    else:
        reactor.listenTCP(int(config()['daemon']['port']),
                          HermesSite(),
                          interface=config()['daemon'].get("if", "127.0.0.1"))
Exemplo n.º 23
0
 def _listen(self, site):
     if self.scheme == "http":
         return reactor.listenTCP(0, site, interface="127.0.0.1")
     elif self.scheme == "https":
         sslFactory = DefaultOpenSSLContextFactory(data_file("server.key"),
                                                   data_file("server.crt"))
         return reactor.listenSSL(0,
                                  site,
                                  sslFactory,
                                  interface="127.0.0.1")
     else:
         self.fail("unknown scheme: %s" % self.scheme)
Exemplo n.º 24
0
    def test_loseConnectionAfterHandshake(self):
        """
        L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and
        shuts down the underlying connection.
        """
        clientConnectionLost = Deferred()
        clientFactory = ClientFactory()
        clientFactory.protocol = (
            lambda: ConnectionLostNotifyingProtocol(clientConnectionLost))

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True,
                                             clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = Protocol()
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False,
                                             serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol,
                                           sslClientProtocol)

        # Wait for the handshake before dropping the connection.
        def cbHandshake(ignored):
            serverProtocol.transport.loseConnection()

            # Now wait for the client to notice.
            return clientConnectionLost

        handshakeDeferred.addCallback(cbHandshake)

        # Wait for the connection to end, then make sure the client was
        # notified of a handshake failure.
        def cbConnectionDone(clientProtocol):
            clientProtocol.lostConnectionReason.trap(ConnectionDone)

            # The server should have closed its underlying transport, in
            # addition to whatever it did to shut down the TLS layer.
            self.assertTrue(serverProtocol.transport.q.disconnect)

            # The client should also have closed its underlying transport once
            # it saw the server shut down the TLS layer, so as to avoid relying
            # on the server to close the underlying connection.
            self.assertTrue(clientProtocol.transport.q.disconnect)

        handshakeDeferred.addCallback(cbConnectionDone)
        return handshakeDeferred
Exemplo n.º 25
0
def addWebServer(cfg, dist, sched):
    """Set up a web server.
         cfg -- a configuration object from Main.  We use these options:
                HTTPS_N_BRIDGES_PER_ANSWER
                HTTP_UNENCRYPTED_PORT
                HTTP_UNENCRYPTED_BIND_IP
                HTTP_USE_IP_FROM_FORWARDED_HEADER
                HTTPS_PORT
                HTTPS_BIND_IP
                HTTPS_USE_IP_FROM_FORWARDED_HEADER
                RECAPTCHA_ENABLED
                RECAPTCHA_PUB_KEY
                RECAPTCHA_PRIV_KEY 
         dist -- an IPBasedDistributor object.
         sched -- an IntervalSchedule object.
    """
    site = None
    httpdist = twisted.web.resource.Resource()
    httpdist.putChild('', WebRoot())
    httpdist.putChild('assets', static.File(os.path.join(template_root, 'assets/')))

    resource = WebResource(dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER,
                   cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
                   includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS,
                   domains=cfg.EMAIL_DOMAINS)

    if cfg.RECAPTCHA_ENABLED:
        protected = CaptchaProtectedResource(
                recaptchaPrivKey=cfg.RECAPTCHA_PRIV_KEY,
                recaptchaPubKey=cfg.RECAPTCHA_PUB_KEY,
                useForwardedHeader=cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
                resource=resource)
        httpdist.putChild('bridges', protected)
    else:
        httpdist.putChild('bridges', resource)
        
    site = Site(httpdist)

    if cfg.HTTP_UNENCRYPTED_PORT:
        ip = cfg.HTTP_UNENCRYPTED_BIND_IP or ""
        reactor.listenTCP(cfg.HTTP_UNENCRYPTED_PORT, site, interface=ip)

    if cfg.HTTPS_PORT:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        #from OpenSSL.SSL import SSLv3_METHOD
        ip = cfg.HTTPS_BIND_IP or ""
        factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE,
                                               cfg.HTTPS_CERT_FILE)
        reactor.listenSSL(cfg.HTTPS_PORT, site, factory, interface=ip)

    return site
Exemplo n.º 26
0
def addWebServer(cfg, dist, sched):
    """Set up a web server.
         cfg -- a configuration object from Main.  We use these options:
                HTTPS_N_BRIDGES_PER_ANSWER
                HTTP_UNENCRYPTED_PORT
                HTTP_UNENCRYPTED_BIND_IP
                HTTP_USE_IP_FROM_FORWARDED_HEADER
                HTTPS_PORT
                HTTPS_BIND_IP
                HTTPS_USE_IP_FROM_FORWARDED_HEADER
                RECAPTCHA_ENABLED
                RECAPTCHA_PUB_KEY
                RECAPTCHA_PRIV_KEY 
         dist -- an IPBasedDistributor object.
         sched -- an IntervalSchedule object.
    """
    Site = twisted.web.server.Site
    site = None
    if cfg.HTTP_UNENCRYPTED_PORT:
        ip = cfg.HTTP_UNENCRYPTED_BIND_IP or ""
        resource = WebResource(
            dist,
            sched,
            cfg.HTTPS_N_BRIDGES_PER_ANSWER,
            cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
            includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS,
            useRecaptcha=cfg.RECAPTCHA_ENABLED,
            domains=cfg.EMAIL_DOMAINS,
            recaptchaPrivKey=cfg.RECAPTCHA_PRIV_KEY,
            recaptchaPubKey=cfg.RECAPTCHA_PUB_KEY)
        site = Site(resource)
        reactor.listenTCP(cfg.HTTP_UNENCRYPTED_PORT, site, interface=ip)
    if cfg.HTTPS_PORT:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        #from OpenSSL.SSL import SSLv3_METHOD
        ip = cfg.HTTPS_BIND_IP or ""
        factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE,
                                               cfg.HTTPS_CERT_FILE)
        resource = WebResource(
            dist,
            sched,
            cfg.HTTPS_N_BRIDGES_PER_ANSWER,
            cfg.HTTPS_USE_IP_FROM_FORWARDED_HEADER,
            includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS,
            domains=cfg.EMAIL_DOMAINS,
            useRecaptcha=cfg.RECAPTCHA_ENABLED,
            recaptchaPrivKey=cfg.RECAPTCHA_PRIV_KEY,
            recaptchaPubKey=cfg.RECAPTCHA_PUB_KEY)
        site = Site(resource)
        reactor.listenSSL(cfg.HTTPS_PORT, site, factory, interface=ip)
    return site
Exemplo n.º 27
0
def main():
    log.startLogging(sys.stdout)

    # Start the daemon, to update the cache certificate fingerprints once a day
    forkUpdater(cachefile)
    # Start the Bounce Proxy Server
    reactor.listenTCP(6112, BounceFactory(None))
    # Start the Notary SSL server
    reactor.listenSSL(6113,
                      NotaryFactory(),
                      DefaultOpenSSLContextFactory("./testroot.key",
                                                   "./testroot.pem"),
                      backlog=15)

    reactor.run()
Exemplo n.º 28
0
    def test_ssl_verification_positive(self):
        """
        The L{VerifyingContextFactory} properly allows to connect to the
        endpoint if the certificates match.
        """
        context_factory = DefaultOpenSSLContextFactory(PRIVKEY, PUBKEY)
        self.port = reactor.listenSSL(0,
                                      self.site,
                                      context_factory,
                                      interface="127.0.0.1")
        self.portno = self.port.getHost().port

        endpoint = AWSServiceEndpoint(ssl_hostname_verification=True)
        query = BaseQuery("an action", "creds", endpoint)
        d = query.get_page(self._get_url("file"))
        return d.addCallback(self.assertEquals, "0123456789")
Exemplo n.º 29
0
    def _open_endpoint(self):
        try:
            if self.key is None or self.cert is None:
                endpoint = endpoints.TCP4ServerEndpoint(reactor, self.port)
            else:
                # Enforce TLSv1_2_METHOD
                ctx = DefaultOpenSSLContextFactory(self.key, self.cert,
                                                   TLSv1_2_METHOD)
                endpoint = SSL4ServerEndpoint(reactor, self.port, ctx)

            self.site = Site(self.app.resource())
            self.tcp_port = yield endpoint.listen(self.site)
            log.info('web-server-started', port=self.port)
            self.endpoint = endpoint
        except Exception as e:
            self.log.exception('web-server-failed-to-start', e=e)
Exemplo n.º 30
0
def connect(logger):
    '''Connect the Siri server to handle iPhone requests.

    * logger -- The logger

    '''
    # Grab the configured port for the iPhone
    port = Options.get(Sections.iPhone, Ids.Port)

    # Create the SSL context using the iPhone key and certificate files
    keyFile = Options.get(Sections.iPhone, Ids.KeyFile)
    certFile = Options.get(Sections.iPhone, Ids.CertFile)
    authentication = DefaultOpenSSLContextFactory(keyFile, certFile)

    # Create the SSL server using the given authentication files
    reactor.listenSSL(port, _Factory(logger), authentication)
Exemplo n.º 31
0
    def test_ssl_verification_negative(self):
        """
        The L{VerifyingContextFactory} fails with a SSL error the certificates
        can't be checked.
        """
        context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY)
        self.port = reactor.listenSSL(0,
                                      self.site,
                                      context_factory,
                                      interface="127.0.0.1")
        self.portno = self.port.getHost().port

        endpoint = AWSServiceEndpoint(ssl_hostname_verification=True)
        query = BaseQuery("an action", "creds", endpoint)
        d = query.get_page(self._get_url("file"))
        return self.assertFailure(d, SSLError)
Exemplo n.º 32
0
    def test_ssl_subject_alt_name(self):
        """
        L{VerifyingContextFactory} supports checking C{subjectAltName} in the
        certificate if it's available.
        """
        context_factory = DefaultOpenSSLContextFactory(PRIVSANKEY, PUBSANKEY)
        self.port = reactor.listenSSL(0,
                                      self.site,
                                      context_factory,
                                      interface="127.0.0.1")
        self.portno = self.port.getHost().port

        endpoint = AWSServiceEndpoint(ssl_hostname_verification=True)
        query = BaseQuery("an action", "creds", endpoint)
        d = query.get_page("https://127.0.0.1:%d/file" % (self.portno, ))
        return d.addCallback(self.assertEquals, "0123456789")
Exemplo n.º 33
0
    def lineReceived(self, line):
        log.msg("Received line %s" % line)
        try:
            d = loads(line)
            # Required names.
            host = d["daddr"]
            dport = d["dport"]
            password = d["password"]
            # Optional names.
            sport = d.get("sport")
            ws = d.get("ws", False)
            tls = d.get("tls", False)
            client_opts = d.get("client", {})

            # Allocate the source port.
            sport = self.factory.allocate_port(sport)

            factory = VNCProxy(host, dport, password, client_opts)

            if ws:
                factory = WebSocketFactory(factory)
            if tls:
                context = DefaultOpenSSLContextFactory("keys/vncap.key",
                                                       "keys/vncap.crt")
                listening = reactor.listenSSL(sport, factory, context)
            else:
                listening = reactor.listenTCP(sport, factory)

            # Set up our timeout.
            def timeout():
                log.msg("Timed out connection on port %d" % sport)
                listening.stopListening()
                self.factory.free_port(sport)
            reactor.callLater(30, timeout)

            log.msg("New forwarder (%d->%s:%d)" % (sport, host, dport))
            self.sendLine("%d" % sport)
        except (KeyError, ValueError):
            log.msg("Couldn't handle line %s" % line)
            self.sendLine("FAILED")
        except CannotListenError:
            # Couldn't bind the port. Don't free it, as it's probably not
            # available to us.
            log.msg("Couldn't bind port %d" % sport)
            self.sendLine("FAILED")

        self.transport.loseConnection()
Exemplo n.º 34
0
    def test_writeAfterHandshake(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
        complete are received by the protocol on the other side of the
        connection once the handshake succeeds.
        """
        bytes = "some bytes"

        clientProtocol = Protocol()
        clientFactory = ClientFactory()
        clientFactory.protocol = lambda: clientProtocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True,
                                             clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False,
                                             serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol,
                                           sslClientProtocol)

        # Wait for the handshake to finish before writing anything.
        def cbHandshook(ignored):
            clientProtocol.transport.write(bytes)

            # The server will drop the connection once it gets the bytes.
            return connectionDeferred

        handshakeDeferred.addCallback(cbHandshook)

        # Once the connection is lost, make sure the server received the
        # expected bytes.
        def cbDisconnected(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)

        handshakeDeferred.addCallback(cbDisconnected)

        return handshakeDeferred
Exemplo n.º 35
0
def listen(url, site):
    global _defaultUser
    data = urlparse.urlparse(url, "http", False)
    if data.scheme == "https":
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        query = urlparse.parse_qs(data.query)
        reactor.listenSSL(int(data.port or 443),
                          site,
                          DefaultOpenSSLContextFactory(query["private"][0],
                                                       query["cert"][0]),
                          interface=data.hostname or "127.0.0.1")
    else:
        reactor.listenTCP(int(data.port or 80),
                          site,
                          interface=data.hostname or "127.0.0.1")
    if data.username and data.password:
        _defaultUser = user.User(data.username, data.password, "Default User")
Exemplo n.º 36
0
    def test_ssl_verification_bypassed(self):
        """
        L{BaseQuery} doesn't use L{VerifyingContextFactory}
        if C{ssl_hostname_verification} is C{False}, thus allowing to connect
        to non-secure endpoints.
        """
        context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY)
        self.port = reactor.listenSSL(0,
                                      self.site,
                                      context_factory,
                                      interface="127.0.0.1")
        self.portno = self.port.getHost().port

        endpoint = AWSServiceEndpoint(ssl_hostname_verification=False)
        query = BaseQuery("an action", "creds", endpoint)
        d = query.get_page(self._get_url("file"))
        return d.addCallback(self.assertEquals, "0123456789")
Exemplo n.º 37
0
def makeService(config):
    s = service.MultiService()
    if config['root']:
        root = config['root']
        if config['indexes']:
            config['root'].indexNames = config['indexes']
    else:
        # This really ought to be web.Admin or something
        root = demo.Test()

    if isinstance(root, static.File):
        root.registry.setComponent(interfaces.IServiceCollection, s)

    if config['logfile']:
        site = server.Site(root, logPath=config['logfile'])
    else:
        site = server.Site(root)

    site.displayTracebacks = not config["notracebacks"]

    if config['personal']:
        import pwd, os

        pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                 = pwd.getpwuid(os.getuid())
        i = internet.UNIXServer(
            os.path.join(pw_dir, distrib.UserDirectory.userSocketName),
            pb.BrokerFactory(distrib.ResourcePublisher(site)))
        i.setServiceParent(s)
    else:
        if config['https']:
            from twisted.internet.ssl import DefaultOpenSSLContextFactory
            i = internet.SSLServer(
                int(config['https']), site,
                DefaultOpenSSLContextFactory(config['privkey'],
                                             config['certificate']))
            i.setServiceParent(s)
        strports.service(config['port'], site).setServiceParent(s)

    flashport = config.get('flashconduit', None)
    if flashport:
        from twisted.web.woven.flashconduit import FlashConduitFactory
        i = internet.TCPServer(int(flashport), FlashConduitFactory(site))
        i.setServiceParent(s)
    return s
Exemplo n.º 38
0
 def getContext(self, hostname=None, port=None):
     return DefaultOpenSSLContextFactory.getContext(self)
Exemplo n.º 39
0
class StartTLS(ModuleData, Command):
	implements(IPlugin, IModuleData, ICommand)
	
	name = "StartTLS"
	forRegistered = False
	
	def actions(self):
		return [ ("capabilitylist", 10, self.addCapability) ]
	
	def userCommands(self):
		return [ ("STARTTLS", 1, self) ]
	
	def load(self):
		if "unloading-tls" in self.ircd.dataCache:
			del self.ircd.dataCache["unloading-tls"]
			return
		if "cap-add" in self.ircd.functionCache:
			self.ircd.functionCache["cap-add"]("tls")
		try:
			self.certContext = DefaultOpenSSLContextFactory(self.ircd.config["starttls_key"], self.ircd.config["starttls_cert"])
			self.certContext.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True)
		except SSL.Error:
			raise ModuleLoadError("StartTLS", "Failed to initialize SSL context")
	
	def rehash(self):
		oldContext = self.certContext
		try:
			self.certContext = DefaultOpenSSLContextFactory(self.ircd.config["starttls_key"], self.ircd.config["starttls_cert"])
			self.certContext.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True)
		except SSL.Error:
			self.ircd.log.error("Failed to initialize new SSL context for StartTLS; keeping old context")
			self.certContext = oldContext
	
	def unload(self):
		self.ircd.dataCache["unloading-tls"] = True
	
	def fullUnload(self):
		del self.ircd.dataCache["unloading-tls"]
		if "cap-del" in self.ircd.functionCache:
			self.ircd.functionCache["cap-del"]("tls")
	
	def verifyConfig(self, config):
		if "starttls_key" in config:
			if not isinstance(config["starttls_key"], basestring):
				raise ConfigValidationError("starttls_key", "value must be a file name")
		else:
			config["starttls_key"] = "server.pem" # We'll use the Twisted default for endpoints here
		if "starttls_cert" in config:
			if not isinstance(config["starttls_cert"], basestring):
				raise ConfigValidationError("starttls_cert", "value must be a file name")
		else:
			config["starttls_cert"] = config["starttls_key"]
	
	def addCapability(self, user, capList):
		capList.append("tls")
	
	def parseParams(self, user, prefix, params, tags):
		return {}
	
	def execute(self, user, data):
		if user.secureConnection:
			user.sendMessage(irc.ERR_STARTTLS, "The connection is already secure")
			return True
		try:
			secureTransport = ITLSTransport(user.transport)
		except TypeError:
			user.sendMessage(irc.ERR_STARTTLS, "Failed to initialize transport for STARTTLS")
			return True
		if secureTransport is None:
			user.sendMessage(irc.ERR_STARTTLS, "Failed to initialize transport for STARTTLS")
			return True
		user.transport = secureTransport
		user.sendMessage(irc.RPL_STARTTLS, "STARTTLS successful; proceed with TLS handshake")
		secureTransport.startTLS(self.certContext)
		user.secureConnection = ISSLTransport(secureTransport, None) is not None
		return True
Exemplo n.º 40
0
 def getContext(self, host, port):
     return DefaultOpenSSLContextFactory.getContext(self)
Exemplo n.º 41
0
 def cacheContext(self):
     DefaultOpenSSLContextFactory.cacheContext(self)
     self._context.use_certificate_chain_file(self.certificateFileName)
Exemplo n.º 42
0
 def cacheContext(self):
   DefaultOpenSSLContextFactory.cacheContext(self)
   if self.chain:
     self._context.use_certificate_chain_file(self.chain)
     self._context.use_privatekey_file(self.privateKeyFileName)
Exemplo n.º 43
0
 def __init__(self, private_key, cert, curve_name=None, *args, **kwargs):
     DefaultOpenSSLContextFactory.__init__(self, private_key, cert, *args, **kwargs)
     self.set_curve(curve_name)