Initiates session fingerprint based on user agent configurations and / or
ip address. Fingerprint which includes ip address might not work with
proxies based networks.
352233
private function setupFingerprintHandler()
    {
        if ($this->userAgentFingerprinted || $this->ipAddressFingerprinted
            && !isset($_SESSION['__HANDLER_FINGERPRINT'])) {
            $_SESSION['__HANDLER_FINGERPRINT'] = $this->createFingerprint();
        }
    }
688062
def get_process_fingerprint():
    
    pid = os.getpid()
    hostname = socket.gethostname()
    padded_pid = _pad(_to_base36(pid), 2)
    hostname_hash = sum([ord(x) for x in hostname]) + len(hostname) + 36
    padded_hostname = _pad(_to_base36(hostname_hash), 2)
    return padded_pid + padded_hostname
187777
private static ProtocolSigFingerprint getSigFingerprint(
      Class <? extends VersionedProtocol> protocol, long serverVersion) {
    String protocolName = protocol.getName();
    synchronized (PROTOCOL_FINGERPRINT_CACHE) {
      ProtocolSigFingerprint sig = PROTOCOL_FINGERPRINT_CACHE.get(protocolName);
      if (sig == null) {
        int[] serverMethodHashcodes = getFingerprints(protocol.getMethods());
        sig = new ProtocolSigFingerprint(
            new ProtocolSignature(serverVersion, serverMethodHashcodes),
            getFingerprint(serverMethodHashcodes));
        PROTOCOL_FINGERPRINT_CACHE.put(protocolName, sig);
      }
      return sig;
    }
  }
239794
def dshield_ip_check(ip):
    """"""
    if not is_IPv4Address(ip):
        return None

    headers = {'User-Agent': useragent}
    url = 'https://isc.sans.edu/api/ip/'
    response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
    return response.json()
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
1281305
def _check(peers):

    ''''''

    if not isinstance(peers, list):
        return False

    for peer in peers:
        if not isinstance(peer, six.string_types):
            return False

    if not HAS_NETADDR:  # if does not have this lib installed, will simply try to load what user specified
        # if the addresses are not correctly specified, will trow error when loading the actual config
        return True

    ip_only_peers = []
    for peer in peers:
        try:
            ip_only_peers.append(six.text_type(IPAddress(peer)))  # append the str value
        except AddrFormatError:
            # if not a valid IP Address
            # will try to see if it is a nameserver and resolve it
            if not HAS_DNSRESOLVER:
                continue  # without the dns resolver cannot populate the list of NTP entities based on their nameserver
                # so we'll move on
            dns_reply = []
            try:
                # try to see if it is a valid NS
                dns_reply = dns.resolver.query(peer)
            except dns.resolver.NoAnswer:
                # no a valid DNS entry either
                return False
            for dns_ip in dns_reply:
                ip_only_peers.append(six.text_type(dns_ip))

    peers = ip_only_peers

    return True
291676
protected Object activateProxy()
    {
        if ( settings == null )
        {
            return null;
        }
        final Proxy proxy = settings.getActiveProxy();
        if ( proxy == null )
        {
            return null;
        }

        final List<String> properties = new ArrayList<String>();
        final String protocol = proxy.getProtocol();
        final String prefix = isEmpty( protocol ) ? "" : ( protocol + "." );

        final String host = proxy.getHost();
        final String hostProperty = prefix + "proxyHost";
        final String hostValue = isEmpty( host ) ? null : host;
        setProperty( properties, hostProperty, hostValue );
        final int port = proxy.getPort();
        final String portProperty = prefix + "proxyPort";
        final String portValue = ( port == 0 || port == -1 ) ? null : String.valueOf( port );
        setProperty( properties, portProperty, portValue );
        final String username = proxy.getUsername();
        final String userProperty = prefix + "proxyUser";
        final String userValue = isEmpty( username ) ? null : username;
        setProperty( properties, userProperty, userValue );
        final String password = proxy.getPassword();
        final String passwordProperty = prefix + "proxyPassword";
        final String passwordValue = isEmpty( password ) ? null : password;
        setProperty( properties, passwordProperty, passwordValue );
        final String nonProxyHosts = proxy.getNonProxyHosts();
        final String nonProxyHostsProperty = prefix + "nonProxyHosts";
        final String nonProxyHostsValue = isEmpty( nonProxyHosts ) ? null : nonProxyHosts.replace( ',', '|' );
        setProperty( properties, nonProxyHostsProperty, nonProxyHostsValue );
        getLog().debug( "Proxy settings: " + hostProperty + "=" + hostValue + ", " + portProperty + "=" + portValue
            + ", " + userProperty + "=" + userValue + ", " + passwordProperty + "="
            + ( passwordValue == null ? "null" : "<PasswordNotLogged>" ) + ", " + nonProxyHostsProperty + "="
            + nonProxyHostsValue );
        return properties;
    }
801745
def create
      session[:impersonator_redirect_path] = params[:redirect_path].presence
      @user = MnoEnterprise::User.find(params[:user_id])
      if @user.present?
        if @user.admin_role.present?
          flash[:notice] = 'User is a staff member'
        else
          impersonate(@user)
        end
      else
        flash[:notice] = "User doesn't exist"
      end

      path = mnoe_home_path
      path = add_param_to_fragment(path, 'dhbRefId', params[:dhbRefId]) if params[:dhbRefId].present?

      redirect_to path
    end
1000993
def FingerprintFile(self, pathspec, max_filesize=None, request_data=None):
    """"""
    request = rdf_client_action.FingerprintRequest(pathspec=pathspec)
    if max_filesize is not None:
      request.max_filesize = max_filesize

    # Generic hash.
    request.AddRequest(
        fp_type=rdf_client_action.FingerprintTuple.Type.FPT_GENERIC,
        hashers=[
            rdf_client_action.FingerprintTuple.HashType.MD5,
            rdf_client_action.FingerprintTuple.HashType.SHA1,
            rdf_client_action.FingerprintTuple.HashType.SHA256
        ])

    # Authenticode hash.
    request.AddRequest(
        fp_type=rdf_client_action.FingerprintTuple.Type.FPT_PE_COFF,
        hashers=[
            rdf_client_action.FingerprintTuple.HashType.MD5,
            rdf_client_action.FingerprintTuple.HashType.SHA1,
            rdf_client_action.FingerprintTuple.HashType.SHA256
        ])

    self.CallClient(
        self.fingerprint_file_mixin_client_action,
        request,
        next_state="ProcessFingerprint",
        request_data=request_data)
509136
private boolean matchesFingerprint(byte[] buffer, byte[] fingerprint)
   {
      return Arrays.equals(fingerprint, Arrays.copyOf(buffer, fingerprint.length));
   }
546061
public void updateAnonymity() throws IOException {
    ProxyBinResponse response = GhostMeHelper.getMyInformation(this.getJavaNetProxy());

    if (!response.getOrigin().equalsIgnoreCase(this.getIp())) {
      anonymous = false;
      return;
    }

    if (!response.getHeaders().get("X-Forwarded-For").equalsIgnoreCase(this.getIp())) {
      anonymous = false;
      return;
    }

    if (!response.getHeaders().get("X-Real-Ip").equalsIgnoreCase(this.getIp())) {
      anonymous = false;
      return;
    }

    anonymous = true;

  }
498305
private String getServerTlsFingerPrint() {
        String fingerPrint = null;
        Map<String, Object> serverConfig = Config.getInstance().getJsonMapConfigNoCache("server");
        Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfigNoCache("secret");
        // load keystore here based on server config and secret config
        String keystoreName = (String)serverConfig.get("keystoreName");
        String serverKeystorePass = (String)secretConfig.get("serverKeystorePass");
        if(keystoreName != null) {
            try (InputStream stream = Config.getInstance().getInputStreamFromFile(keystoreName)) {
                KeyStore loadedKeystore = KeyStore.getInstance("JKS");
                loadedKeystore.load(stream, serverKeystorePass.toCharArray());
                X509Certificate cert = (X509Certificate)loadedKeystore.getCertificate("server");
                if(cert != null) {
                    fingerPrint = FingerPrintUtil.getCertFingerPrint(cert);
                } else {
                    logger.error("Unable to find the certificate with alias name as server in the keystore");
                }
            } catch (Exception e) {
                logger.error("Unable to load server keystore ", e);
            }
        }
        return fingerPrint;
    }
1229015
@InterfaceAudience.Private
    protected void checkSession() {
        if (getAuthenticator() != null) {
            Authorizer auth = (Authorizer) getAuthenticator();
            auth.setRemoteURL(remote);
            auth.setLocalUUID(db.publicUUID());
        }
        if (getAuthenticator() != null && getAuthenticator() instanceof SessionCookieAuthorizer) {
            // Sync Gateway session API is at /db/_session; try that first
            checkSessionAtPath("_session");
        } else {
            login();
        }
    }
1130834
def Run(self, args):
    """"""
    with vfs.VFSOpen(
        args.pathspec, progress_callback=self.Progress) as file_obj:
      fingerprinter = Fingerprinter(self.Progress, file_obj)
      response = rdf_client_action.FingerprintResponse()
      response.pathspec = file_obj.pathspec
      if args.tuples:
        tuples = args.tuples
      else:
        # There are none selected -- we will cover everything
        tuples = list()
        for k in self._fingerprint_types:
          tuples.append(rdf_client_action.FingerprintTuple(fp_type=k))

      for finger in tuples:
        hashers = [self._hash_types[h] for h in finger.hashers] or None
        if finger.fp_type in self._fingerprint_types:
          invoke = self._fingerprint_types[finger.fp_type]
          res = invoke(fingerprinter, hashers)
          if res:
            response.matching_types.append(finger.fp_type)
        else:
          raise RuntimeError(
              "Encountered unknown fingerprint type. %s" % finger.fp_type)

      # Structure of the results is a list of dicts, each containing the
      # name of the hashing method, hashes for enabled hash algorithms,
      # and auxilliary data where present (e.g. signature blobs).
      # Also see Fingerprint:HashIt()
      response.results = fingerprinter.HashIt()

      # We now return data in a more structured form.
      for result in response.results:
        if result.GetItem("name") == "generic":
          for hash_type in ["md5", "sha1", "sha256"]:
            value = result.GetItem(hash_type)
            if value is not None:
              setattr(response.hash, hash_type, value)

        if result["name"] == "pecoff":
          for hash_type in ["md5", "sha1", "sha256"]:
            value = result.GetItem(hash_type)
            if value:
              setattr(response.hash, "pecoff_" + hash_type, value)

          signed_data = result.GetItem("SignedData", [])
          for data in signed_data:
            response.hash.signed_data.Append(
                revision=data[0], cert_type=data[1], certificate=data[2])

      self.SendReply(response)
266191
def fingerprint_path(cls, user, fingerprint):
        """"""
        return google.api_core.path_template.expand(
            "users/{user}/sshPublicKeys/{fingerprint}",
            user=user,
            fingerprint=fingerprint,
        )
471522
private function laterSessionStart()
    {
        if (!is_null($this->fingerprint) && !$this->fingerprint->hasValidFingerprint()) {
            throw new \Exception("Session fingerprint doesn't match"); // @codeCoverageIgnore
        }
        if (!is_null($this->expiration) && $this->expiration->isObsolete()) {
            return true;
        }
        return false;
    }
1022247
public SipStack initializeSipStack(String myTransport, String myHost, String myPort, String outboundProxy) throws Exception {
		return initializeSipStack(myTransport, myHost, myPort, outboundProxy, true, null, null, null);
	}