verifies the proxy credential
511608
public void verify() throws Exception {

        Map<String, ProxyPolicyHandler> handlers = null;
        if (proxyCertInfo != null) {
            String oid = proxyCertInfo.getProxyPolicy().getPolicyLanguage().getId();
            handlers = new HashMap<String,ProxyPolicyHandler>();
            handlers.put(oid, new ProxyPolicyHandler() {
                public void validate(ProxyCertInfo proxyCertInfo,
                         CertPath certPath,
                         int index)
                throws CertPathValidatorException {
                // ignore policy - this is just for proxy init case
                System.out.println("Proxy verify: Ignoring proxy policy");
                if (debug) {
                    String policy =
                    new String(proxyCertInfo.getProxyPolicy().getPolicy());
                    System.out.println("Policy:");
                    System.out.println(policy);
                }
              }
            });
        }

        KeyStore keyStore = Stores.getDefaultTrustStore();
        CertStore crlStore = Stores.getDefaultCRLStore();
        ResourceSigningPolicyStore sigPolStore = Stores.getDefaultSigningPolicyStore();
        X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, crlStore, sigPolStore, false, handlers);
        X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator();
        validator.engineValidate(CertificateUtil.getCertPath(proxy.getCertificateChain()), parameters);
    }
1356263
async def verify_credentials(self):
        """"""
        _, public_key = self.srp.initialize()

        msg = messages.crypto_pairing({
            tlv8.TLV_SEQ_NO: b'\x01',
            tlv8.TLV_PUBLIC_KEY: public_key})
        resp = await self.protocol.send_and_receive(
            msg, generate_identifier=False)

        resp = _get_pairing_data(resp)
        session_pub_key = resp[tlv8.TLV_PUBLIC_KEY]
        encrypted = resp[tlv8.TLV_ENCRYPTED_DATA]
        log_binary(_LOGGER,
                   'Device',
                   Public=self.credentials.ltpk,
                   Encrypted=encrypted)

        encrypted_data = self.srp.verify1(
            self.credentials, session_pub_key, encrypted)
        msg = messages.crypto_pairing({
            tlv8.TLV_SEQ_NO: b'\x03',
            tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
        resp = await self.protocol.send_and_receive(
            msg, generate_identifier=False)

        # TODO: check status code

        self._output_key, self._input_key = self.srp.verify2()
872075
def _get_instance(hosts=None, profile=None):
    '''
    
    '''
    es = None
    proxies = None
    use_ssl = False
    ca_certs = None
    verify_certs = True
    http_auth = None
    timeout = 10

    if profile is None:
        profile = 'elasticsearch'

    if isinstance(profile, six.string_types):
        _profile = __salt__['config.option'](profile, None)
    elif isinstance(profile, dict):
        _profile = profile
    if _profile:
        hosts = _profile.get('host', hosts)
        if not hosts:
            hosts = _profile.get('hosts', hosts)
        proxies = _profile.get('proxies', None)
        use_ssl = _profile.get('use_ssl', False)
        ca_certs = _profile.get('ca_certs', None)
        verify_certs = _profile.get('verify_certs', True)
        username = _profile.get('username', None)
        password = _profile.get('password', None)
        timeout = _profile.get('timeout', 10)

        if username and password:
            http_auth = (username, password)

    if not hosts:
        hosts = ['127.0.0.1:9200']
    if isinstance(hosts, six.string_types):
        hosts = [hosts]
    try:
        if proxies:
            # Custom connection class to use requests module with proxies
            class ProxyConnection(RequestsHttpConnection):
                def __init__(self, *args, **kwargs):
                    proxies = kwargs.pop('proxies', {})
                    super(ProxyConnection, self).__init__(*args, **kwargs)
                    self.session.proxies = proxies

            es = elasticsearch.Elasticsearch(
                hosts,
                connection_class=ProxyConnection,
                proxies=proxies,
                use_ssl=use_ssl,
                ca_certs=ca_certs,
                verify_certs=verify_certs,
                http_auth=http_auth,
                timeout=timeout,
            )
        else:
            es = elasticsearch.Elasticsearch(
                    hosts,
                    use_ssl=use_ssl,
                    ca_certs=ca_certs,
                    verify_certs=verify_certs,
                    http_auth=http_auth,
                    timeout=timeout,
                )

        # Try the connection
        es.info()
    except elasticsearch.exceptions.TransportError as err:
        raise CommandExecutionError(
            'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))
    return es
619437
def _verify(self, connection, cert, errorNumber, errorDepth, returnCode):
        
        try:
            user = userForCert(self.store, cert)
        except ItemNotFound:
            log.msg("Connection attempt by {0!r}, but no user with that "
                    "e-mail address was found, cert digest was {1}"
                    .format(emailForCert(cert), cert.digest("sha512")))
            return False

        digest = cert.digest("sha512")
        if user.digest is None:
            user.digest = digest
            log.msg("First connection by {0!r}, stored digest: {1}"
                    .format(user.email, digest))
            return True
        elif user.digest == digest:
            log.msg("Successful connection by {0!r}".format(user.email))
            return True
        else:
            log.msg("Failed connection by {0!r}; cert digest was {1}, "
                    "expecting {2}".format(user.email, digest, user.digest))
            return False
1175518
protected function proxy() {
        if (!$this->context) {
            $this->context = new VerificationContext(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }
1355677
private void setupProxyIfNeeded(HttpClientBuilder builder) {
        if (httpProxy != null) {
            builder.setProxy(new HttpHost(httpProxy.getHost(),httpProxy.getPort()));
            if (httpProxy.getUser() != null) {
                AuthScope proxyAuthScope = new AuthScope(httpProxy.getHost(),httpProxy.getPort());
                UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(httpProxy.getUser(),httpProxy.getPass());
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(proxyAuthScope,proxyCredentials);
                builder.setDefaultCredentialsProvider(credentialsProvider);
            }
        }
    }
1246772
def _internal_verify_cas(ticket, service, suffix):
    

    params = {'ticket': ticket, 'service': service}
    if settings.CAS_PROXY_CALLBACK:
        params['pgtUrl'] = settings.CAS_PROXY_CALLBACK

    url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' +
           urlencode(params))

    page = urlopen(url)

    username = None

    try:
        response = page.read()
        tree = ElementTree.fromstring(response)
        document = minidom.parseString(response)

        if tree[0].tag.endswith('authenticationSuccess'):
            if settings.CAS_RESPONSE_CALLBACKS:
                cas_response_callbacks(tree)

            username = tree[0][0].text

            pgt_el = document.getElementsByTagName('cas:proxyGrantingTicket')

            if pgt_el:
                pgt = pgt_el[0].firstChild.nodeValue
                try:
                    pgtIou = _get_pgtiou(pgt)
                    tgt = Tgt.objects.get(username=username)
                    tgt.tgt = pgtIou.tgt
                    tgt.save()
                    pgtIou.delete()
                except Tgt.DoesNotExist:
                    Tgt.objects.create(username=username, tgt=pgtIou.tgt)
                    logger.info('Creating TGT ticket for {user}'.format(
                        user=username
                    ))
                    pgtIou.delete()
                except Exception as e:
                    logger.warning('Failed to do proxy authentication. {message}'.format(
                        message=e
                    ))

        else:
            failure = document.getElementsByTagName('cas:authenticationFailure')
            if failure:
                logger.warn('Authentication failed from CAS server: %s',
                            failure[0].firstChild.nodeValue)

    except Exception as e:
        logger.error('Failed to verify CAS authentication: {message}'.format(
            message=e
        ))

    finally:
        page.close()

    return username
736389
def validate_proxy_args(cls, *args):
        """"""
        supplied_proxies = Counter((not arg for arg in (*args,))).get(False)
        if not supplied_proxies:
            return
        elif supplied_proxies > 1:
            raise RaccoonException("Must specify only one of the following:\n"
                                   "--tor-routing, --proxy-list, --proxy")
1126051
private function canProxy() {
        // grab the comma-delimited set of trusted proxies if they exist
        $trustedProxies = config('proxypass.trusted_proxies');
        if(empty($trustedProxies)) {
            // no proxies have been whitelisted so allow all proxy servers
            return true;
        }

        // form an array and kill any whitespace in each element
        $proxyArr = explode(",", $trustedProxies);
        array_walk($proxyArr, 'trim');

        // first we need to check the REMOTE_ADDR value to see if the IP
        // address being reported matches one of the trusted proxies
        if(!empty($_SERVER['REMOTE_ADDR'])) {
            if(in_array($_SERVER['REMOTE_ADDR'], $proxyArr)) {
                // the machine that made the request is a trusted proxy so
                // everything is fine
                return true;
            }
        }

        // now we need to check the X-Forwarded-Server header if it exists
        // since that's one of the three standard request headers that a
        // proxy would pass along with a request
        if(!empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) {
            if(in_array(trim($_SERVER['HTTP_X_FORWARDED_SERVER']), $proxyArr)) {
                // the hostname of the proxy matches a trusted proxy so
                // everything is fine
                return true;
            }
        }

        // we are either not behind a proxy or the proxy forwarding the request
        // is not in the set of trusted proxies
        return false;
    }
526559
def has_credentials(self):
        
        return all([
            getattr(self, '_%s' % field, None) is not None
            for field in self.CredentialMap.get(self.provider_name)])
811461
def verify(self, verifier, consumer_key=None, consumer_secret=None,
               access_token=None, access_token_secret=None):
        
        # Stored values can be supplied to verify
        self.consumer_key = consumer_key or self.consumer_key
        self.consumer_secret = consumer_secret or self.consumer_secret
        self.access_token = access_token or self.access_token
        self.access_token_secret = access_token_secret or self.access_token_secret

        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=self.access_token,
            resource_owner_secret=self.access_token_secret,
            verifier=verifier)
        r = requests.post(self.url('ACCESS_TOKEN'), auth=oauth)
        if r.status_code == 200:
            creds = parse_qs(r.content)
        else:
            return (False, r.content)

        self.finalize_oauth(creds.get('oauth_token')[0],
                            creds.get('oauth_token_secret')[0])
        return (True, None)
1025224
public static function isAuthenticatedProxy()
    {
        $proxyUser = self::$global->getProxyUser();
        $proxyPwd = self::$global->getProxyPassword();
        return !empty($proxyUser) && !empty($proxyPwd);
    }
971019
def Credentials(self):
		

		return(clc.v2.API.Call('GET','servers/%s/%s/credentials' % (self.alias,self.name),session=self.session))
72854
def getCert(certHost=vos.vos.SERVER, certfile=None,
            certQuery="/cred/proxyCert?daysValid=",daysValid=2):
    """"""

    if certfile is None:
        certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem")

    dirname = os.path.dirname(certfile)
    try:
        os.makedirs(dirname)
    except OSError as e:
        if os.path.isdir(dirname):
            pass
        elif e.errno == 20 or e.errno == 17:
            sys.stderr.write(str(e)+": %s \n" % dirname)
            sys.stderr.write("Expected %s to be a directory.\n" % ( dirname))
            sys.exit(e.errno)
        else:
            raise e
    
    # Example taken from voidspace.org.uk
    # create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    (username, passwd) = getUserPassword(host=certHost)

    # Add the username and password.
    # If we knew the realm, we could use it instead of ``None``.
    top_level_url = "http://"+certHost
    password_mgr.add_password(None, top_level_url, username, passwd)
    
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    
    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)
    
    # Install the opener.   
    urllib2.install_opener(opener)

    # Now all calls to urllib2.urlopen use our opener.
    url="http://"+certHost+certQuery+str(daysValid)
    r= urllib2.urlopen(url)
    w= file(certfile,'w')
    while True:
        buf=r.read()
        if not buf:
            break
        w.write(buf)
    w.close()
    r.close()
    return
226517
public void setProxy(Proxy proxy) {
        if (verifiers.removeIf(verifier -> verifier instanceof SkillRequestSignatureVerifier)) {
            verifiers.add(new SkillRequestSignatureVerifier(proxy));
        }
    }
614824
def verify1(self, credentials, session_pub_key, encrypted):
        """"""
        # No additional hashing used
        self._shared = self._verify_private.get_shared_key(
            curve25519.Public(session_pub_key), hashfunc=lambda x: x)

        session_key = hkdf_expand('Pair-Verify-Encrypt-Salt',
                                  'Pair-Verify-Encrypt-Info',
                                  self._shared)

        chacha = chacha20.Chacha20Cipher(session_key, session_key)
        decrypted_tlv = tlv8.read_tlv(
            chacha.decrypt(encrypted, nounce='PV-Msg02'.encode()))

        identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
        signature = decrypted_tlv[tlv8.TLV_SIGNATURE]

        if identifier != credentials.atv_id:
            raise Exception('incorrect device response')  # TODO: new exception

        info = session_pub_key + \
            bytes(identifier) + self._verify_public.serialize()
        ltpk = VerifyingKey(bytes(credentials.ltpk))
        ltpk.verify(bytes(signature), bytes(info))  # throws if no match

        device_info = self._verify_public.serialize() + \
            credentials.client_id + session_pub_key

        device_signature = SigningKey(credentials.ltsk).sign(device_info)

        tlv = tlv8.write_tlv({tlv8.TLV_IDENTIFIER: credentials.client_id,
                              tlv8.TLV_SIGNATURE: device_signature})

        return chacha.encrypt(tlv, nounce='PV-Msg03'.encode())
428854
def _process_credentials(self, req, resp, origin):
        
        if self._cors_config['allow_credentials_all_origins']:
            self._set_allow_credentials(resp)
            return True

        if origin in self._cors_config['allow_credentials_origins_list']:
            self._set_allow_credentials(resp)
            return True

        credentials_regex = self._cors_config['allow_credentials_origins_regex']
        if credentials_regex:
            if credentials_regex.match(origin):
                self._set_allow_credentials(resp)
                return True

        return False