jiahuimbzuai/CoQuIR huggingface dataset:
// WebSecurityConfig::configure [java]
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/webjars/**", "/login", "/logout", "/static/**", "/console/*").permitAll();
		http.authorizeRequests().antMatchers("/user/**").hasAnyAuthority(FredBetPermission.PERM_USER_ADMINISTRATION);
		http.authorizeRequests().antMatchers("/admin/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
		http.authorizeRequests().antMatchers("/buildinfo/**").hasAnyAuthority(FredBetPermission.PERM_SYSTEM_INFO);
		http.authorizeRequests().antMatchers("/administration/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);

		// Spring Boot Actuator
		http.authorizeRequests().antMatchers("/actuator/health").permitAll();
		http.authorizeRequests().antMatchers("/actuator/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
		
		http.authorizeRequests().anyRequest().authenticated();
		
		http.formLogin().loginPage("/login").defaultSuccessUrl("/matches/upcoming").permitAll();
		http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true)
				.deleteCookies("JSESSIONID", "remember-me").permitAll();
		http.rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(REMEMBER_ME_TOKEN_VALIDITY_SECONDS);

		// we do not use CSRF in this app (by now)
		http.csrf().disable();

		// disable cache control to allow usage of ETAG headers (no image reload
		// if the image has not been changed)
		http.headers().cacheControl().disable();

		if (environment.acceptsProfiles(FredBetProfile.DEV)) {
			// this is for the embedded h2 console
			http.headers().frameOptions().disable();
		}
	}
// AuthenticationConfig::configure [java]
	@Override
	protected void configure(final HttpSecurity http) throws Exception {
		http
		        .authorizeRequests()
    				.antMatchers("/css/**").permitAll()
    				.antMatchers("/js/**").permitAll()
    				.antMatchers("/fonts/**").permitAll()
    				.antMatchers("/plugins/**").permitAll()
    				.antMatchers("/dist/**").permitAll()
                    .antMatchers("/login").permitAll()
    				.anyRequest().authenticated()
    				.and()
				.formLogin()
				    .loginPage("/login")
				    .permitAll()
				    .and()
				.logout()                                    
                    .permitAll();
	}
// AuthenticationConfig::configure [java]
	@Override
	protected void configure(final HttpSecurity http) throws Exception {
		http
		        .csrf()
		        .disable()
		        .authorizeRequests()
    				.antMatchers("/css/**").permitAll()
    				.antMatchers("/js/**").permitAll()
    				.antMatchers("/fonts/**").permitAll()
    				.antMatchers("/plugins/**").permitAll()
    				.antMatchers("/dist/**").permitAll()
                    .antMatchers("/login").permitAll()
    				.anyRequest().authenticated()
    				.and()
				.formLogin()
				    .loginPage("/login")
				    .permitAll()
				    .and()
				.logout()                                    
                    .permitAll();
	}
// mongoStore [javascript]
        store: new mongoStore({ mongooseConnection: mongoose.connection })
    }));

    server.use(passport.initialize());
    server.use(passport.session());
    server.use(flash());
    server.use(lusca.csrf());
    server.use(function(req, res, callback) {
        // Make user object available in templates.
        res.locals.user = req.user;
        res.locals.site = {
            title: config.app.title,
            url: config.server.host,
            dbHost: config.database,
            mailHost: config.mailer
        };
        callback();
    });

    // for nginx proxy
    if (mode == 'production') {
        server.enable('trust proxy');  // using Express behind nginx
    }

    server.use(function(req, res, callback) {
        // Remember original destination before login.
        var path = req.path.split('/')[1];

        if (/auth|api|login|logout|signup|components|css|img|js|favicon/i.test(path) || path == '') {
            return callback();
        }
        req.session.returnTo = req.path;

        callback();
    });

    var HOUR = 3600000;
    var DAY = HOUR * 24;
    var WEEK = DAY * 7;

    server.use(express.static(path.join(__dirname, 'public'), { maxAge: WEEK }));

    // Route Point
    var home = require('../route/home');
    var stat = require('../route/stat');
    var account = require('../route/account');
    var dashboard = require('../route/dashboard');

    server.use(home);
    server.use(stat);
    server.use(account);
    server.use(dashboard);

    // globalMiddleware
    // api counter for ip district
    // haroo cloud api document page
    // dummy testing
    // version specified api for only feature test
    // commonMiddleware
    // header parameter test
    // for account
    // districtMiddleware
    // district test
    // for token
    // for api version
    // for users
    // for documents

    // 500 Error Handler
    server.use(errorHandler());

    callback(server);
}
// mongoStore [javascript]
        store: new mongoStore({ mongooseConnection: mongoose.connection })
    }));

    server.use(passport.initialize());
    server.use(passport.session());
    server.use(flash());
    server.use(csrf());
    server.use(function(req, res, callback) {
        // Make user object available in templates.
        res.locals.user = req.user;
        res.locals.site = {
            title: config.app.title,
            url: config.server.host,
            dbHost: config.database,
            mailHost: config.mailer
        };
        callback();
    });

    // for nginx proxy
    if (mode == 'production') {
        server.enable('trust proxy');  // using Express behind nginx
    }

    server.use(function(req, res, callback) {
        // Remember original destination before login.
        var path = req.path.split('/')[1];

        if (/auth|api|login|logout|signup|components|css|img|js|favicon/i.test(path) || path == '') {
            return callback();
        }
        req.session.returnTo = req.path;

        callback();
    });

    var HOUR = 3600000;
    var DAY = HOUR * 24;
    var WEEK = DAY * 7;

    server.use(express.static(path.join(__dirname, 'public'), { maxAge: WEEK }));

    // Route Point
    var home = require('../route/home');
    var stat = require('../route/stat');
    var account = require('../route/account');
    var dashboard = require('../route/dashboard');

    server.use(home);
    server.use(stat);
    server.use(account);
    server.use(dashboard);

    // globalMiddleware
    // api counter for ip district
    // haroo cloud api document page
    // dummy testing
    // version specified api for only feature test
    // commonMiddleware
    // header parameter test
    // for account
    // districtMiddleware
    // district test
    // for token
    // for api version
    // for users
    // for documents

    // 500 Error Handler
    server.use(errorHandler());

    callback(server);
}
// (anonymous) [javascript]
app.use((req, res, next) => {
    if (req.path === '/api/upload' || req.path === '/upload' || req.path === '/' || req.path === '/getPosts/:userId') {
        next();
    } else {
        lusca.csrf()(req, res, next);
    }
});
// (anonymous) [javascript]
app.use((req, res, next) => {
    if (req.path === '/api/upload') {
        next();
    } else {
        lusca.csrf()(req, res, next);
    }
});
// (anonymous) [javascript]
app.post('/ldap', set_current_config, csrfProtection, function(req, res, next) {
  // Convert ENABLE_WRITE_BACK and ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD to boolean.
  req.body.ENABLE_WRITE_BACK = !!(req.body.ENABLE_WRITE_BACK && req.body.ENABLE_WRITE_BACK === 'on');
  req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD = !!(req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD && req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD === 'on');

  var config = xtend({}, req.current_config, req.body);
  test_config(config, function(err, result) {
    if (err) {
      return res.render('index', xtend(req.current_config, req.body, {
        ERROR: err.message,
        LDAP_RESULTS: result
      }));
    }
    req.session.LDAP_RESULTS = result;
    console.log(req.session.LDAP_RESULTS);
    next();
  });
}, function(req, res, next) {
// (anonymous) [javascript]
app.post('/ldap', set_current_config, function(req, res, next) {
  // Convert ENABLE_WRITE_BACK and ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD to boolean.
  req.body.ENABLE_WRITE_BACK = !!(req.body.ENABLE_WRITE_BACK && req.body.ENABLE_WRITE_BACK === 'on');
  req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD = !!(req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD && req.body.ENABLE_ACTIVE_DIRECTORY_UNICODE_PASSWORD === 'on');

  var config = xtend({}, req.current_config, req.body);
  test_config(config, function(err, result) {
    if (err) {
      return res.render('index', xtend(req.current_config, req.body, {
        ERROR: err.message,
        LDAP_RESULTS: result
      }));
    }
    req.session.LDAP_RESULTS = result;
    console.log(req.session.LDAP_RESULTS);
    next();
  });
}, function(req, res, next) {
// TestConfigServerTLSMinVersionIsSetBasedOnOptions [go]
func TestConfigServerTLSMinVersionIsSetBasedOnOptions(t *testing.T) {
	versions := []uint16{
		tls.VersionTLS12,
	}
	key, cert := getCertAndKey()

	for _, v := range versions {
		tlsConfig, err := Server(Options{
			MinVersion: v,
			CertFile:   cert,
			KeyFile:    key,
		})

		if err != nil || tlsConfig == nil {
			t.Fatal("Unable to configure server TLS", err)
		}

		if tlsConfig.MinVersion != v {
			t.Fatal("Unexpected minimum TLS version: ", tlsConfig.MinVersion)
		}
	}
}
// TestConfigServerTLSMinVersionIsSetBasedOnOptions [go]
func TestConfigServerTLSMinVersionIsSetBasedOnOptions(t *testing.T) {
	versions := []uint16{
		tls.VersionTLS11,
		tls.VersionTLS12,
	}
	key, cert := getCertAndKey()

	for _, v := range versions {
		tlsConfig, err := Server(Options{
			MinVersion: v,
			CertFile:   cert,
			KeyFile:    key,
		})

		if err != nil || tlsConfig == nil {
			t.Fatal("Unable to configure server TLS", err)
		}

		if tlsConfig.MinVersion != v {
			t.Fatal("Unexpected minimum TLS version: ", tlsConfig.MinVersion)
		}
	}
}
// ServerDefault [go]
func ServerDefault(ops ...func(*tls.Config)) *tls.Config {
	tlsconfig := &tls.Config{
		// Avoid fallback by default to SSL protocols < TLS1.2
		MinVersion:               tls.VersionTLS12,
		PreferServerCipherSuites: true,
		CipherSuites:             DefaultServerAcceptedCiphers,
	}

	for _, op := range ops {
		op(tlsconfig)
	}

	return tlsconfig
}
// ServerDefault [go]
func ServerDefault(ops ...func(*tls.Config)) *tls.Config {
	tlsconfig := &tls.Config{
		// Avoid fallback by default to SSL protocols < TLS1.0
		MinVersion:               tls.VersionTLS10,
		PreferServerCipherSuites: true,
		CipherSuites:             DefaultServerAcceptedCiphers,
	}

	for _, op := range ops {
		op(tlsconfig)
	}

	return tlsconfig
}
// TestConfigServerTLSServerCertsOnly [go]
func TestConfigServerTLSServerCertsOnly(t *testing.T) {
	key, cert := getCertAndKey()

	keypair, err := tls.LoadX509KeyPair(cert, key)
	if err != nil {
		t.Fatal("Unable to load the generated cert and key")
	}

	tlsConfig, err := Server(Options{
		CertFile: cert,
		KeyFile:  key,
	})
	if err != nil || tlsConfig == nil {
		t.Fatal("Unable to configure server TLS", err)
	}

	if len(tlsConfig.Certificates) != 1 {
		t.Fatal("Unexpected server certificates")
	}
	if len(tlsConfig.Certificates[0].Certificate) != len(keypair.Certificate) {
		t.Fatal("Unexpected server certificates")
	}
	for i, cert := range tlsConfig.Certificates[0].Certificate {
		if !bytes.Equal(cert, keypair.Certificate[i]) {
			t.Fatal("Unexpected server certificates")
		}
	}

	if !reflect.DeepEqual(tlsConfig.CipherSuites, DefaultServerAcceptedCiphers) {
		t.Fatal("Unexpected server cipher suites")
	}
	if !tlsConfig.PreferServerCipherSuites {
		t.Fatal("Expected server to prefer cipher suites")
	}
	if tlsConfig.MinVersion != tls.VersionTLS12 {
		t.Fatal("Unexpected server TLS version")
	}
}
// TestConfigServerTLSServerCertsOnly [go]
func TestConfigServerTLSServerCertsOnly(t *testing.T) {
	key, cert := getCertAndKey()

	keypair, err := tls.LoadX509KeyPair(cert, key)
	if err != nil {
		t.Fatal("Unable to load the generated cert and key")
	}

	tlsConfig, err := Server(Options{
		CertFile: cert,
		KeyFile:  key,
	})
	if err != nil || tlsConfig == nil {
		t.Fatal("Unable to configure server TLS", err)
	}

	if len(tlsConfig.Certificates) != 1 {
		t.Fatal("Unexpected server certificates")
	}
	if len(tlsConfig.Certificates[0].Certificate) != len(keypair.Certificate) {
		t.Fatal("Unexpected server certificates")
	}
	for i, cert := range tlsConfig.Certificates[0].Certificate {
		if !bytes.Equal(cert, keypair.Certificate[i]) {
			t.Fatal("Unexpected server certificates")
		}
	}

	if !reflect.DeepEqual(tlsConfig.CipherSuites, DefaultServerAcceptedCiphers) {
		t.Fatal("Unexpected server cipher suites")
	}
	if !tlsConfig.PreferServerCipherSuites {
		t.Fatal("Expected server to prefer cipher suites")
	}
	if tlsConfig.MinVersion != tls.VersionTLS10 {
		t.Fatal("Unexpected server TLS version")
	}
}
// create [python]
def create(request):
    return create_(User, request, encrypt_password_callback)
// create [python]
def create(request):
    return create_(User, request, encrypt_password)
// login [python]
def login(username, password):
    """Returns a `User` instance if the login does not fail with the
    given login and password.

    :username: username as String
    :password: password as SHA1 encrypted string
    :returns: `User` instance if login is OK else None.

    """
    log.debug("Login user '%s' with pw '%s'" % (username, password))
    user = load_user(username)
    if user:
        if verify_password(password, user.password):
            if user.activated:
                log.info("Login successfull '%s'" % (username))
                if passwords_needs_update(user.password):
                    log.info("Updating password for user '%s'" % (username))
                    user.password = encrypt_password(password) 
                return user
            else:
                log.info("Login failed for user '%s'. "
                         "Reason: Not activated" % username)
        else:
            log.info("Login failed for user '%s'. "
                     "Reason: Wrong password" % username)
    else:
        log.info("Login failed for user '%s'. "
                 "Reason: Username not known" % username)
    return None
// login [python]
def login(username, password):
    """Returns a `User` instance if the login does not fail with the
    given login and password.

    :username: username as String
    :password: password as SHA1 encrypted string
    :returns: `User` instance if login is OK else None.

    """
    md5_pw = hashlib.md5()
    md5_pw.update(password or "")
    md5_pw = md5_pw.hexdigest()
    log.debug("Login user '%s' with pw '%s'" % (username, password))
    try:
        user = DBSession.query(User).filter_by(login=username,
                                               password=md5_pw).one()
        if user.activated:
            log.info("Login successfull '%s'" % (username))
            return user
        log.info("Login failed for user '%s'. "
                 "Reason: Not activated" % username)
    except NoResultFound:
        log.info("Login failed for user '%s'. "
                 "Reason: Username or Password wrong" % username)
    return None
// test_ssl3_disabled [python]
    def test_ssl3_disabled(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        ssl_sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3)

        self.assertRaises(socket.error,
                          ssl_sock.connect,
                          ('127.0.0.1', 8000))
// test_ssl3_disabled [python]
    def test_ssl3_disabled(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        ssl_sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3)

        self.assertRaises(ssl.SSLError,
                          ssl_sock.connect,
                          ('127.0.0.1', 8000))
// _connect [python]
    def _connect(self):
        """Connect to the host and port specified in __init__."""
        if self.sock:
            return
        if self._proxy_host is not None:
            logger.info('Connecting to http proxy %s:%s',
                        self._proxy_host, self._proxy_port)
            sock = socketutil.create_connection((self._proxy_host,
                                                 self._proxy_port))
            if self.ssl:
                # TODO proxy header support
                data = self._buildheaders('CONNECT', '%s:%d' % (self.host,
                                                                self.port),
                                          {}, HTTP_VER_1_0)
                sock.send(data)
                sock.setblocking(0)
                r = self.response_class(sock, self.timeout, 'CONNECT')
                timeout_exc = HTTPTimeoutException(
                    'Timed out waiting for CONNECT response from proxy')
                while not r.complete():
                    try:
                        # We're a friend of the response class, so let
                        # us use the private attribute.
                        # pylint: disable=W0212
                        if not r._select():
                            if not r.complete():
                                raise timeout_exc
                    except HTTPTimeoutException:
                        # This raise/except pattern looks goofy, but
                        # _select can raise the timeout as well as the
                        # loop body. I wish it wasn't this convoluted,
                        # but I don't have a better solution
                        # immediately handy.
                        raise timeout_exc
                if r.status != 200:
                    raise HTTPProxyConnectFailedException(
                        'Proxy connection failed: %d %s' % (r.status,
                                                            r.read()))
                logger.info('CONNECT (for SSL) to %s:%s via proxy succeeded.',
                            self.host, self.port)
        else:
            sock = socketutil.create_connection((self.host, self.port))
        if self.ssl:
            # This is the default, but in the case of proxied SSL
            # requests the proxy logic above will have cleared
            # blocking mode, so re-enable it just to be safe.
            sock.setblocking(1)
            logger.debug('wrapping socket for ssl with options %r',
                         self.ssl_opts)
            sock = self._ssl_wrap_socket(sock, **self.ssl_opts)
            if self._ssl_validator:
                self._ssl_validator(sock)
        sock.setblocking(0)
        self.sock = sock
// _connect [python]
    def _connect(self):
        """Connect to the host and port specified in __init__."""
        if self.sock:
            return
        if self._proxy_host is not None:
            logger.info('Connecting to http proxy %s:%s',
                        self._proxy_host, self._proxy_port)
            sock = socketutil.create_connection((self._proxy_host,
                                                 self._proxy_port))
            if self.ssl:
                # TODO proxy header support
                data = self._buildheaders('CONNECT', '%s:%d' % (self.host,
                                                                self.port),
                                          {}, HTTP_VER_1_0)
                sock.send(data)
                sock.setblocking(0)
                r = self.response_class(sock, self.timeout, 'CONNECT')
                timeout_exc = HTTPTimeoutException(
                    'Timed out waiting for CONNECT response from proxy')
                while not r.complete():
                    try:
                        # We're a friend of the response class, so let
                        # us use the private attribute.
                        # pylint: disable=W0212
                        if not r._select():
                            if not r.complete():
                                raise timeout_exc
                    except HTTPTimeoutException:
                        # This raise/except pattern looks goofy, but
                        # _select can raise the timeout as well as the
                        # loop body. I wish it wasn't this convoluted,
                        # but I don't have a better solution
                        # immediately handy.
                        raise timeout_exc
                if r.status != 200:
                    raise HTTPProxyConnectFailedException(
                        'Proxy connection failed: %d %s' % (r.status,
                                                            r.read()))
                logger.info('CONNECT (for SSL) to %s:%s via proxy succeeded.',
                            self.host, self.port)
        else:
            sock = socketutil.create_connection((self.host, self.port))
        if self.ssl:
            # This is the default, but in the case of proxied SSL
            # requests the proxy logic above will have cleared
            # blocking mode, so re-enable it just to be safe.
            sock.setblocking(1)
            logger.debug('wrapping socket for ssl with options %r',
                         self.ssl_opts)
            sock = socketutil.wrap_socket(sock, **self.ssl_opts)
            if self._ssl_validator:
                self._ssl_validator(sock)
        sock.setblocking(0)
        self.sock = sock
// get_request [python]
        def get_request(self):

            # Prepare SSL context.
            context = ssl._create_unverified_context(
                protocol=ssl.PROTOCOL_TLS_SERVER,
                cert_reqs=ssl.CERT_OPTIONAL,
                check_hostname=False,
                purpose=ssl.Purpose.CLIENT_AUTH,
                certfile=HttpsTestServerLayer.CERT_FILE,
                keyfile=HttpsTestServerLayer.CERT_FILE,
                cafile=HttpsTestServerLayer.CACERT_FILE)

            # Set minimum protocol version, TLSv1 and TLSv1.1 are unsafe.
            context.minimum_version = ssl.TLSVersion.TLSv1_2

            # Wrap TLS encryption around socket.
            socket, client_address = HTTPServer.get_request(self)
            socket = context.wrap_socket(socket, server_side=True)

            return socket, client_address
// get_request [python]
        def get_request(self):
            socket, client_address = HTTPServer.get_request(self)
            socket = ssl.wrap_socket(socket,
                                     keyfile=HttpsTestServerLayer.CERT_FILE,
                                     certfile=HttpsTestServerLayer.CERT_FILE,
                                     cert_reqs=ssl.CERT_OPTIONAL,
                                     ca_certs=HttpsTestServerLayer.CACERT_FILE,
                                     server_side=True)
            return socket, client_address
// __init__ [python]
    def __init__(self, host, port=None, use_ssl=None, ssl_validator=None,
                 timeout=TIMEOUT_DEFAULT,
                 continue_timeout=TIMEOUT_ASSUME_CONTINUE,
                 proxy_hostport=None, ssl_wrap_socket=None, **ssl_opts):
        """Create a new HTTPConnection.

        Args:
          host: The host to which we'll connect.
          port: Optional. The port over which we'll connect. Default 80 for
                non-ssl, 443 for ssl.
          use_ssl: Optional. Whether to use ssl. Defaults to False if port is
                   not 443, true if port is 443.
          ssl_validator: a function(socket) to validate the ssl cert
          timeout: Optional. Connection timeout, default is TIMEOUT_DEFAULT.
          continue_timeout: Optional. Timeout for waiting on an expected
                   "100 Continue" response. Default is TIMEOUT_ASSUME_CONTINUE.
          proxy_hostport: Optional. Tuple of (host, port) to use as an http
                       proxy for the connection. Default is to not use a proxy.
          ssl_wrap_socket: Optional function to use for wrapping
            sockets. If unspecified, the one from the ssl module will
            be used if available, or something that's compatible with
            it if on a Python older than 2.6.

        Any extra keyword arguments to this function will be provided
        to the ssl_wrap_socket method. If no ssl
        """
        if port is None and host.count(':') == 1 or ']:' in host:
            host, port = host.rsplit(':', 1)
            port = int(port)
            if '[' in host:
                host = host[1:-1]
        if ssl_wrap_socket is not None:
            self._ssl_wrap_socket = ssl_wrap_socket
        else:
            self._ssl_wrap_socket = socketutil.wrap_socket
        if use_ssl is None and port is None:
            use_ssl = False
            port = 80
        elif use_ssl is None:
            use_ssl = (port == 443)
        elif port is None:
            port = (use_ssl and 443 or 80)
        self.port = port
        if use_ssl and not socketutil.have_ssl:
            raise Exception('ssl requested but unavailable on this Python')
        self.ssl = use_ssl
        self.ssl_opts = ssl_opts
        self._ssl_validator = ssl_validator
        self.host = host
        self.sock = None
        self._current_response = None
        self._current_response_taken = False
        if proxy_hostport is None:
            self._proxy_host = self._proxy_port = None
        else:
            self._proxy_host, self._proxy_port = proxy_hostport

        self.timeout = timeout
        self.continue_timeout = continue_timeout
// __init__ [python]
    def __init__(self, host, port=None, use_ssl=None, ssl_validator=None,
                 timeout=TIMEOUT_DEFAULT,
                 continue_timeout=TIMEOUT_ASSUME_CONTINUE,
                 proxy_hostport=None, **ssl_opts):
        """Create a new HTTPConnection.

        Args:
          host: The host to which we'll connect.
          port: Optional. The port over which we'll connect. Default 80 for
                non-ssl, 443 for ssl.
          use_ssl: Optional. Whether to use ssl. Defaults to False if port is
                   not 443, true if port is 443.
          ssl_validator: a function(socket) to validate the ssl cert
          timeout: Optional. Connection timeout, default is TIMEOUT_DEFAULT.
          continue_timeout: Optional. Timeout for waiting on an expected
                   "100 Continue" response. Default is TIMEOUT_ASSUME_CONTINUE.
          proxy_hostport: Optional. Tuple of (host, port) to use as an http
                       proxy for the connection. Default is to not use a proxy.
        """
        if port is None and host.count(':') == 1 or ']:' in host:
            host, port = host.rsplit(':', 1)
            port = int(port)
            if '[' in host:
                host = host[1:-1]
        if use_ssl is None and port is None:
            use_ssl = False
            port = 80
        elif use_ssl is None:
            use_ssl = (port == 443)
        elif port is None:
            port = (use_ssl and 443 or 80)
        self.port = port
        if use_ssl and not socketutil.have_ssl:
            raise Exception('ssl requested but unavailable on this Python')
        self.ssl = use_ssl
        self.ssl_opts = ssl_opts
        self._ssl_validator = ssl_validator
        self.host = host
        self.sock = None
        self._current_response = None
        self._current_response_taken = False
        if proxy_hostport is None:
            self._proxy_host = self._proxy_port = None
        else:
            self._proxy_host, self._proxy_port = proxy_hostport

        self.timeout = timeout
        self.continue_timeout = continue_timeout
// preparehttpserver [python]
    @staticmethod
    def preparehttpserver(httpserver, ui):
        try:
            from .. import sslutil
            sslutil.modernssl
        except ImportError:
            raise error.Abort(_("SSL support is unavailable"))

        certfile = ui.config('web', 'certificate')

        # These config options are currently only meant for testing. Use
        # at your own risk.
        cafile = ui.config('devel', 'servercafile')
        reqcert = ui.configbool('devel', 'serverrequirecert')

        httpserver.socket = sslutil.wrapserversocket(httpserver.socket,
                                                     ui,
                                                     certfile=certfile,
                                                     cafile=cafile,
                                                     requireclientcert=reqcert)
// preparehttpserver [python]
    @staticmethod
    def preparehttpserver(httpserver, ui):
        try:
            import ssl
            ssl.wrap_socket
        except ImportError:
            raise error.Abort(_("SSL support is unavailable"))

        certfile = ui.config('web', 'certificate')
        httpserver.socket = ssl.wrap_socket(
            httpserver.socket, server_side=True,
            certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1)
// vault_encrypt [python]
def vault_encrypt(v_plaintexts, mp):
    aes = do_crypto_setup(mp)
    return aes.encrypt(vault_encode(v_plaintexts, mp))
// vault_encrypt [python]
def vault_encrypt(v_plaintexts, mp):
    iv = '01234567'
    vault_code = vault_encode(v_plaintexts, mp)
    des3 = DES3.new(hash_mp(mp), DES3.MODE_CFB, iv)
    # plaintext= staruct.pack("%sI" % len(vault_code), *vault_code)
    c = des3.encrypt(vault_code)
    return c
// __init__ [python]
    def __init__(self, server_address, RequestHandlerClass, router, rewriter, bind_hostname,
                 config=None, use_ssl=False, key_file=None, certificate=None,
                 encrypt_after_connect=False, latency=None, **kwargs):
        """Server for HTTP(s) Requests

        :param server_address: tuple of (server_name, port)

        :param RequestHandlerClass: BaseHTTPRequestHandler-like class to use for
                                    handling requests.

        :param router: Router instance to use for matching requests to handler
                       functions

        :param rewriter: RequestRewriter-like instance to use for preprocessing
                         requests before they are routed

        :param config: Dictionary holding environment configuration settings for
                       handlers to read, or None to use the default values.

        :param use_ssl: Boolean indicating whether the server should use SSL

        :param key_file: Path to key file to use if SSL is enabled.

        :param certificate: Path to certificate to use if SSL is enabled.

        :param encrypt_after_connect: For each connection, don't start encryption
                                      until a CONNECT message has been received.
                                      This enables the server to act as a
                                      self-proxy.

        :param bind_hostname True to bind the server to both the hostname and
                             port specified in the server_address parameter.
                             False to bind the server only to the port in the
                             server_address parameter, but not to the hostname.
        :param latency: Delay in ms to wait before seving each response, or
                        callable that returns a delay in ms
        """
        self.router = router
        self.rewriter = rewriter

        self.scheme = "https" if use_ssl else "http"

        self.latency = latency

        if bind_hostname:
            hostname_port = server_address
        else:
            hostname_port = ("",server_address[1])

        #super doesn't work here because BaseHTTPServer.HTTPServer is old-style
        BaseHTTPServer.HTTPServer.__init__(self, hostname_port, RequestHandlerClass, **kwargs)

        if config is not None:
            Server.config = config
        else:
            logger.debug("Using default configuration")
            Server.config = {"host": server_address[0],
                             "domains": {"": server_address[0]},
                             "ports": {"http": [self.server_address[1]]}}


        self.key_file = key_file
        self.certificate = certificate
        self.encrypt_after_connect = use_ssl and encrypt_after_connect

        if use_ssl and not encrypt_after_connect:
            self.socket = ssl.wrap_socket(self.socket,
                                          keyfile=self.key_file,
                                          certfile=self.certificate,
                                          server_side=True)
// vault_decrypt [python]
def vault_decrypt(v_ciphertexts, mp, vault_size):
    aes = do_crypto_setup(mp)
    return vault_decode(aes.decrypt(v_ciphertexts), mp, vault_size)
// vault_decrypt [python]
def vault_decrypt(v_ciphertexts, mp, vault_size):
    iv = '01234567'
    des3 = DES3.new(hash_mp(mp), DES3.MODE_CFB, iv)
    return vault_decode(des3.decrypt(v_ciphertexts), mp, vault_size)
// password_reset [python]
def password_reset(token, db):
    """Will check if there is a password reset token is valid. The
    function will reset the password of the user. The new generated
    password is returned.

    :token: password reset token
    :db: db connection
    :returns: tupe of user and password
    """
    try:
        token = db.query(PasswordResetRequest).filter_by(token=token).one()
        # Check that the token is not outdated
        td = datetime.now() - token.created
        if td.days <= 1:
            user = token.user
            password = password_generator()
            user.password = encrypt_password(password)
            log.info('Password reset success for user %s' % user)
            # delete all old password request token
            for old_token in user.reset_tokens:
                db.delete(old_token)
            return user, password
        else:
            log.warning('Password reset failed for token %s (outdated)'
                        % token)
            return None, None
    except NoResultFound:
        log.warning('Password reset failed for token %s' % token)
        return None, None
// password_reset [python]
def password_reset(token, db):
    """Will check if there is a password reset token is valid. The
    function will reset the password of the user. The new generated
    password is returned.

    :token: password reset token
    :db: db connection
    :returns: tupe of user and password
    """
    try:
        token = db.query(PasswordResetRequest).filter_by(token=token).one()
        # Check that the token is not outdated
        td = datetime.now() - token.created
        if td.days <= 1:
            user = token.user
            password = password_generator()
            md5_pw = hashlib.md5()
            md5_pw.update(password)
            md5_pw = md5_pw.hexdigest()
            user.password = md5_pw
            log.info('Password reset success for user %s' % user)
            # delete all old password request token
            for old_token in user.reset_tokens:
                db.delete(old_token)
            return user, password
        else:
            log.warning('Password reset failed for token %s (outdated)'
                        % token)
            return None, None
    except NoResultFound:
        log.warning('Password reset failed for token %s' % token)
        return None, None
// connect [python]
    @tornado.web.asynchronous
    def connect(self):
        """Gets called when a connect request is received.

        * The host and port are obtained from the request uri
        * A socket is created, wrapped in ssl and then added to SSLIOStream
        * This stream is used to connect to speak to the remote host on given port
        * If the server speaks ssl on that port, callback start_tunnel is called
        * An OK response is written back to client
        * The client side socket is wrapped in ssl
        * If the wrapping is successful, a new SSLIOStream is made using that socket
        * The stream is added back to the server for monitoring
        """
        host, port = self.request.uri.split(':')

        def start_tunnel():
            try:
                self.request.connection.stream.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
                wrap_socket(
                    self.request.connection.stream.socket,
                    host,
                    self.application.ca_cert,
                    self.application.ca_key,
                    self.application.ca_key_pass,
                    self.application.certs_folder,
                    success=ssl_success
                )
            except tornado.iostream.StreamClosedError:
                pass

        def ssl_success(client_socket):
            client = tornado.iostream.SSLIOStream(client_socket)
            ProxyHandler.server.handle_stream(client, self.application.inbound_ip)

        # Tiny Hack to satisfy proxychains CONNECT request to HTTP port.
        # HTTPS fail check has to be improvised
        def ssl_fail():
            try:
                self.request.connection.stream.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
            except tornado.iostream.StreamClosedError:
                pass
            ProxyHandler.server.handle_stream(self.request.connection.stream, self.application.inbound_ip)

        # Hacking to be done here, so as to check for ssl using proxy and auth
        try:
            # Adds a fix for check_hostname errors in Tornado 4.3.0
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.check_hostname = False
            context.load_default_certs()
            # When connecting through a new socket, no need to wrap the socket before passing
            # to SSIOStream
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            upstream = tornado.iostream.SSLIOStream(s, ssl_options=context)
            upstream.set_close_callback(ssl_fail)
            upstream.connect((host, int(port)), start_tunnel)
        except Exception:
            self.finish()
// connect [python]
    @tornado.web.asynchronous
    def connect(self):
        """Gets called when a connect request is received.

        * The host and port are obtained from the request uri
        * A socket is created, wrapped in ssl and then added to SSLIOStream
        * This stream is used to connect to speak to the remote host on given port
        * If the server speaks ssl on that port, callback start_tunnel is called
        * An OK response is written back to client
        * The client side socket is wrapped in ssl
        * If the wrapping is successful, a new SSLIOStream is made using that socket
        * The stream is added back to the server for monitoring
        """
        host, port = self.request.uri.split(':')

        def start_tunnel():
            try:
                self.request.connection.stream.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
                wrap_socket(
                    self.request.connection.stream.socket,
                    host,
                    self.application.ca_cert,
                    self.application.ca_key,
                    self.application.ca_key_pass,
                    self.application.certs_folder,
                    success=ssl_success
                )
            except tornado.iostream.StreamClosedError:
                pass

        def ssl_success(client_socket):
            client = tornado.iostream.SSLIOStream(client_socket)
            ProxyHandler.server.handle_stream(client, self.application.inbound_ip)

        # Tiny Hack to satisfy proxychains CONNECT request to HTTP port.
        # HTTPS fail check has to be improvised
        def ssl_fail():
            try:
                self.request.connection.stream.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
            except tornado.iostream.StreamClosedError:
                pass
            ProxyHandler.server.handle_stream(self.request.connection.stream, self.application.inbound_ip)

        # Hacking to be done here, so as to check for ssl using proxy and auth
        try:
            s = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0))
            upstream = tornado.iostream.SSLIOStream(s)
            upstream.set_close_callback(ssl_fail)
            upstream.connect((host, int(port)), start_tunnel)
        except Exception:
            self.finish()
// test_fluent_safe [python]
def test_fluent_safe():
    hostname = 'www.python.org'
    context = SSL.Context(SSL.SSLv23_METHOD)
    context.set_options(SSL.OP_NO_SSLv2)
    context.set_options(SSL.OP_NO_SSLv3)
    context.set_options(SSL.OP_NO_TLSv1)
    context.set_options(SSL.OP_NO_TLSv1_1)

    conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
    r = conn.connect((hostname, 443))
    print(r, conn.get_protocol_version_name())
// test_fluent_safe [python]
def test_fluent_safe():
    hostname = 'www.python.org'
    context = SSL.Context(SSL.SSLv23_METHOD)
    context.set_options(SSL.OP_NO_TLSv1)
    context.set_options(SSL.OP_NO_TLSv1_1)

    conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
    r = conn.connect((hostname, 443))
    print(r, conn.get_protocol_version_name())
// connect [python]
    def connect(self):
        """Override the Connect Method to fix the Certificate Verification."""
        # Add certificate verification
        conn = self._new_conn()

        if getattr(self, '_tunnel_host', None):
            # _tunnel_host was added in Python 2.6.3
            # (See: http://hg.python.org/cpython/rev/0f57b30a152f)

            self.sock = conn
            # Calls self._set_hostport(), so self.host is
            # self._tunnel_host below.
            #
            # disable pylint because pylint doesn't support importing
            # from six.moves yet. see:
            # https://bitbucket.org/logilab/pylint/issue/550/
            self._tunnel()  # pylint: disable=E1101
            # Mark this connection as not reusable
            self.auto_open = 0

        # The RECENT_DATE is originally taken from requests. The date is just
        # an arbitrary value that is used as a sanity test to identify hosts
        # that are using the default time after bootup (e.g. 1970), and
        # provides information for debugging
        RECENT_DATE = datetime.date(2014, 1, 1)
        is_time_off = datetime.date.today() < RECENT_DATE
        if is_time_off:
            LOG.warning('System time is way off (before %s). This will '
                        'probably lead to SSL verification errors.',
                        RECENT_DATE)

        # Wrap socket using verification with the root certs in
        # trusted_root_certs
        self.sock = ssl.SSLContext.wrap_socket(conn)

        self._verify_cert(self.sock, self.ca_certs)
        self.is_verified = True
// connect [python]
    def connect(self):
        """Override the Connect Method to fix the Certificate Verification."""
        # Add certificate verification
        conn = self._new_conn()

        if getattr(self, '_tunnel_host', None):
            # _tunnel_host was added in Python 2.6.3
            # (See: http://hg.python.org/cpython/rev/0f57b30a152f)

            self.sock = conn
            # Calls self._set_hostport(), so self.host is
            # self._tunnel_host below.
            #
            # disable pylint because pylint doesn't support importing
            # from six.moves yet. see:
            # https://bitbucket.org/logilab/pylint/issue/550/
            self._tunnel()  # pylint: disable=E1101
            # Mark this connection as not reusable
            self.auto_open = 0

        # The RECENT_DATE is originally taken from requests. The date is just
        # an arbitrary value that is used as a sanity test to identify hosts
        # that are using the default time after bootup (e.g. 1970), and
        # provides information for debugging
        RECENT_DATE = datetime.date(2014, 1, 1)
        is_time_off = datetime.date.today() < RECENT_DATE
        if is_time_off:
            LOG.warning('System time is way off (before %s). This will '
                        'probably lead to SSL verification errors.',
                        RECENT_DATE)

        # Wrap socket using verification with the root certs in
        # trusted_root_certs
        self.sock = ssl.wrap_socket(conn)

        self._verify_cert(self.sock, self.ca_certs)
        self.is_verified = True
// gen_signed_cert [python]
def gen_signed_cert(domain, ca_crt, ca_key, ca_pass, certs_folder):
    """
    This function takes a domain name as a parameter and then creates a certificate and key with the
    domain name(replacing dots by underscores), finally signing the certificate using specified CA and
    returns the path of key and cert files. If you are yet to generate a CA then check the top comments
    """
    key_path = os.path.join(certs_folder, re.sub('[^-0-9a-zA-Z_]', '_', domain) + ".key")
    cert_path = os.path.join(certs_folder, re.sub('[^-0-9a-zA-Z_]', '_', domain) + ".crt")

    # The first conditions checks if file exists, and does nothing if true
    # If file doenst exist lock is obtained for writing (Other processes in race must wait)
    # After obtaining lock another check to handle race conditions gracefully
    if os.path.exists(key_path) and os.path.exists(cert_path):
        pass
    else:
        with FileLock(cert_path, timeout=2):
            # Check happens if the certificate and key pair already exists for a domain
            if os.path.exists(key_path) and os.path.exists(cert_path):
                pass
            else:
                # Serial Generation - Serial number must be unique for each certificate,
                # so serial is generated based on domain name
                md5_hash = hashlib.md5()
                md5_hash.update(domain)
                serial = int(md5_hash.hexdigest(), 36)

                # The CA stuff is loaded from the same folder as this script
                ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(ca_crt, 'rb').read())
                # The last parameter is the password for your CA key file
                ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(ca_key, 'rb').read(), passphrase=ca_pass)

                key = crypto.PKey()
                key.generate_key(crypto.TYPE_RSA, 2048)

                cert = crypto.X509()
                cert.get_subject().C = "IN"
                cert.get_subject().ST = "AP"
                cert.get_subject().L = "127.0.0.1"
                cert.get_subject().O = "OWTF"
                cert.get_subject().OU = "Inbound-Proxy"
                cert.get_subject().CN = domain
                cert.gmtime_adj_notBefore(0)
                cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)
                cert.set_serial_number(serial)
                cert.set_issuer(ca_cert.get_subject())
                cert.set_pubkey(key)
                cert.sign(ca_key, "sha1")

                # The key and cert files are dumped and their paths are returned
                domain_key = open(key_path, "w")
                domain_key.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))

                domain_cert = open(cert_path, "w")
                domain_cert.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    return key_path, cert_path