Validates that the defined certificates exist
506085
def validate_certificates
      validate_each :certificates do |c|
        cert = self.grid.certificates.find_by(subject: c[:subject])
        unless cert
          [:not_found, "Certificate #{c[:subject]} does not exist"]
        else
          nil
        end
      end
    end
1323465
def validate_pipeline(conf, args):
    """"""
    host = conf.config['instances'][args.host_instance]
    host_url = api.build_pipeline_url(build_instance_url(host))
    host_auth = tuple([conf.creds['instances'][args.host_instance]['user'],
                      conf.creds['instances'][args.host_instance]['pass']])
    verify_ssl = host.get('verify_ssl', True)
    validate_result = api.validate_pipeline(host_url, args.pipeline_id, host_auth, verify_ssl)
    return validate_result
983033
def verify_gem(signature, data, chain, time = Time.now)
      Gem.ensure_ssl_available
      cert_class = OpenSSL::X509::Certificate
      exc = Gem::Security::Exception
      chain ||= []

      chain = chain.map{ |str| cert_class.new(str) }
      signer, ch_len = chain[-1], chain.size

      # make sure signature is valid
      if @verify_data
        # get digest algorithm (TODO: this should be configurable)
        dgst = @opt[:dgst_algo]

        # verify the data signature (this is the most important part, so don't
        # screw it up :D)
        v = signer.public_key.verify(dgst.new, signature, data)
        raise exc, "Invalid Gem Signature" unless v

        # make sure the signer is valid
        if @verify_signer
          # make sure the signing cert is valid right now
          v = signer.check_validity(nil, time)
          raise exc, "Invalid Signature: #{v[:desc]}" unless v[:is_valid]
        end
      end

      # make sure the certificate chain is valid
      if @verify_chain
        # iterate down over the chain and verify each certificate against it's
        # issuer
        (ch_len - 1).downto(1) do |i|
          issuer, cert = chain[i - 1, 2]
          v = cert.check_validity(issuer, time)
          raise exc, "%s: cert = '%s', error = '%s'" % [
              'Invalid Signing Chain', cert.subject, v[:desc]
          ] unless v[:is_valid]
        end

        # verify root of chain
        if @verify_root
          # make sure root is self-signed
          root = chain[0]
          raise exc, "%s: %s (subject = '%s', issuer = '%s')" % [
              'Invalid Signing Chain Root',
              'Subject does not match Issuer for Gem Signing Chain',
              root.subject.to_s,
              root.issuer.to_s,
          ] unless root.issuer.to_s == root.subject.to_s

          # make sure root is valid
          v = root.check_validity(root, time)
          raise exc, "%s: cert = '%s', error = '%s'" % [
              'Invalid Signing Chain Root', root.subject, v[:desc]
          ] unless v[:is_valid]

          # verify that the chain root is trusted
          if @only_trusted
            # get digest algorithm, calculate checksum of root.subject
            algo = @opt[:dgst_algo]
            path = Gem::Security::Policy.trusted_cert_path(root, @opt)

            # check to make sure trusted path exists
            raise exc, "%s: cert = '%s', error = '%s'" % [
                'Untrusted Signing Chain Root',
                root.subject.to_s,
                "path \"#{path}\" does not exist",
            ] unless File.exist?(path)

            # load calculate digest from saved cert file
            save_cert = OpenSSL::X509::Certificate.new(File.read(path))
            save_dgst = algo.digest(save_cert.public_key.to_s)

            # create digest of public key
            pkey_str = root.public_key.to_s
            cert_dgst = algo.digest(pkey_str)

            # now compare the two digests, raise exception
            # if they don't match
            raise exc, "%s: %s (saved = '%s', root = '%s')" % [
                'Invalid Signing Chain Root',
                "Saved checksum doesn't match root checksum",
                save_dgst, cert_dgst,
            ] unless save_dgst == cert_dgst
          end
        end

        # return the signing chain
        chain.map { |cert| cert.subject }
      end
    end
815264
def ValidateCertificateHostname(cert, hostname):
  
  hosts = GetValidHostsForCert(cert)
  boto.log.debug(
      "validating server certificate: hostname=%s, certificate hosts=%s",
      hostname, hosts)
  for host in hosts:
    host_re = host.replace('.', '\.').replace('*', '[^.]*')
    if re.search('^%s$' % (host_re,), hostname, re.I):
      return True
  return False
735733
public function validate(): PathValidationResult
    {
        $n = count($this->_certificates);
        $state = ValidatorState::initialize($this->_config, $this->_trustAnchor,
            $n);
        for ($i = 0; $i < $n; ++$i) {
            $state = $state->withIndex($i + 1);
            $cert = $this->_certificates[$i];
            // process certificate (section 6.1.3.)
            $state = $this->_processCertificate($state, $cert);
            if (!$state->isFinal()) {
                // prepare next certificate (section 6.1.4.)
                $state = $this->_prepareNext($state, $cert);
            }
        }
        if (!isset($cert)) {
            throw new \LogicException("No certificates.");
        }
        // wrap-up (section 6.1.5.)
        $state = $this->_wrapUp($state, $cert);
        // return outputs
        return $state->getResult($this->_certificates);
    }
1144823
def validate(message, **config):
    

    if not _validate_implementations:
        init(**config)

    cfg = copy.deepcopy(config)
    if 'gpg_home' not in cfg:
        cfg['gpg_home'] = os.path.expanduser('~/.gnupg/')

    if 'ssldir' not in cfg:
        cfg['ssldir'] = '/etc/pki/fedmsg'

    if 'crypto' in message:
        if not message['crypto'] in _possible_backends:
            log.warn("Message specified an impossible crypto backend")
            return False
        try:
            backend = _possible_backends[message['crypto']]
        except Exception as e:
            log.warn("Failed to load %r %r" % (message['crypto'], e))
            return False
    # fedmsg 0.7.2 and earlier did not specify which crypto backend a message
    # was signed with.  As long as we care about interoperability with those
    # versions, attempt to guess the backend to use
    elif 'certificate' in message:
        backend = x509
    elif 'signature' in message:
        backend = gpg
    else:
        log.warn('Could not determine crypto backend.  Message unsigned?')
        return False

    if backend in _validate_implementations:
        return backend.validate(message, **cfg)
    else:
        log.warn("Crypto backend %r is disallowed" % backend)
        return False
29054
def check_cert(certfile):
    
    cmd = 'openssl x509 -in {} -text -noout'.format(certfile)
    out = subprocess.check_output(cmd, shell=True)
    return out
1346384
function validate () {
  var env = state.env('NODE_ENV');
  var uri = state.env('MONGO_URI');
  var notTestEnv = env !== 'test';
  if (notTestEnv) {
    throw new Error('NODE_ENV must be set to "test".');
  }
  var notTestDb = word.test(uri) === false;
  if (notTestDb) {
    throw new Error('MONGO_URI must contain "test" word.');
  }
}
926385
def _verify_cert(self, sock: ssl.SSLSocket):
        ''''''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
832305
private void verifySignature(X509Certificate cert)
        throws CertPathValidatorException
    {
        String msg = "signature";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        try {
            if (sigProvider != null) {
                cert.verify(prevPubKey, sigProvider);
            } else {
                cert.verify(prevPubKey);
            }
        } catch (SignatureException e) {
            throw new CertPathValidatorException
                (msg + " check failed", e, null, -1,
                 BasicReason.INVALID_SIGNATURE);
        } catch (GeneralSecurityException e) {
            throw new CertPathValidatorException(msg + " check failed", e);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
631845
public String validate(KeyStore keyStore, String keyAlias) throws CertificateException {
        String result = null;
        if (keyAlias != null) {
            try {
                validate(keyStore, keyStore.getCertificate(keyAlias));
            } catch (KeyStoreException kse) {
                logger.debug("", kse);
                throw new CertificateException("Unable to validate certificate" +
                        " for alias [" + keyAlias + "]: " + kse.getMessage(), kse);
            }
            result = keyAlias;
        }
	return result;
    }
349680
def _validate(self):
        
        for key in self:
            if key not in DEFAULTS:
                raise exceptions.ConfigurationException(
                    'Unknown configuration key "{}"! Valid configuration keys are'
                    " {}".format(key, list(DEFAULTS.keys()))
                )

        validate_queues(self["queues"])
        validate_bindings(self["bindings"])
        validate_client_properties(self["client_properties"])
197589
def validate(self):
        
        assert self.path, "{} must have a path".format(self.__class__.__name__)
        _, dotext = os.path.splitext(self.path)
        ext = dotext.lstrip('.')
        # don't validate for single-digit extension, or no extension
        if len(ext) > 1:
            assert ext in self.allowed_formats, "{} must have one of the following"
            "extensions: {} (instead, got '{}' from '{}')".format(
            self.__class__.__name__, self.allowed_formats, ext, self.path)
1077956
public void validate( KeyStore keyStore ) throws CertificateException
{
    try
    {
        Enumeration<String> aliases = keyStore.aliases();
        
        for ( ; aliases.hasMoreElements(); )
        {
            String alias = aliases.nextElement();
            
            validate(keyStore,alias);
        }
        
    }
    catch ( KeyStoreException kse )
    {
        throw new CertificateException("Unable to retrieve aliases from keystore", kse);
    }
}
1012520
function validateCertChain(cert, cb)
{
  // walk up the certificate chain and collect all the certificates in an array
  var certs = [];
  while (cert && cert.issuerCertificate &&
  (cert.fingerprint !== cert.issuerCertificate.fingerprint))
  {
    certs.push(cert);
    cert = cert.issuerCertificate;
  }

  // create an array to store any errors encountered
  // while validating the certificate chain
  var errors = new Array(certs.length);

  /**
   * Called for every certificate as we traverse the certificate chain and
   * validate each one.
   *
   * @param certs
   * @param index
   */
  var eachCallback = function(certs, index)
  {
    var cert = certs[index];
    validateCert(cert, function(err, data)
    {
      completed++;
      errors[index] = err;

      // if we have an ocsp response, cache it
      if (data)
      {
        getOcspResponseCache().set(cert, data);
      }

      // if this is the last request to complete
      if (completed === certs.length)
      {
        // if we saw one or more errors, invoke the callback with the first
        // error we saw; otherwise invoke the callback without any error
        for (var errorIndex = 0, length = errors.length;
             errorIndex < length; errorIndex++)
        {
          var error = errors[errorIndex];
          if (error)
          {
            break;
          }
        }
        cb(error);
      }
    });
  };

  // fire off requests to validate all the certificates in the chain
  var completed = 0;
  for (var index = 0, length = certs.length; index < length; index++)
  {
    eachCallback(certs, index);
  }
}
993712
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException {
        Certificate[] certChain = null;
	if (cert != null && cert instanceof X509Certificate) {
            ((X509Certificate)cert).checkValidity();
            
            String certAlias = null;
            try {
                if (keyStore == null) {
                    throw new InvalidParameterException("Keystore cannot be null");
                }

                certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
                if (certAlias == null) {
                    certAlias = "CHSMPP" + String.format("%016X", aliasCount.incrementAndGet());
                    keyStore.setCertificateEntry(certAlias, cert);
                }
                
                certChain = keyStore.getCertificateChain(certAlias);
                if (certChain == null || certChain.length == 0) {
                    throw new IllegalStateException("Unable to retrieve certificate chain");
                }
            }
            catch (KeyStoreException kse) {
                logger.debug("", kse);
                throw new CertificateException("Unable to validate certificate" +
					       (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
            }
            validate(certChain);
        } 
    }
1140342
def verifyCertificate(self, name):
        
        certPath = os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name)
        if not os.path.isfile(certPath):
            raise ValueError('Certificate [%s] not found' % certPath)
        if subprocess.call([ 'openssl', 'x509', '-noout', '-text', '-in', certPath ]) != 0:
            raise ValueError('Failed to verify the certificate')