Nginx web ssl config
356001
def nginx_web_ssl_config(self):
        

        dt = [self.nginx_web_dir, self.nginx_ssl_dir]
        return nginx_conf_string.simple_ssl_web_conf.format(dt=dt)
83191
def get_config(self):
        
        self.create_ssl_certs()

        config = {
            "bootstrap_servers": self.get_brokers(),
            "security_protocol": 'SSL',
            "ssl_cafile": self.ssl["ca"]["file"].name,
            "ssl_certfile": self.ssl["cert"]["file"].name,
            "ssl_keyfile": self.ssl["key"]["file"].name,
            "ssl_check_hostname": False,
            "ssl_password": None
        }
        self.config.update(config)
853104
def write_nginx_config(self):
        
        log = logging.getLogger('ipsv.models.sites.site')
        if not os.path.exists(self.root):
            log.debug('Creating HTTP root directory: %s', self.root)
            os.makedirs(self.root, 0o755)

        # Generate our server block configuration
        server_block = ServerBlock(self)

        server_config_path = os.path.join(_cfg.get('Paths', 'NginxSitesAvailable'), self.domain.name)
        if not os.path.exists(server_config_path):
            log.debug('Creating new configuration path: %s', server_config_path)
            os.makedirs(server_config_path, 0o755)

        server_config_path = os.path.join(server_config_path, '{fn}.conf'.format(fn=self.slug))
        if os.path.exists(server_config_path):
            log.info('Server block configuration file already exists, overwriting: %s', server_config_path)
            os.remove(server_config_path)

        log.info('Writing Nginx server block configuration file')
        with open(server_config_path, 'w') as f:
            f.write(server_block.template)
219209
function installConfiguration()
    {
        info('Installing nginx configuration...');

        $contents = $this->files->get(__DIR__.'/../stubs/nginx.conf');

        $this->files->putAsUser(
            static::NGINX_CONF,
            str_replace(['VALET_USER', 'VALET_HOME_PATH'], [user(), VALET_HOME_PATH], $contents)
        );
    }
98348
def start_tls(req, options)
      return unless req.uri.https? && !failed_proxy_connect?

      ssl_context = options.ssl_context

      unless ssl_context
        ssl_context = OpenSSL::SSL::SSLContext.new
        ssl_context.set_params(options.ssl || {})
      end

      @socket.start_tls(req.uri.host, options.ssl_socket_class, ssl_context)
    end
1275961
def get_certificate
      uri = URI.parse(URI.escape(@host))
      options = { use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE }
      Net::HTTP.start(uri.host, uri.port, options) do |http|
        http.peer_cert
      end
    end
353433
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = (
    options.cache === undefined ? 3600 :
    // -1 is a special case to turn off caching.
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Preventing_caching
    options.cache === -1 ? 'no-cache, no-store, must-revalidate' :
    options.cache // in seconds.
  );
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.showDotfiles = options.showDotfiles;
  this.gzip = options.gzip === true;
  this.brotli = options.brotli === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.username || options.password) {
    before.push(function (req, res) {
      var credentials = auth(req);

      // We perform these outside the if to avoid short-circuiting and giving
      // an attacker knowledge of whether the username is correct via a timing
      // attack.
      if (credentials) {
        var usernameEqual = secureCompare(options.username, credentials.name);
        var passwordEqual = secureCompare(options.password, credentials.pass);
        if (usernameEqual && passwordEqual) {
          return res.emit('next');
        }
      }

      res.statusCode = 401;
      res.setHeader('WWW-Authenticate', 'Basic realm=""');
      res.end('Access denied');
    });
  }

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    showDotfiles: this.showDotfiles,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    brotli: this.brotli,
    contentType: this.contentType,
    handleError: typeof options.proxy !== 'string'
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      }, function (err, req, res, target) {
        if (options.logFn) {
          options.logFn(req, res, {
            message: err.message,
            status: res.statusCode });
        }
        res.emit('next');
      });
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
273167
def ssl?
      @env[Merb::Const::UPCASE_HTTPS] == 'on' || @env[Merb::Const::HTTP_X_FORWARDED_PROTO] == Merb::Const::HTTPS
    end
540538
def setup()
      send_bridge_request
      code = nil
			name = nil
			headers = []
			while (line = gets())
				line = line.strip
				if (line == "")
					case code.to_i
					when 100 # 100 Continue, just a ping. Ignore.
						code = name = nil
						headers = []
						next
					when 101 # 101 Upgrade, successfuly got a connection.
						write("HTTP/1.1 100 Continue\r\n\r\n") # let the server know we're still here.
						return self
					when 401 # 401 Access Denied, key wasn't right.
					  close()
					  raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required."
					when 503, 504 # 503 Service Unavailable or 504 Gateway Timeout, just retry.
						close()
						sleep_time = headers.find {|header| header["Retry-After"] } || 5
						raise RetryError.new("BRIDGE server timed out or is overloaded, wait #{sleep_time}s to try again.", sleep_time)
					else
						raise "HTTP BRIDGE error #{code}: #{name} waiting for connection."
					end
				end
		
				if (!code && !name) # This is the initial response line
					if (match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$}))
						code = match[1]
						name = match[2]
						next
					else
						raise "Parse error in BRIDGE request reply."
					end
				else
					if (match = line.match(%r{^(.+?):\s+(.+)$}))
						headers.push({match[1] => match[2]})
					else
						raise "Parse error in BRIDGE request reply's headers."
					end
				end
			end
			return nil
		end
597287
def autoconf(self):
        
        nginxInfo = NginxInfo(self._host, self._port,
                                self._user, self._password, 
                                self._statuspath, self._ssl)
        return nginxInfo is not None
473093
private static void configureEngine(SSLEngine engine, FlowType type, SSLLinkConfig config, SSLConnectionLink connLink) {
        // Update the engine with the latest config parameters.
        engine.setEnabledCipherSuites(config.getEnabledCipherSuites(engine));

        //Set the configured protocol on the SSLEngine
        String protocol = config.getSSLProtocol();
        if (protocol != null) {
            engine.setEnabledProtocols(new String[] { protocol });
        }

        if (type == FlowType.INBOUND) {
            engine.setUseClientMode(false);
            boolean flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION);
            // When on z/OS, need to check the MutualAuthCBINDCheck property
            // to force client authentication
            //TODO: z/os
            //            if (PlatformHelperFactory.getPlatformHelper().isZOS() &&
            //            	 UserRegistryConfig.TYPE_LOCAL_OS.equals(SecurityObjectLocator.getSecurityConfig().getActiveUserRegistry().getType()))
            //            {
            //            	Boolean cbindCheckEnabled = Boolean.FALSE;
            //
            //            	//get the endpoint name off of the thread
            //                Map connectionInfo = JSSEHelper.getInstance().getInboundConnectionInfo();
            //                if (connectionInfo != null) {
            //                    String endpointName = (String) connectionInfo.get(Constants.CONNECTION_INFO_ENDPOINT_NAME);
            //                    //only enforce cbind check on web requests
            //                    if (endpointName != null && endpointName.startsWith("HTTP")) {
            //                    	if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //                            Tr.debug(tc, "The endpoint, " + endpointName + ", is web and we are on z/OS. Proceeding to get the mutualAuthCbindCheck property.");
            //                        }
            //		                try {
            //		                    // Get cbind check flag using reflection
            //		                    final String className = "com.ibm.ws.security.zOS.NativeConfiguration";
            //		                    final Class<?> zNativeConfigClass = Class.forName(className);
            //		                    final Method getConfigMethod = zNativeConfigClass.getMethod("getConfig", (java.lang.Class[]) null);
            //		                    final Object configInstance = getConfigMethod.invoke((java.lang.Class[]) null, (java.lang.Object[]) null);
            //		                    final Method cbindCheckMethod = zNativeConfigClass.getMethod("isMutualAuthCBINDCheckEnabled", (java.lang.Class[]) null);
            //		                    cbindCheckEnabled = (Boolean) cbindCheckMethod.invoke(configInstance, (java.lang.Object[]) null);
            //		                } catch (Exception e) {
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            //		                        Tr.debug(tc, "No class, object, or method found for CBIND check", new Object[] {e});
            //		                    FFDCFilter.processException(e, CLASS_NAME, "1237");
            //		                }
            //		                if (cbindCheckEnabled.booleanValue()) {
            //		                    flag = cbindCheckEnabled.booleanValue();
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //		                        Tr.debug(tc, "The mutualAuthCBINDCheck is true, so hard-coded setNeedClientAuth to true.");}
            //		                }
            //		            }
            //                }
            //            }

            engine.setNeedClientAuth(flag);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Client auth needed is " + engine.getNeedClientAuth());
            }
            if (!flag) {
                // Client auth set to false, check client auth supported
                flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION_SUPPORTED);
                engine.setWantClientAuth(flag);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Client auth supported is " + engine.getWantClientAuth());
                }
            }
            // enable ALPN support if this is for an inbound connection
            AlpnSupportUtils.registerAlpnSupport(connLink, engine);

        } else {
            // Update engine with client side specific config parameters.
            engine.setUseClientMode(true);
        }

        try {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Calling beginHandshake on engine");
            }
            engine.beginHandshake();
        } catch (SSLException se) {
            // no FFDC required
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Error while starting handshake; " + se);
            }
        }
    }
1133544
private SSLSocketFactory setUpSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(null, new TrustManager[] { createPromptingTrustManager() }, null);
        return ctx.getSocketFactory();
    }
715234
def enable_ssl(self, *args, **kwargs):
        
        if self.handshake_sent:
            raise SSLError('can only enable SSL before handshake')

        self.secure = True
        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
1200138
def set_server(self, wsgi_app, fnc_serve=None):
        

        self.set_wsgi_app(wsgi_app)

        ssl_config = self.get_config("ssl")
        ssl_context = {}

        if self.get_config("server") == "gevent":

            if ssl_config.get("enabled"):
                ssl_context["certfile"] = ssl_config.get("cert")
                ssl_context["keyfile"] = ssl_config.get("key")

            from gevent.pywsgi import WSGIServer

            http_server = WSGIServer(
                (self.host, self.port),
                wsgi_app,
                **ssl_context
            )

            self.log.debug("Serving WSGI via gevent.pywsgi.WSGIServer")

            fnc_serve = http_server.serve_forever

        elif self.get_config("server") == "uwsgi":
            self.pluginmgr_config["start_manual"] = True

        elif self.get_config("server") == "gunicorn":
            self.pluginmgr_config["start_manual"] = True

        elif self.get_config("server") == "self":
            fnc_serve = self.run

        # figure out async handler

        if self.get_config("async") == "gevent":

            # handle async via gevent
            import gevent

            self.log.debug("Handling wsgi on gevent")

            self.worker = gevent.spawn(fnc_serve)

        elif self.get_config("async") == "thread":

            self.worker = fnc_serve

        else:

            self.worker = fnc_serve
436482
def ssl_domain_port_path(uri)
      uri = URI.parse(uri)
      ssl = uri.scheme == 'https'
      [ssl, uri.host, uri.port, uri.path]
    end
1011494
def setup_ssl_context(config) # :nodoc:
      unless config[:SSLCertificate]
        cn = config[:SSLCertName]
        comment = config[:SSLCertComment]
        cert, key = Utils.create_self_signed_cert(1024, cn, comment)
        config[:SSLCertificate] = cert
        config[:SSLPrivateKey] = key
      end
      ctx = OpenSSL::SSL::SSLContext.new
      ctx.set_params
      ctx.ciphers = (CIPHERS - SmartProxyDynflowCore::Settings.instance.ssl_disabled_ciphers).join(':')
      ctx.key = config[:SSLPrivateKey]
      ctx.cert = config[:SSLCertificate]
      ctx.client_ca = config[:SSLClientCA]
      ctx.extra_chain_cert = config[:SSLExtraChainCert]
      ctx.ca_file = config[:SSLCACertificateFile]
      ctx.ca_path = config[:SSLCACertificatePath]
      ctx.cert_store = config[:SSLCertificateStore]
      ctx.tmp_dh_callback = config[:SSLTmpDhCallback]
      ctx.verify_mode = config[:SSLVerifyClient]
      ctx.verify_depth = config[:SSLVerifyDepth]
      ctx.verify_callback = config[:SSLVerifyCallback]
      ctx.timeout = config[:SSLTimeout]
      ctx.options |= config[:SSLOptions] unless config[:SSLOptions].nil?
      ctx
    end
325463
def install_nginx(instance, dbhost, dbname, port, hostname=None):
    """"""

    _check_root()

    log("Installing nginx configuration")

    if hostname is None:
        try:
            configuration = _get_system_configuration(dbhost, dbname)
            hostname = configuration.hostname
        except Exception as e:
            log('Exception:', e, type(e), exc=True, lvl=error)
            log("""Could not determine public fully qualified hostname!
Check systemconfig (see db view and db modify commands) or specify
manually with --hostname host.domain.tld

Using 'localhost' for now""", lvl=warn)
            hostname = 'localhost'

    definitions = {
        'instance': instance,
        'server_public_name': hostname,
        'ssl_certificate': cert_file,
        'ssl_key': key_file,
        'host_url': 'http://127.0.0.1:%i/' % port
    }

    if distribution == 'DEBIAN':
        configuration_file = '/etc/nginx/sites-available/hfos.%s.conf' % instance
        configuration_link = '/etc/nginx/sites-enabled/hfos.%s.conf' % instance
    elif distribution == 'ARCH':
        configuration_file = '/etc/nginx/nginx.conf'
        configuration_link = None
    else:
        log('Unsure how to proceed, you may need to specify your '
            'distribution', lvl=error)
        return

    log('Writing nginx HFOS site definition')
    write_template_file(os.path.join('dev/templates', nginx_configuration),
                        configuration_file,
                        definitions)

    if configuration_link is not None:
        log('Enabling nginx HFOS site (symlink)')
        if not os.path.exists(configuration_link):
            os.symlink(configuration_file, configuration_link)

    log('Restarting nginx service')
    Popen([
        'systemctl',
        'restart',
        'nginx.service'
    ])

    log("Done: ")