Example #1
0
int GTTruststore_addLookupDir(const char *path)
{
	int res = GT_UNKNOWN_ERROR;
	X509_LOOKUP *lookup = NULL;

	if (GT_truststore == NULL) {
		/* Create an empty trustrore. */
		res = GTTruststore_init(0);
		if (res != GT_OK) goto cleanup;
	}

	if (path == NULL) {
		res = GT_INVALID_ARGUMENT;
		goto cleanup;
	}

	lookup = X509_STORE_add_lookup(GT_truststore, X509_LOOKUP_hash_dir());
	if (lookup == NULL) {
		res = GT_OUT_OF_MEMORY;
		goto cleanup;
	}

	if (!X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM)) {
		res = GT_PKI_BAD_DATA_FORMAT;
		goto cleanup;
	}

	res = GT_OK;

cleanup:

	return res;
}
/**
 * xmlSecOpenSSLX509StoreAddCertsPath:
 * @store: the pointer to OpenSSL x509 store.
 * @path: the path to the certs dir.
 *
 * Adds all certs in the @path to the list of trusted certs
 * in @store.
 *
 * Returns: 0 on success or a negative value otherwise.
 */
int
xmlSecOpenSSLX509StoreAddCertsPath(xmlSecKeyDataStorePtr store, const char *path) {
    xmlSecOpenSSLX509StoreCtxPtr ctx;
    X509_LOOKUP *lookup = NULL;

    xmlSecAssert2(xmlSecKeyDataStoreCheckId(store, xmlSecOpenSSLX509StoreId), -1);
    xmlSecAssert2(path != NULL, -1);

    ctx = xmlSecOpenSSLX509StoreGetCtx(store);
    xmlSecAssert2(ctx != NULL, -1);
    xmlSecAssert2(ctx->xst != NULL, -1);

    lookup = X509_STORE_add_lookup(ctx->xst, X509_LOOKUP_hash_dir());
    if(lookup == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    xmlSecErrorsSafeString(xmlSecKeyDataStoreGetName(store)),
                    "X509_STORE_add_lookup",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }
    if(!X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    xmlSecErrorsSafeString(xmlSecKeyDataStoreGetName(store)),
                    "X509_LOOKUP_add_dir",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "path='%s'",
                    xmlSecErrorsSafeString(path)
        );
        return(-1);
    }
    return(0);
}
Example #3
0
X509_STORE *SSL_X509_STORE_create(char *cpFile, char *cpPath)
{
    X509_STORE *pStore;
    X509_LOOKUP *pLookup;

    if (cpFile == NULL && cpPath == NULL)
        return NULL;
    if ((pStore = X509_STORE_new()) == NULL)
        return NULL;
    if (cpFile != NULL) {
        if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())) == NULL) {
            X509_STORE_free(pStore);
            return NULL;
        }
        X509_LOOKUP_load_file(pLookup, cpFile, X509_FILETYPE_PEM);
    }
    if (cpPath != NULL) {
        if ((pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir())) == NULL) {
            X509_STORE_free(pStore);
            return NULL;
        }
        X509_LOOKUP_add_dir(pLookup, cpPath, X509_FILETYPE_PEM);
    }
    return pStore;
}
Example #4
0
/**
 * xmlSecOpenSSLX509StoreAddCertsPath:
 * @store: the pointer to OpenSSL x509 store.
 * @path: the path to the certs dir.
 *
 * Adds all certs in the @path to the list of trusted certs
 * in @store.
 *
 * Returns: 0 on success or a negative value otherwise.
 */
int
xmlSecOpenSSLX509StoreAddCertsPath(xmlSecKeyDataStorePtr store, const char *path) {
    xmlSecOpenSSLX509StoreCtxPtr ctx;
    X509_LOOKUP *lookup = NULL;

    xmlSecAssert2(xmlSecKeyDataStoreCheckId(store, xmlSecOpenSSLX509StoreId), -1);
    xmlSecAssert2(path != NULL, -1);

    ctx = xmlSecOpenSSLX509StoreGetCtx(store);
    xmlSecAssert2(ctx != NULL, -1);
    xmlSecAssert2(ctx->xst != NULL, -1);

    lookup = X509_STORE_add_lookup(ctx->xst, X509_LOOKUP_hash_dir());
    if(lookup == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_STORE_add_lookup");
        return(-1);
    }
    if(!X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM)) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_LOOKUP_add_dir");
        return(-1);
    }
    return(0);
}
Example #5
0
static X509_STORE *create_cert_store(char *ca_path, char *ca_file)
	{
	X509_STORE *cert_ctx = NULL;
	X509_LOOKUP *lookup = NULL;
	int i;

	/* Creating the X509_STORE object. */
	cert_ctx = X509_STORE_new();

	/* Setting the callback for certificate chain verification. */
	X509_STORE_set_verify_cb(cert_ctx, verify_cb);

	/* Adding a trusted certificate directory source. */
	if (ca_path)
		{
		lookup = X509_STORE_add_lookup(cert_ctx,
					       X509_LOOKUP_hash_dir());
		if (lookup == NULL)
			{
			BIO_printf(bio_err, "memory allocation failure\n");
			goto err;
			}
		i = X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM);
		if (!i)
			{
			BIO_printf(bio_err, "Error loading directory %s\n",
				   ca_path);
			goto err;
			}
		}

	/* Adding a trusted certificate file source. */
	if (ca_file)
		{
		lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
		if (lookup == NULL)
			{
			BIO_printf(bio_err, "memory allocation failure\n");
			goto err;
			}
		i = X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM);
		if (!i)
			{
			BIO_printf(bio_err, "Error loading file %s\n", ca_file);
			goto err;
			}
		}

	return cert_ctx;
 err:
	X509_STORE_free(cert_ctx);
	return NULL;
	}
Example #6
0
boolean x509_verify_cert(CryptoCert cert, rdpSettings* settings)
{
	char* cert_loc;
	X509_STORE_CTX* csc;
	boolean status = false;
	X509_STORE* cert_ctx = NULL;
	X509_LOOKUP* lookup = NULL;
	X509* xcert = cert->px509;

	cert_ctx = X509_STORE_new();

	if (cert_ctx == NULL)
		goto end;

	OpenSSL_add_all_algorithms();
	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());

	if (lookup == NULL)
		goto end;

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());

	if (lookup == NULL)
		goto end;

	X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
	cert_loc = get_local_certloc(settings->home_path);

	if(cert_loc != NULL)
	{
		X509_LOOKUP_add_dir(lookup, cert_loc, X509_FILETYPE_ASN1);
		xfree(cert_loc);
	}

	csc = X509_STORE_CTX_new();

	if (csc == NULL)
		goto end;

	X509_STORE_set_flags(cert_ctx, 0);

	if(!X509_STORE_CTX_init(csc, cert_ctx, xcert, 0))
		goto end;

	if (X509_verify_cert(csc) == 1)
		status = true;

	X509_STORE_CTX_free(csc);
	X509_STORE_free(cert_ctx);

end:
	return status;
}
Example #7
0
static X509_STORE *
setup_verify(char *CAfile, char *CApath)
{
    X509_STORE *store = NULL;
    X509_LOOKUP *lookup = NULL;

    if(!(store = X509_STORE_new())){
        // Something bad is happening...
        goto end;
    }

    // adds the X509 file lookup method
    lookup = X509_STORE_add_lookup(store,X509_LOOKUP_file());
    if (lookup == NULL){
        goto end;
    }

    // Autenticating against one CA file
    if (CAfile) {
        if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
            // Invalid CA => Bye bye
            opkg_msg(ERROR, "Error loading file %s.\n", CAfile);
            goto end;
        }
    } else {
        X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
    }

    // Now look into CApath directory if supplied
    lookup = X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
    if (lookup == NULL){
        goto end;
    }

    if (CApath) {
        if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
            opkg_msg(ERROR, "Error loading directory %s.\n", CApath);
            goto end;
        }
    } else {
        X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
    }

    // All right !
    ERR_clear_error();
    return store;

end:

    X509_STORE_free(store);
    return NULL;

}
Example #8
0
BOOL x509_verify_certificate(CryptoCert cert, char* certificate_store_path)
{
	X509_STORE_CTX* csc;
	BOOL status = FALSE;
	X509_STORE* cert_ctx = NULL;
	X509_LOOKUP* lookup = NULL;
	X509* xcert = cert->px509;

	cert_ctx = X509_STORE_new();

	if (cert_ctx == NULL)
		goto end;

	OpenSSL_add_all_algorithms();
	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());

	if (lookup == NULL)
		goto end;

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());

	if (lookup == NULL)
		goto end;

	X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

	if (certificate_store_path != NULL)
	{
		X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_ASN1);
	}

	csc = X509_STORE_CTX_new();

	if (csc == NULL)
		goto end;

	X509_STORE_set_flags(cert_ctx, 0);

	if (!X509_STORE_CTX_init(csc, cert_ctx, xcert, 0))
		goto end;

	if (X509_verify_cert(csc) == 1)
		status = TRUE;

	X509_STORE_CTX_free(csc);
	X509_STORE_free(cert_ctx);

end:
	return status;
}
static X509_LOOKUP_METHOD *
get_lookup_method (MonoBtlsX509LookupType type)
{
    switch (type) {
    case MONO_BTLS_X509_LOOKUP_TYPE_FILE:
        return X509_LOOKUP_file ();
    case MONO_BTLS_X509_LOOKUP_TYPE_HASH_DIR:
        return X509_LOOKUP_hash_dir ();
    case MONO_BTLS_X509_LOOKUP_TYPE_MONO:
        return mono_btls_x509_lookup_mono_method ();
    default:
        return NULL;
    }
}
Example #10
0
static int add_dir_lookup(X509_STORE *store, char *name) {
    X509_LOOKUP *lookup;

    lookup=X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
    if(!lookup) {
        sslerror("X509_STORE_add_lookup");
        return 0;
    }
    if(!X509_LOOKUP_add_dir(lookup, name, X509_FILETYPE_PEM)) {
        s_log(LOG_ERR, "Failed to add %s revocation lookup directory", name);
        sslerror("X509_LOOKUP_add_dir");
        return 0;
    }
    s_log(LOG_DEBUG, "Added %s revocation lookup directory", name);
    return 1; /* OK */
}
Example #11
0
int X509_STORE_set_default_paths(X509_STORE *ctx)
	{
	X509_LOOKUP *lookup;

	lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_file());
	if (lookup == NULL) return(0);
	X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);

	lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_hash_dir());
	if (lookup == NULL) return(0);
	X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
	
	/* clear any errors */
	ERR_clear_error();

	return(1);
	}
Example #12
0
File: ssl.c Project: UIKit0/picogui
static int
_SSL_verify_x509(X509 *x509)
{
	X509_STORE *cert_ctx = NULL;
	X509_LOOKUP *lookup = NULL;
	X509_STORE_CTX csc;
	int i;


	if (!(cert_ctx = X509_STORE_new())) {
		fprintf(stderr, "_SSL_verify_x509 :: X509_STORE_new failed\n");
		exit(1);
	}
	/* X509_STORE_set_verify_cb_func(cert_ctx, cb); */

/*
	if (!(lookup = X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_file()))) {
		fprintf(stderr, "_SSL_verify_x509 :: X509_STORE_add_lookup failed\n");
		exit(1);
	}
	if (!X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT)) {
		fprintf(stderr, "_SSL_verify_x509 :: X509_LOOKUP_load_file failed\n");
		exit(1);
	}
*/

	if (!(lookup = X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_hash_dir()))) {
		fprintf(stderr, "_SSL_verify_x509 :: X509_STORE_add_lookup failed\n");
		exit(1);
	}
	if (!!X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT)) {
		fprintf(stderr, "_SSL_verify_x509 :: X509_LOOKUP_add_dir failed\n");
		exit(1);
	}

	/* ... */
	X509_STORE_CTX_init(&csc, cert_ctx, x509, NULL);
	i = X509_verify_cert(&csc);
	X509_STORE_CTX_cleanup(&csc);
	/* ... */

	X509_STORE_free(cert_ctx);

	return (i);
}
Example #13
0
static X509_STORE *create_cert_store(char *CApath, char *CAfile, X509_VERIFY_PARAM *vpm)
{
    X509_STORE *cert_ctx = NULL;
    X509_LOOKUP *lookup = NULL;
    int i;

    cert_ctx = X509_STORE_new();
    X509_STORE_set_verify_cb(cert_ctx, verify_cb);
    if (CApath != NULL) {
        lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
        if (lookup == NULL) {
            BIO_printf(bio_err, "memory allocation failure\n");
            goto err;
        }
        i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
        if (!i) {
            BIO_printf(bio_err, "Error loading directory %s\n", CApath);
            goto err;
        }
    }

    if (CAfile != NULL) {
        lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
        if (lookup == NULL) {
            BIO_printf(bio_err, "memory allocation failure\n");
            goto err;
        }
        i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
        if (!i) {
            BIO_printf(bio_err, "Error loading file %s\n", CAfile);
            goto err;
        }
    }

    if (vpm != NULL)
        X509_STORE_set1_param(cert_ctx, vpm);

    return cert_ctx;

 err:
    X509_STORE_free(cert_ctx);
    return NULL;
}
Example #14
0
static VALUE 
ossl_x509store_add_path(VALUE self, VALUE dir)
{
    X509_STORE *store;
    X509_LOOKUP *lookup;
    char *path = NULL;

    if(dir != Qnil){
        Check_SafeStr(dir);
	path = RSTRING_PTR(dir);
    }
    GetX509Store(self, store);
    lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
    if(lookup == NULL) ossl_raise(eX509StoreError, NULL);
    if(X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) != 1){
        ossl_raise(eX509StoreError, NULL);
    }

    return self;
}
int verify_certificate (const char* certfile, const char* ca_cert)
{
	X509_STORE *cert_ctx=NULL;
	X509_LOOKUP *lookup=NULL;

	cert_ctx=X509_STORE_new();
	if (!cert_ctx)
		return 0;

	OpenSSL_add_all_algorithms();

	lookup=X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_file());
	if (!lookup)
	{
		if (cert_ctx)
			X509_STORE_free(cert_ctx);
		return 0;
	}

	if(!X509_LOOKUP_load_file(lookup,ca_cert,X509_FILETYPE_PEM))
	{
		if (cert_ctx)
			X509_STORE_free(cert_ctx);
		return 0;
	}

	lookup=X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_hash_dir());
	if (!lookup)
	{
		if (cert_ctx)
			X509_STORE_free(cert_ctx);
		return 0;
	}

	X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);

	return check(cert_ctx, certfile);
}
Example #16
0
int X509_STORE_load_locations(X509_STORE *ctx, const char *file,
		const char *path)
	{
	X509_LOOKUP *lookup;

	if (file != NULL)
		{
		lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_file());
		if (lookup == NULL) return(0);
		if (X509_LOOKUP_load_file(lookup,file,X509_FILETYPE_PEM) != 1)
		    return(0);
		}
	if (path != NULL)
		{
		lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_hash_dir());
		if (lookup == NULL) return(0);
		if (X509_LOOKUP_add_dir(lookup,path,X509_FILETYPE_PEM) != 1)
		    return(0);
		}
	if ((path == NULL) && (file == NULL))
		return(0);
	return(1);
	}
Example #17
0
static X509_STORE *
read_cacerts(char *file)
{
	X509_STORE *store;
	X509_LOOKUP *lookup;

	if ((store = X509_STORE_new()) == NULL) {
		warnx("Malloc failed");
		goto end;
	}
	if ((lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())) ==
	    NULL) {
		warnx("Unable to load CA certs from file %s", file);
		goto end;
	}
	if (file) {
		if (!X509_LOOKUP_load_file(lookup, file, X509_FILETYPE_PEM)) {
			warnx("Unable to load CA certs from file %s", file);
			goto end;
		}
	} else
		X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);

	if ((lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir())) ==
	    NULL) {
		warnx("Unable to load CA certs from file %s", file);
		goto end;
	}
	X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
	ERR_clear_error();
	return store;

end:
	X509_STORE_free(store);
	return NULL;
}
Example #18
0
API int nc_tls_init(const char* peer_cert, const char* peer_key, const char *CAfile, const char *CApath, const char *CRLfile, const char *CRLpath)
{
	const char* key_ = peer_key;
	SSL_CTX* tls_ctx;
	X509_LOOKUP* lookup;
	X509_STORE* tls_store;
	int destroy = 0, ret;

	if (peer_cert == NULL) {
		ERROR("%s: Invalid parameter.", __func__);
		return (EXIT_FAILURE);
	}

	pthread_once(&tls_ctx_once, tls_ctx_init);

	tls_ctx = pthread_getspecific(tls_ctx_key);
	if (tls_ctx) {
		VERB("TLS subsystem reinitiation. Resetting certificates settings");
		/*
		 * continue with creation of a new TLS context, the current will be
		 * destroyed after everything successes
		 */
		destroy = 1;
	}

	/* prepare global SSL context, allow only mandatory TLS 1.2  */
	if ((tls_ctx = SSL_CTX_new(TLSv1_2_client_method())) == NULL) {
		ERROR("Unable to create OpenSSL context (%s)", ERR_reason_error_string(ERR_get_error()));
		return (EXIT_FAILURE);
	}

	/* force peer certificate verification (NO_PEER_CERT and CLIENT_ONCE are ignored when
	 * acting as client, but included just in case) and optionaly set CRL checking callback */
	if (CRLfile != NULL || CRLpath != NULL) {
		/* set the revocation store with the correct paths for the callback */
		tls_store = X509_STORE_new();
		tls_store->cache = 0;

		if (CRLfile != NULL) {
			if ((lookup = X509_STORE_add_lookup(tls_store, X509_LOOKUP_file())) == NULL) {
				ERROR("Failed to add lookup method in CRL checking");
				return (EXIT_FAILURE);
			}
			if (X509_LOOKUP_add_dir(lookup, CRLfile, X509_FILETYPE_PEM) != 1) {
				ERROR("Failed to add revocation lookup file");
				return (EXIT_FAILURE);
			}
		}

		if (CRLpath != NULL) {
			if ((lookup = X509_STORE_add_lookup(tls_store, X509_LOOKUP_hash_dir())) == NULL) {
				ERROR("Failed to add lookup method in CRL checking");
				return (EXIT_FAILURE);
			}
			if (X509_LOOKUP_add_dir(lookup, CRLpath, X509_FILETYPE_PEM) != 1) {
				ERROR("Failed to add revocation lookup directory");
				return (EXIT_FAILURE);
			}
		}

		if ((ret = pthread_key_create(&tls_store_key, (void (*)(void *))X509_STORE_free)) != 0) {
			ERROR("Unable to create pthread key: %s", strerror(ret));
			return (EXIT_FAILURE);
		}
		if ((ret = pthread_setspecific(tls_store_key, tls_store)) != 0) {
			ERROR("Unable to set thread-specific data: %s", strerror(ret));
			return (EXIT_FAILURE);
		}

		SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, verify_callback);
	} else {
		/* CRL checking will be skipped */
		SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, NULL);
	}

	/* get peer certificate */
	if (SSL_CTX_use_certificate_file(tls_ctx, peer_cert, SSL_FILETYPE_PEM) != 1) {
		ERROR("Loading a peer certificate from \'%s\' failed (%s).", peer_cert, ERR_reason_error_string(ERR_get_error()));
		return (EXIT_FAILURE);
	}

	if (key_ == NULL) {
		/*
		 * if the file with private key not specified, expect that the private
		 * key is stored altogether with the certificate
		 */
		key_ = peer_cert;
	}
	if (SSL_CTX_use_PrivateKey_file(tls_ctx, key_, SSL_FILETYPE_PEM) != 1) {
		ERROR("Loading a peer certificate from \'%s\' failed (%s).", key_, ERR_reason_error_string(ERR_get_error()));
		return (EXIT_FAILURE);
	}

	if(! SSL_CTX_load_verify_locations(tls_ctx, CAfile, CApath))	{
		WARN("SSL_CTX_load_verify_locations() failed (%s).", ERR_reason_error_string(ERR_get_error()));
	}

	/* store TLS context for thread */
	if (destroy) {
		nc_tls_destroy();
	}
	pthread_setspecific(tls_ctx_key, tls_ctx);

	return (EXIT_SUCCESS);
}
Example #19
0
int checkCert(X509 *cert, char *CAfile, char *CApath)
{
  X509_STORE *cert_ctx   = NULL;

  int i;
#if 0 /* FUTURE EXPANSION OF CAPABILITIES  1 */
  int purpose = -1;
  char *untfile   = NULL;
  char *trustfile = NULL;
  STACK_OF(X509) *untrusted = NULL;
  STACK_OF(X509) *trusted   = NULL;
#endif
  X509_LOOKUP *lookup    = NULL;

  cert_ctx = X509_STORE_new();

  if (cert_ctx == NULL)
    goto end;

  lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());

  if (lookup == NULL)
    return 123456;

  if (CAfile)
    {
      i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
      if (!i)
        {
          fprintf(stderr, "Error loading file %s\n", CAfile);
          goto end;
        }
    }
  else
    {
      X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
    }

  lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());

  if (lookup == NULL)
    return 123456;

  if (CApath)
    {
      i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
      if (!i)
        {
          fprintf(stderr, "Error loading directory %s\n", CApath);
          goto end;
		}
	}
  else
    X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

#if 0 /* FUTURE EXPANSION OF CAPABILITIES  1 */
  if (untfile)
    {
      if (!(untrusted = load_untrusted(untfile)))
        {
          fprintf(stderr, "Error loading untrusted file %s\n", untfile);
          goto end;
        }
	}

	if (trustfile)
      {
		if (!(trusted = load_untrusted(trustfile)))
          {
			fprintf(stderr, "Error loading untrusted file %s\n", trustfile);
			goto end;
          }
      }

    check(cert_ctx, cert, untrusted, trusted, purpose);
#endif

 end:

	if (cert_ctx != NULL)
      X509_STORE_free(cert_ctx);

#if 0 /* FUTURE EXPANSION OF CAPABILITIES  1 */
	sk_X509_pop_free(untrusted, X509_free);
	sk_X509_pop_free(trusted, X509_free);
#endif

    return 0;
}
Example #20
0
void
tls_ctx_load_ca (struct tls_root_ctx *ctx, const char *ca_file,
    const char *ca_file_inline,
    const char *ca_path, bool tls_server
    )
{
  STACK_OF(X509_INFO) *info_stack = NULL;
  STACK_OF(X509_NAME) *cert_names = NULL;
  X509_LOOKUP *lookup = NULL;
  X509_STORE *store = NULL;
  X509_NAME *xn = NULL;
  BIO *in = NULL;
  int i, added = 0;

  ASSERT(NULL != ctx);

  store = SSL_CTX_get_cert_store(ctx->ctx);
  if (!store)
    msg(M_SSLERR, "Cannot get certificate store (SSL_CTX_get_cert_store)");

  /* Try to add certificates and CRLs from ca_file */
  if (ca_file)
    {
      if (!strcmp (ca_file, INLINE_FILE_TAG) && ca_file_inline)
        in = BIO_new_mem_buf ((char *)ca_file_inline, -1);
      else
        in = BIO_new_file (ca_file, "r");

      if (in)
        info_stack = PEM_X509_INFO_read_bio (in, NULL, NULL, NULL);

      if (info_stack)
        {
          for (i = 0; i < sk_X509_INFO_num (info_stack); i++)
            {
              X509_INFO *info = sk_X509_INFO_value (info_stack, i);
              if (info->crl)
                  X509_STORE_add_crl (store, info->crl);

              if (info->x509)
                {
                  X509_STORE_add_cert (store, info->x509);
                  added++;

                  if (!tls_server)
                    continue;

                  /* Use names of CAs as a client CA list */
                  if (cert_names == NULL)
                    {
                      cert_names = sk_X509_NAME_new (sk_x509_name_cmp);
                      if (!cert_names)
                        continue;
                    }

                  xn = X509_get_subject_name (info->x509);
                  if (!xn)
                    continue;

                  /* Don't add duplicate CA names */
                  if (sk_X509_NAME_find (cert_names, xn) == -1)
                    {
                      xn = X509_NAME_dup (xn);
                      if (!xn)
                        continue;
                      sk_X509_NAME_push (cert_names, xn);
                    }
                }
            }
          sk_X509_INFO_pop_free (info_stack, X509_INFO_free);
        }

      if (tls_server)
        SSL_CTX_set_client_CA_list (ctx->ctx, cert_names);

      if (!added || (tls_server && sk_X509_NAME_num (cert_names) != added))
        msg (M_SSLERR, "Cannot load CA certificate file %s", np(ca_file));
      if (in)
        BIO_free (in);
    }

  /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
  if (ca_path)
    {
      lookup = X509_STORE_add_lookup (store, X509_LOOKUP_hash_dir ());
      if (lookup && X509_LOOKUP_add_dir (lookup, ca_path, X509_FILETYPE_PEM))
        msg(M_WARN, "WARNING: experimental option --capath %s", ca_path);
      else
        msg(M_SSLERR, "Cannot add lookup at --capath %s", ca_path);
#if OPENSSL_VERSION_NUMBER >= 0x00907000L
      X509_STORE_set_flags (store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
#else
      msg(M_WARN, "WARNING: this version of OpenSSL cannot handle CRL files in capath");
#endif
    }
}
int MAIN(int argc, char **argv)
{
    X509_CRL *x=NULL;
    char *CAfile = NULL, *CApath = NULL;
    int ret=1,i,num,badops=0;
    BIO *out=NULL;
    int informat,outformat;
    char *infile=NULL,*outfile=NULL;
    int hash=0,issuer=0,lastupdate=0,nextupdate=0,noout=0,text=0;
    int fingerprint = 0;
    char **pp,buf[256];
    X509_STORE *store = NULL;
    X509_STORE_CTX ctx;
    X509_LOOKUP *lookup = NULL;
    X509_OBJECT xobj;
    EVP_PKEY *pkey;
    int do_ver = 0;
    const EVP_MD *md_alg,*digest=EVP_md5();

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err=BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

    if (bio_out == NULL)
        if ((bio_out=BIO_new(BIO_s_file())) != NULL)
        {
            BIO_set_fp(bio_out,stdout,BIO_NOCLOSE);
#ifdef VMS
            {
                BIO *tmpbio = BIO_new(BIO_f_linebuffer());
                bio_out = BIO_push(tmpbio, bio_out);
            }
#endif
        }

    informat=FORMAT_PEM;
    outformat=FORMAT_PEM;

    argc--;
    argv++;
    num=0;
    while (argc >= 1)
    {
#ifdef undef
        if	(strcmp(*argv,"-p") == 0)
        {
            if (--argc < 1) goto bad;
            if (!args_from_file(++argv,Nargc,Nargv)) {
                goto end;
            }*/
        }
#endif
        if 	(strcmp(*argv,"-inform") == 0)
        {
            if (--argc < 1) goto bad;
            informat=str2fmt(*(++argv));
        }
        else if (strcmp(*argv,"-outform") == 0)
        {
            if (--argc < 1) goto bad;
            outformat=str2fmt(*(++argv));
        }
        else if (strcmp(*argv,"-in") == 0)
        {
            if (--argc < 1) goto bad;
            infile= *(++argv);
        }
        else if (strcmp(*argv,"-out") == 0)
        {
            if (--argc < 1) goto bad;
            outfile= *(++argv);
        }
        else if (strcmp(*argv,"-CApath") == 0)
        {
            if (--argc < 1) goto bad;
            CApath = *(++argv);
            do_ver = 1;
        }
        else if (strcmp(*argv,"-CAfile") == 0)
        {
            if (--argc < 1) goto bad;
            CAfile = *(++argv);
            do_ver = 1;
        }
        else if (strcmp(*argv,"-verify") == 0)
            do_ver = 1;
        else if (strcmp(*argv,"-text") == 0)
            text = 1;
        else if (strcmp(*argv,"-hash") == 0)
            hash= ++num;
        else if (strcmp(*argv,"-issuer") == 0)
            issuer= ++num;
        else if (strcmp(*argv,"-lastupdate") == 0)
            lastupdate= ++num;
        else if (strcmp(*argv,"-nextupdate") == 0)
            nextupdate= ++num;
        else if (strcmp(*argv,"-noout") == 0)
            noout= ++num;
        else if (strcmp(*argv,"-fingerprint") == 0)
            fingerprint= ++num;
        else if ((md_alg=EVP_get_digestbyname(*argv + 1)))
        {
            /* ok */
            digest=md_alg;
        }
        else
        {
            BIO_printf(bio_err,"unknown option %s\n",*argv);
            badops=1;
            break;
        }
        argc--;
        argv++;
    }

    if (badops)
    {
bad:
        for (pp=crl_usage; (*pp != NULL); pp++)
            BIO_printf(bio_err,*pp);
        goto end;
    }

    ERR_load_crypto_strings();
    x=load_crl(infile,informat);
    if (x == NULL) {
        goto end;
    }

    if(do_ver) {
        store = X509_STORE_new();
        lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
        if (lookup == NULL) goto end;
        if (!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM))
            X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);

        lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
        if (lookup == NULL) goto end;
        if (!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM))
            X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
        ERR_clear_error();

        X509_STORE_CTX_init(&ctx, store, NULL, NULL);

        i = X509_STORE_get_by_subject(&ctx, X509_LU_X509,
                                      X509_CRL_get_issuer(x), &xobj);
        if(i <= 0) {
            BIO_printf(bio_err,
                       "Error getting CRL issuer certificate\n");
            goto end;
        }
        pkey = X509_get_pubkey(xobj.data.x509);
        X509_OBJECT_free_contents(&xobj);
        if(!pkey) {
            BIO_printf(bio_err,
                       "Error getting CRL issuer public key\n");
            goto end;
        }
        i = X509_CRL_verify(x, pkey);
        EVP_PKEY_free(pkey);
        if(i < 0) goto end;
        if(i == 0) BIO_printf(bio_err, "verify failure\n");
        else BIO_printf(bio_err, "verify OK\n");
    }

    if (num)
    {
        for (i=1; i<=num; i++)
        {
            if (issuer == i)
            {
                X509_NAME_oneline(X509_CRL_get_issuer(x),
                                  buf,256);
                BIO_printf(bio_out,"issuer= %s\n",buf);
            }

            if (hash == i)
            {
                BIO_printf(bio_out,"%08lx\n",
                           X509_NAME_hash(X509_CRL_get_issuer(x)));
            }
            if (lastupdate == i)
            {
                BIO_printf(bio_out,"lastUpdate=");
                ASN1_TIME_print(bio_out,
                                X509_CRL_get_lastUpdate(x));
                BIO_printf(bio_out,"\n");
            }
            if (nextupdate == i)
            {
                BIO_printf(bio_out,"nextUpdate=");
                if (X509_CRL_get_nextUpdate(x))
                    ASN1_TIME_print(bio_out,
                                    X509_CRL_get_nextUpdate(x));
                else
                    BIO_printf(bio_out,"NONE");
                BIO_printf(bio_out,"\n");
            }
            if (fingerprint == i)
            {
                int j;
                unsigned int n;
                unsigned char md[EVP_MAX_MD_SIZE];

                if (!X509_CRL_digest(x,digest,md,&n))
                {
                    BIO_printf(bio_err,"out of memory\n");
                    goto end;
                }
                BIO_printf(bio_out,"%s Fingerprint=",
                           OBJ_nid2sn(EVP_MD_type(digest)));
                for (j=0; j<(int)n; j++)
                {
                    BIO_printf(bio_out,"%02X%c",md[j],
                               (j+1 == (int)n)
                               ?'\n':':');
                }
            }
        }
    }

    out=BIO_new(BIO_s_file());
    if (out == NULL)
    {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (outfile == NULL)
    {
        BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef VMS
        {
            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
            out = BIO_push(tmpbio, out);
        }
#endif
    }
    else
    {
        if (BIO_write_filename(out,outfile) <= 0)
        {
            perror(outfile);
            goto end;
        }
    }

    if (text) X509_CRL_print(out, x);

    if (noout) goto end;

    if 	(outformat == FORMAT_ASN1)
        i=(int)i2d_X509_CRL_bio(out,x);
    else if (outformat == FORMAT_PEM)
        i=PEM_write_bio_X509_CRL(out,x);
    else
    {
        BIO_printf(bio_err,"bad output format specified for outfile\n");
        goto end;
    }
    if (!i) {
        BIO_printf(bio_err,"unable to write CRL\n");
        goto end;
    }
    ret=0;
end:
    BIO_free_all(out);
    BIO_free_all(bio_out);
    bio_out=NULL;
    X509_CRL_free(x);
    if(store) {
        X509_STORE_CTX_cleanup(&ctx);
        X509_STORE_free(store);
    }
    EXIT(ret);
}
Example #22
0
int
crl_main(int argc, char **argv)
{
	unsigned long nmflag = 0;
	X509_CRL *x = NULL;
	int ret = 1, i;
	BIO *out = NULL;
	X509_STORE *store = NULL;
	X509_STORE_CTX ctx;
	X509_LOOKUP *lookup = NULL;
	X509_OBJECT xobj;
	EVP_PKEY *pkey;
	const EVP_MD *digest;
	char *digest_name = NULL;

	if (single_execution) {
		if (pledge("stdio cpath wpath rpath", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	if (bio_out == NULL) {
		if ((bio_out = BIO_new(BIO_s_file())) != NULL) {
			BIO_set_fp(bio_out, stdout, BIO_NOCLOSE);
		}
	}

	digest = EVP_sha256();

	memset(&crl_config, 0, sizeof(crl_config));
	crl_config.informat = FORMAT_PEM;
	crl_config.outformat = FORMAT_PEM;

	if (options_parse(argc, argv, crl_options, &digest_name, NULL) != 0) {
		crl_usage();
		goto end;
	}

	if (crl_config.cafile != NULL || crl_config.capath != NULL)
		crl_config.verify = 1;

	if (crl_config.nameopt != NULL) {
		if (set_name_ex(&nmflag, crl_config.nameopt) != 1) {
			fprintf(stderr,
			    "Invalid -nameopt argument '%s'\n",
			    crl_config.nameopt);
			goto end;
		}
	}

	if (digest_name != NULL) {
		if ((digest = EVP_get_digestbyname(digest_name)) == NULL) {
			fprintf(stderr,
			    "Unknown message digest algorithm '%s'\n",
			    digest_name);
			goto end;
		}
	}

	x = load_crl(crl_config.infile, crl_config.informat);
	if (x == NULL)
		goto end;

	if (crl_config.verify) {
		store = X509_STORE_new();
		lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
		if (lookup == NULL)
			goto end;
		if (!X509_LOOKUP_load_file(lookup, crl_config.cafile,
		    X509_FILETYPE_PEM))
			X509_LOOKUP_load_file(lookup, NULL,
			    X509_FILETYPE_DEFAULT);

		lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
		if (lookup == NULL)
			goto end;
		if (!X509_LOOKUP_add_dir(lookup, crl_config.capath,
		    X509_FILETYPE_PEM))
			X509_LOOKUP_add_dir(lookup, NULL,
			    X509_FILETYPE_DEFAULT);
		ERR_clear_error();

		if (!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) {
			BIO_printf(bio_err,
			    "Error initialising X509 store\n");
			goto end;
		}
		i = X509_STORE_get_by_subject(&ctx, X509_LU_X509,
		    X509_CRL_get_issuer(x), &xobj);
		if (i <= 0) {
			BIO_printf(bio_err,
			    "Error getting CRL issuer certificate\n");
			goto end;
		}
		pkey = X509_get_pubkey(xobj.data.x509);
		X509_OBJECT_free_contents(&xobj);
		if (!pkey) {
			BIO_printf(bio_err,
			    "Error getting CRL issuer public key\n");
			goto end;
		}
		i = X509_CRL_verify(x, pkey);
		EVP_PKEY_free(pkey);
		if (i < 0)
			goto end;
		if (i == 0)
			BIO_printf(bio_err, "verify failure\n");
		else
			BIO_printf(bio_err, "verify OK\n");
	}

	/* Print requested information the order that the flags were given. */
	for (i = 1; i <= argc; i++) {
		if (crl_config.issuer == i) {
			print_name(bio_out, "issuer=",
			    X509_CRL_get_issuer(x), nmflag);
		}
		if (crl_config.crlnumber == i) {
			ASN1_INTEGER *crlnum;
			crlnum = X509_CRL_get_ext_d2i(x,
			    NID_crl_number, NULL, NULL);
			BIO_printf(bio_out, "crlNumber=");
			if (crlnum) {
				i2a_ASN1_INTEGER(bio_out, crlnum);
				ASN1_INTEGER_free(crlnum);
			} else
				BIO_puts(bio_out, "<NONE>");
			BIO_printf(bio_out, "\n");
		}
		if (crl_config.hash == i) {
			BIO_printf(bio_out, "%08lx\n",
			    X509_NAME_hash(X509_CRL_get_issuer(x)));
		}
#ifndef OPENSSL_NO_MD5
		if (crl_config.hash_old == i) {
			BIO_printf(bio_out, "%08lx\n",
			    X509_NAME_hash_old(X509_CRL_get_issuer(x)));
		}
#endif
		if (crl_config.lastupdate == i) {
			BIO_printf(bio_out, "lastUpdate=");
			ASN1_TIME_print(bio_out,
			    X509_CRL_get_lastUpdate(x));
			BIO_printf(bio_out, "\n");
		}
		if (crl_config.nextupdate == i) {
			BIO_printf(bio_out, "nextUpdate=");
			if (X509_CRL_get_nextUpdate(x))
				ASN1_TIME_print(bio_out,
				    X509_CRL_get_nextUpdate(x));
			else
				BIO_printf(bio_out, "NONE");
			BIO_printf(bio_out, "\n");
		}
		if (crl_config.fingerprint == i) {
			int j;
			unsigned int n;
			unsigned char md[EVP_MAX_MD_SIZE];

			if (!X509_CRL_digest(x, digest, md, &n)) {
				BIO_printf(bio_err, "out of memory\n");
				goto end;
			}
			BIO_printf(bio_out, "%s Fingerprint=",
			    OBJ_nid2sn(EVP_MD_type(digest)));
			for (j = 0; j < (int) n; j++) {
				BIO_printf(bio_out, "%02X%c", md[j],
				    (j + 1 == (int)n) ? '\n' : ':');
			}
		}
	}

	out = BIO_new(BIO_s_file());
	if (out == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (crl_config.outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, crl_config.outfile) <= 0) {
			perror(crl_config.outfile);
			goto end;
		}
	}

	if (crl_config.text)
		X509_CRL_print(out, x);

	if (crl_config.noout) {
		ret = 0;
		goto end;
	}
	if (crl_config.outformat == FORMAT_ASN1)
		i = (int) i2d_X509_CRL_bio(out, x);
	else if (crl_config.outformat == FORMAT_PEM)
		i = PEM_write_bio_X509_CRL(out, x);
	else {
		BIO_printf(bio_err,
		    "bad output format specified for outfile\n");
		goto end;
	}
	if (!i) {
		BIO_printf(bio_err, "unable to write CRL\n");
		goto end;
	}
	ret = 0;

 end:
	BIO_free_all(out);
	BIO_free_all(bio_out);
	bio_out = NULL;
	X509_CRL_free(x);
	if (store) {
		X509_STORE_CTX_cleanup(&ctx);
		X509_STORE_free(store);
	}

	return (ret);
}
Example #23
0
int myproxy_ocsp_verify(X509 *cert, X509 *issuer) {
  BIO                   *bio = 0;
  int                   rc, reason, ssl, status;
  char                  *host = 0, *path = 0, *port = 0, *certdir = 0;
  char                  *aiaocspurl = 0, *chosenurl = 0;
  SSL_CTX               *ctx = 0;
  X509_LOOKUP           *lookup = NULL;
  X509_STORE            *store = 0;
  OCSP_CERTID           *id;
  OCSP_REQUEST          *req = 0;
  OCSP_RESPONSE         *resp = 0;
  OCSP_BASICRESP        *basic = 0;
  myproxy_ocspresult_t  result;
  ASN1_GENERALIZEDTIME  *producedAt, *thisUpdate, *nextUpdate;
  globus_result_t       res;

  if (!policy && !responder_url) {
      result = MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED;
      goto end;
  }

  result = MYPROXY_OCSPRESULT_ERROR_UNKNOWN;

  if (policy && strstr(policy, "aia")) {
      aiaocspurl = myproxy_get_aia_ocsp_uri(cert);
  }

  if (!responder_url && !aiaocspurl) {
      result = MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED;
      goto end;
  }

  chosenurl = aiaocspurl ? aiaocspurl : responder_url;
  if (!OCSP_parse_url(chosenurl, &host, &port, &path, &ssl)) {
    result = MYPROXY_OCSPRESULT_ERROR_BADOCSPADDRESS;
    goto end;
  }

  myproxy_log("querying OCSP responder at %s", chosenurl);

  if (!(req = OCSP_REQUEST_new())) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }

  id = OCSP_cert_to_id(0, cert, issuer);
  if (!id || !OCSP_request_add0_id(req, id)) goto end;
  if (usenonce) OCSP_request_add1_nonce(req, 0, -1);

  /* sign the request */
  if (sign_cert && sign_key &&
      !OCSP_request_sign(req, sign_cert, sign_key, EVP_sha1(), 0, 0)) {
    result = MYPROXY_OCSPRESULT_ERROR_SIGNFAILURE;
    goto end;
  }

  /* setup GSI context */
  store=X509_STORE_new();
  lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  if (lookup == NULL) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }
  res = GLOBUS_GSI_SYSCONFIG_GET_CERT_DIR(&certdir);
  if (res != GLOBUS_SUCCESS) {
    verror_put_string("failed to find GSI CA cert directory");
    globus_error_to_verror(res);
    goto end;
  }
  X509_LOOKUP_add_dir(lookup, certdir, X509_FILETYPE_PEM);
  ctx = SSL_CTX_new(SSLv23_client_method());
  if (ctx == NULL) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
  SSL_CTX_set_cert_store(ctx, store);
  SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);

  /* establish a connection to the OCSP responder */
  if (!(bio = my_connect(host, atoi(port), ssl, &ctx))) {
    result = MYPROXY_OCSPRESULT_ERROR_CONNECTFAILURE;
    goto end;
  }

  /* send the request and get a response */
  resp = OCSP_sendreq_bio(bio, path, req);
  if ((rc = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
    switch (rc) {
      case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
        result = MYPROXY_OCSPRESULT_ERROR_MALFORMEDREQUEST; break;
      case OCSP_RESPONSE_STATUS_INTERNALERROR:
        result = MYPROXY_OCSPRESULT_ERROR_INTERNALERROR;    break;
      case OCSP_RESPONSE_STATUS_TRYLATER:
        result = MYPROXY_OCSPRESULT_ERROR_TRYLATER;         break;
      case OCSP_RESPONSE_STATUS_SIGREQUIRED:
        result = MYPROXY_OCSPRESULT_ERROR_SIGREQUIRED;      break;
      case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
        result = MYPROXY_OCSPRESULT_ERROR_UNAUTHORIZED;     break;
    }
    goto end;
  }

  /* verify the response */
  result = MYPROXY_OCSPRESULT_ERROR_INVALIDRESPONSE;
  if (!(basic = OCSP_response_get1_basic(resp))) goto end;
  if (usenonce && OCSP_check_nonce(req, basic) <= 0) goto end;

  if (!responder_cert ||
      (rc = OCSP_basic_verify(basic, responder_cert, store,
                              OCSP_TRUSTOTHER)) <= 0)
      if ((rc = OCSP_basic_verify(basic, NULL, store, 0)) <= 0) 
          goto end;

  if (!OCSP_resp_find_status(basic, id, &status, &reason, &producedAt,
                             &thisUpdate, &nextUpdate))
    goto end;
  if (!OCSP_check_validity(thisUpdate, nextUpdate, skew, maxage))
    goto end;

  /* All done.  Set the return code based on the status from the response. */
  if (status == V_OCSP_CERTSTATUS_REVOKED) {
    result = MYPROXY_OCSPRESULT_CERTIFICATE_REVOKED;
    myproxy_log("OCSP status revoked!");
  } else {
    result = MYPROXY_OCSPRESULT_CERTIFICATE_VALID;
    myproxy_log("OCSP status valid");
  }

end:
  if (result < 0 && result != MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED) {
      ssl_error_to_verror();
      myproxy_log("OCSP check failed");
      myproxy_log_verror();
  }
  if (bio) BIO_free_all(bio);
  if (host) OPENSSL_free(host);
  if (port) OPENSSL_free(port);
  if (path) OPENSSL_free(path);
  if (req) OCSP_REQUEST_free(req);
  if (resp) OCSP_RESPONSE_free(resp);
  if (basic) OCSP_BASICRESP_free(basic);
  if (ctx) SSL_CTX_free(ctx);   /* this does X509_STORE_free(store) */
  if (certdir) free(certdir);
  if (aiaocspurl) free(aiaocspurl);

  return result;
}
Example #24
0
int
verify_main(int argc, char **argv)
{
	int i, ret = 1, badarg = 0;
	char *CApath = NULL, *CAfile = NULL;
	char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;
	STACK_OF(X509) * untrusted = NULL, *trusted = NULL;
	STACK_OF(X509_CRL) * crls = NULL;
	X509_STORE *cert_ctx = NULL;
	X509_LOOKUP *lookup = NULL;
	X509_VERIFY_PARAM *vpm = NULL;

	if (single_execution) {
		if (pledge("stdio rpath", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	cert_ctx = X509_STORE_new();
	if (cert_ctx == NULL)
		goto end;
	X509_STORE_set_verify_cb(cert_ctx, cb);

	argc--;
	argv++;
	for (;;) {
		if (argc >= 1) {
			if (strcmp(*argv, "-CApath") == 0) {
				if (argc-- < 1)
					goto end;
				CApath = *(++argv);
			} else if (strcmp(*argv, "-CAfile") == 0) {
				if (argc-- < 1)
					goto end;
				CAfile = *(++argv);
			} else if (args_verify(&argv, &argc, &badarg, bio_err,
			    &vpm)) {
				if (badarg)
					goto end;
				continue;
			} else if (strcmp(*argv, "-untrusted") == 0) {
				if (argc-- < 1)
					goto end;
				untfile = *(++argv);
			} else if (strcmp(*argv, "-trusted") == 0) {
				if (argc-- < 1)
					goto end;
				trustfile = *(++argv);
			} else if (strcmp(*argv, "-CRLfile") == 0) {
				if (argc-- < 1)
					goto end;
				crlfile = *(++argv);
			}
			else if (strcmp(*argv, "-help") == 0)
				goto end;
			else if (strcmp(*argv, "-verbose") == 0)
				v_verbose = 1;
			else if (argv[0][0] == '-')
				goto end;
			else
				break;
			argc--;
			argv++;
		} else
			break;
	}

	if (vpm)
		X509_STORE_set1_param(cert_ctx, vpm);

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
	if (lookup == NULL)
		abort();
	if (CAfile) {
		i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
		if (!i) {
			BIO_printf(bio_err, "Error loading file %s\n", CAfile);
			ERR_print_errors(bio_err);
			goto end;
		}
	} else
		X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
	if (lookup == NULL)
		abort();
	if (CApath) {
		i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
		if (!i) {
			BIO_printf(bio_err, "Error loading directory %s\n", CApath);
			ERR_print_errors(bio_err);
			goto end;
		}
	} else
		X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

	ERR_clear_error();

	if (untfile) {
		untrusted = load_certs(bio_err, untfile, FORMAT_PEM,
		    NULL, "untrusted certificates");
		if (!untrusted)
			goto end;
	}
	if (trustfile) {
		trusted = load_certs(bio_err, trustfile, FORMAT_PEM,
		    NULL, "trusted certificates");
		if (!trusted)
			goto end;
	}
	if (crlfile) {
		crls = load_crls(bio_err, crlfile, FORMAT_PEM,
		    NULL, "other CRLs");
		if (!crls)
			goto end;
	}
	ret = 0;
	if (argc < 1) {
		if (1 != check(cert_ctx, NULL, untrusted, trusted, crls))
			ret = -1;
	} else {
		for (i = 0; i < argc; i++)
			if (1 != check(cert_ctx, argv[i], untrusted, trusted,
			    crls))
				ret = -1;
	}

end:
	if (ret == 1) {
		BIO_printf(bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]");
		BIO_printf(bio_err, " [-attime timestamp]");
		BIO_printf(bio_err, " cert1 cert2 ...\n");

		BIO_printf(bio_err, "recognized usages:\n");
		for (i = 0; i < X509_PURPOSE_get_count(); i++) {
			X509_PURPOSE *ptmp;
			ptmp = X509_PURPOSE_get0(i);
			BIO_printf(bio_err, "\t%-10s\t%s\n",
			    X509_PURPOSE_get0_sname(ptmp),
			    X509_PURPOSE_get0_name(ptmp));
		}
	}
	if (vpm)
		X509_VERIFY_PARAM_free(vpm);
	if (cert_ctx != NULL)
		X509_STORE_free(cert_ctx);
	sk_X509_pop_free(untrusted, X509_free);
	sk_X509_pop_free(trusted, X509_free);
	sk_X509_CRL_pop_free(crls, X509_CRL_free);

	return (ret < 0 ? 2 : ret);
}
Example #25
0
File: verify.c Project: 274914765/C
int MAIN (int argc, char **argv)
{
    ENGINE *e = NULL;

    int i, ret = 1, badarg = 0;

    char *CApath = NULL, *CAfile = NULL;

    char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;

    STACK_OF (X509) * untrusted = NULL, *trusted = NULL;
    STACK_OF (X509_CRL) * crls = NULL;
    X509_STORE *cert_ctx = NULL;

    X509_LOOKUP *lookup = NULL;

    X509_VERIFY_PARAM *vpm = NULL;

#ifndef OPENSSL_NO_ENGINE
    char *engine = NULL;
#endif

    cert_ctx = X509_STORE_new ();
    if (cert_ctx == NULL)
        goto end;
    X509_STORE_set_verify_cb (cert_ctx, cb);

    ERR_load_crypto_strings ();

    apps_startup ();

    if (bio_err == NULL)
        if ((bio_err = BIO_new (BIO_s_file ())) != NULL)
            BIO_set_fp (bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config (bio_err, NULL))
        goto end;

    argc--;
    argv++;
    for (;;)
    {
        if (argc >= 1)
        {
            if (strcmp (*argv, "-CApath") == 0)
            {
                if (argc-- < 1)
                    goto end;
                CApath = *(++argv);
            }
            else if (strcmp (*argv, "-CAfile") == 0)
            {
                if (argc-- < 1)
                    goto end;
                CAfile = *(++argv);
            }
            else if (args_verify (&argv, &argc, &badarg, bio_err, &vpm))
            {
                if (badarg)
                    goto end;
                continue;
            }
            else if (strcmp (*argv, "-untrusted") == 0)
            {
                if (argc-- < 1)
                    goto end;
                untfile = *(++argv);
            }
            else if (strcmp (*argv, "-trusted") == 0)
            {
                if (argc-- < 1)
                    goto end;
                trustfile = *(++argv);
            }
            else if (strcmp (*argv, "-CRLfile") == 0)
            {
                if (argc-- < 1)
                    goto end;
                crlfile = *(++argv);
            }
#ifndef OPENSSL_NO_ENGINE
            else if (strcmp (*argv, "-engine") == 0)
            {
                if (--argc < 1)
                    goto end;
                engine = *(++argv);
            }
#endif
            else if (strcmp (*argv, "-help") == 0)
                goto end;
            else if (strcmp (*argv, "-verbose") == 0)
                v_verbose = 1;
            else if (argv[0][0] == '-')
                goto end;
            else
                break;
            argc--;
            argv++;
        }
        else
            break;
    }

#ifndef OPENSSL_NO_ENGINE
    e = setup_engine (bio_err, engine, 0);
#endif

    if (vpm)
        X509_STORE_set1_param (cert_ctx, vpm);

    lookup = X509_STORE_add_lookup (cert_ctx, X509_LOOKUP_file ());
    if (lookup == NULL)
        abort ();
    if (CAfile)
    {
        i = X509_LOOKUP_load_file (lookup, CAfile, X509_FILETYPE_PEM);
        if (!i)
        {
            BIO_printf (bio_err, "Error loading file %s\n", CAfile);
            ERR_print_errors (bio_err);
            goto end;
        }
    }
    else
        X509_LOOKUP_load_file (lookup, NULL, X509_FILETYPE_DEFAULT);

    lookup = X509_STORE_add_lookup (cert_ctx, X509_LOOKUP_hash_dir ());
    if (lookup == NULL)
        abort ();
    if (CApath)
    {
        i = X509_LOOKUP_add_dir (lookup, CApath, X509_FILETYPE_PEM);
        if (!i)
        {
            BIO_printf (bio_err, "Error loading directory %s\n", CApath);
            ERR_print_errors (bio_err);
            goto end;
        }
    }
    else
        X509_LOOKUP_add_dir (lookup, NULL, X509_FILETYPE_DEFAULT);

    ERR_clear_error ();

    if (untfile)
    {
        untrusted = load_certs (bio_err, untfile, FORMAT_PEM, NULL, e, "untrusted certificates");
        if (!untrusted)
            goto end;
    }

    if (trustfile)
    {
        trusted = load_certs (bio_err, trustfile, FORMAT_PEM, NULL, e, "trusted certificates");
        if (!trusted)
            goto end;
    }

    if (crlfile)
    {
        crls = load_crls (bio_err, crlfile, FORMAT_PEM, NULL, e, "other CRLs");
        if (!crls)
            goto end;
    }

    ret = 0;
    if (argc < 1)
    {
        if (1 != check (cert_ctx, NULL, untrusted, trusted, crls, e))
            ret = -1;
    }
    else
    {
        for (i = 0; i < argc; i++)
            if (1 != check (cert_ctx, argv[i], untrusted, trusted, crls, e))
                ret = -1;
    }

  end:
    if (ret == 1)
    {
        BIO_printf (bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]");
        BIO_printf (bio_err, " [-attime timestamp]");
#ifndef OPENSSL_NO_ENGINE
        BIO_printf (bio_err, " [-engine e]");
#endif
        BIO_printf (bio_err, " cert1 cert2 ...\n");

        BIO_printf (bio_err, "recognized usages:\n");
        for (i = 0; i < X509_PURPOSE_get_count (); i++)
        {
            X509_PURPOSE *ptmp;

            ptmp = X509_PURPOSE_get0 (i);
            BIO_printf (bio_err, "\t%-10s\t%s\n", X509_PURPOSE_get0_sname (ptmp), X509_PURPOSE_get0_name (ptmp));
        }
    }
    if (vpm)
        X509_VERIFY_PARAM_free (vpm);
    if (cert_ctx != NULL)
        X509_STORE_free (cert_ctx);
    sk_X509_pop_free (untrusted, X509_free);
    sk_X509_pop_free (trusted, X509_free);
    sk_X509_CRL_pop_free (crls, X509_CRL_free);
    apps_shutdown ();
    OPENSSL_EXIT (ret < 0 ? 2 : ret);
}
Example #26
0
int32_t mz_crypt_sign_verify(uint8_t *message, int32_t message_size, uint8_t *signature, int32_t signature_size)
{
    CMS_ContentInfo *cms = NULL;
    STACK_OF(X509) *signers = NULL;
    STACK_OF(X509) *intercerts = NULL;
    X509_STORE *cert_store = NULL;
    X509_LOOKUP *lookup = NULL;
    X509_STORE_CTX *store_ctx = NULL;
    BIO *message_bio = NULL;
    BIO *signature_bio = NULL;
    BUF_MEM *buf_mem = NULL;
    int32_t signer_count = 0;
    int32_t result = 0;
    int32_t i = 0;
    int32_t err = MZ_SIGN_ERROR;


    if (message == NULL || message_size == 0 || signature == NULL || signature_size == 0)
        return MZ_PARAM_ERROR;

    mz_crypt_init();

    cert_store = X509_STORE_new();

    X509_STORE_load_locations(cert_store, "cacert.pem", NULL);
    X509_STORE_set_default_paths(cert_store);

#if 0
    BIO *yy = BIO_new_file("xyz", "wb");
    BIO_write(yy, signature, signature_size);
    BIO_flush(yy);
    BIO_free(yy);
#endif

    lookup = X509_STORE_add_lookup(cert_store, X509_LOOKUP_file());   
    if (lookup != NULL)
        X509_LOOKUP_load_file(lookup, "cacert.pem", X509_FILETYPE_PEM);
    lookup = X509_STORE_add_lookup(cert_store, X509_LOOKUP_hash_dir());
    if (lookup != NULL)
        X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

    signature_bio = BIO_new_mem_buf(signature, signature_size);
    message_bio = BIO_new(BIO_s_mem());

    cms = d2i_CMS_bio(signature_bio, NULL);
    if (cms)
    {
        result = CMS_verify(cms, NULL, cert_store, NULL, message_bio, CMS_NO_SIGNER_CERT_VERIFY | CMS_BINARY);
        if (result)
            signers = CMS_get0_signers(cms);
        if (signers)
            intercerts = CMS_get1_certs(cms);
        if (intercerts)
        {
            /* Verify signer certificates */
            signer_count = sk_X509_num(signers);
            if (signer_count > 0)
                err = MZ_OK;

            for (i = 0; i < signer_count; i++)
            {
                store_ctx = X509_STORE_CTX_new();
                X509_STORE_CTX_init(store_ctx, cert_store, sk_X509_value(signers, i), intercerts);
                result = X509_verify_cert(store_ctx);
                if (store_ctx)
                    X509_STORE_CTX_free(store_ctx);

                if (!result)
                {
                    err = MZ_SIGN_ERROR;
                    break;
                }
            }
        }

        BIO_get_mem_ptr(message_bio, &buf_mem);

        if (err == MZ_OK)
        {
            /* Verify the message */
            if (((int32_t)buf_mem->length != message_size) || 
                (memcmp(buf_mem->data, message, message_size) != 0))
                err = MZ_SIGN_ERROR;
        }
    }

#if 0
    if (!result)
        printf(ERR_error_string(ERR_get_error(), NULL));
#endif

    if (cms)
        CMS_ContentInfo_free(cms);
    if (message_bio)
        BIO_free(message_bio);
    if (signature_bio)
        BIO_free(signature_bio);
    if (cert_store)
        X509_STORE_free(cert_store);

    return err;
}
Example #27
0
static int
xmlSecOpenSSLX509StoreInitialize(xmlSecKeyDataStorePtr store) {
    const xmlChar* path;
    X509_LOOKUP *lookup = NULL;

    xmlSecOpenSSLX509StoreCtxPtr ctx;
    xmlSecAssert2(xmlSecKeyDataStoreCheckId(store, xmlSecOpenSSLX509StoreId), -1);

    ctx = xmlSecOpenSSLX509StoreGetCtx(store);
    xmlSecAssert2(ctx != NULL, -1);

    memset(ctx, 0, sizeof(xmlSecOpenSSLX509StoreCtx));

    ctx->xst = X509_STORE_new();
    if(ctx->xst == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_STORE_new");
        return(-1);
    }

    if(!X509_STORE_set_default_paths(ctx->xst)) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_STORE_set_default_paths");
        return(-1);
    }


    lookup = X509_STORE_add_lookup(ctx->xst, X509_LOOKUP_hash_dir());
    if(lookup == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_STORE_add_lookup");
         return(-1);
    }

    path = xmlSecOpenSSLGetDefaultTrustedCertsFolder();
    if(path != NULL) {
        if(!X509_LOOKUP_add_dir(lookup, (char*)path, X509_FILETYPE_PEM)) {
            xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                               "X509_LOOKUP_add_dir");
            return(-1);
        }
    } else {
        if(!X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT)) {
            xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                               "X509_LOOKUP_add_dir");
            return(-1);
        }
    }

    ctx->untrusted = sk_X509_new_null();
    if(ctx->untrusted == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "sk_X509_new_null");
        return(-1);
    }

    ctx->crls = sk_X509_CRL_new_null();
    if(ctx->crls == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "sk_X509_CRL_new_null");
        return(-1);
    }

    ctx->vpm = X509_VERIFY_PARAM_new();
    if(ctx->vpm == NULL) {
        xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                           "X509_VERIFY_PARAM_new");
        return(-1);
    }
    X509_VERIFY_PARAM_set_depth(ctx->vpm, 9); /* the default cert verification path in openssl */
    X509_STORE_set1_param(ctx->xst, ctx->vpm);


    return(0);
}
Example #28
0
int MAIN(int argc, char **argv)
{
    unsigned long nmflag = 0;
    X509_CRL *x = NULL;
    char *CAfile = NULL, *CApath = NULL;
    int ret = 1, i, num, badops = 0, badsig = 0;
    BIO *out = NULL;
    int informat, outformat, keyformat;
    char *infile = NULL, *outfile = NULL, *crldiff = NULL, *keyfile = NULL;
    int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout =
        0, text = 0;
#ifndef OPENSSL_NO_MD5
    int hash_old = 0;
#endif
    int fingerprint = 0, crlnumber = 0;
    const char **pp;
    X509_STORE *store = NULL;
    X509_STORE_CTX ctx;
    X509_LOOKUP *lookup = NULL;
    X509_OBJECT xobj;
    EVP_PKEY *pkey;
    int do_ver = 0;
    const EVP_MD *md_alg, *digest = EVP_sha1();

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config(bio_err, NULL))
        goto end;

    if (bio_out == NULL)
        if ((bio_out = BIO_new(BIO_s_file())) != NULL) {
            BIO_set_fp(bio_out, stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
            {
                BIO *tmpbio = BIO_new(BIO_f_linebuffer());
                bio_out = BIO_push(tmpbio, bio_out);
            }
#endif
        }

    informat = FORMAT_PEM;
    outformat = FORMAT_PEM;
    keyformat = FORMAT_PEM;

    argc--;
    argv++;
    num = 0;
    while (argc >= 1) {
#ifdef undef
        if (sgx_strcmp(*argv, "-p") == 0) {
            if (--argc < 1)
                goto bad;
            if (!args_from_file(++argv, Nargc, Nargv)) {
                goto end;
            }
        */}
#endif
        if (sgx_strcmp(*argv, "-inform") == 0) {
            if (--argc < 1)
                goto bad;
            informat = str2fmt(*(++argv));
        } else if (sgx_strcmp(*argv, "-outform") == 0) {
            if (--argc < 1)
                goto bad;
            outformat = str2fmt(*(++argv));
        } else if (sgx_strcmp(*argv, "-in") == 0) {
            if (--argc < 1)
                goto bad;
            infile = *(++argv);
        } else if (sgx_strcmp(*argv, "-gendelta") == 0) {
            if (--argc < 1)
                goto bad;
            crldiff = *(++argv);
        } else if (sgx_strcmp(*argv, "-key") == 0) {
            if (--argc < 1)
                goto bad;
            keyfile = *(++argv);
        } else if (sgx_strcmp(*argv, "-keyform") == 0) {
            if (--argc < 1)
                goto bad;
            keyformat = str2fmt(*(++argv));
        } else if (sgx_strcmp(*argv, "-out") == 0) {
            if (--argc < 1)
                goto bad;
            outfile = *(++argv);
        } else if (sgx_strcmp(*argv, "-CApath") == 0) {
            if (--argc < 1)
                goto bad;
            CApath = *(++argv);
            do_ver = 1;
        } else if (sgx_strcmp(*argv, "-CAfile") == 0) {
            if (--argc < 1)
                goto bad;
            CAfile = *(++argv);
            do_ver = 1;
        } else if (sgx_strcmp(*argv, "-verify") == 0)
            do_ver = 1;
        else if (sgx_strcmp(*argv, "-text") == 0)
            text = 1;
        else if (sgx_strcmp(*argv, "-hash") == 0)
            hash = ++num;
#ifndef OPENSSL_NO_MD5
        else if (sgx_strcmp(*argv, "-hash_old") == 0)
            hash_old = ++num;
#endif
        else if (sgx_strcmp(*argv, "-nameopt") == 0) {
            if (--argc < 1)
                goto bad;
            if (!set_name_ex(&nmflag, *(++argv)))
                goto bad;
        } else if (sgx_strcmp(*argv, "-issuer") == 0)
            issuer = ++num;
        else if (sgx_strcmp(*argv, "-lastupdate") == 0)
            lastupdate = ++num;
        else if (sgx_strcmp(*argv, "-nextupdate") == 0)
            nextupdate = ++num;
        else if (sgx_strcmp(*argv, "-noout") == 0)
            noout = ++num;
        else if (sgx_strcmp(*argv, "-fingerprint") == 0)
            fingerprint = ++num;
        else if (sgx_strcmp(*argv, "-crlnumber") == 0)
            crlnumber = ++num;
        else if (sgx_strcmp(*argv, "-badsig") == 0)
            badsig = 1;
        else if ((md_alg = EVP_get_digestbyname(*argv + 1))) {
            /* ok */
            digest = md_alg;
        } else {
            BIO_printf(bio_err, "unknown option %s\n", *argv);
            badops = 1;
            break;
        }
        argc--;
        argv++;
    }

    if (badops) {
 bad:
        for (pp = crl_usage; (*pp != NULL); pp++)
            BIO_printf(bio_err, "%s", *pp);
        goto end;
    }

    ERR_load_crypto_strings();
    x = load_crl(infile, informat);
    if (x == NULL) {
        goto end;
    }

    if (do_ver) {
        store = X509_STORE_new();
        lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
        if (lookup == NULL)
            goto end;
        if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM))
            X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);

        lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
        if (lookup == NULL)
            goto end;
        if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM))
            X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
        ERR_clear_error();

        if (!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) {
            BIO_printf(bio_err, "Error initialising X509 store\n");
            goto end;
        }

        i = X509_STORE_get_by_subject(&ctx, X509_LU_X509,
                                      X509_CRL_get_issuer(x), &xobj);
        if (i <= 0) {
            BIO_printf(bio_err, "Error getting CRL issuer certificate\n");
            goto end;
        }
        pkey = X509_get_pubkey(xobj.data.x509);
        X509_OBJECT_free_contents(&xobj);
        if (!pkey) {
            BIO_printf(bio_err, "Error getting CRL issuer public key\n");
            goto end;
        }
        i = X509_CRL_verify(x, pkey);
        EVP_PKEY_free(pkey);
        if (i < 0)
            goto end;
        if (i == 0)
            BIO_printf(bio_err, "verify failure\n");
        else
            BIO_printf(bio_err, "verify OK\n");
    }

    if (crldiff) {
        X509_CRL *newcrl, *delta;
        if (!keyfile) {
            BIO_puts(bio_err, "Missing CRL signing key\n");
            goto end;
        }
        newcrl = load_crl(crldiff, informat);
        if (!newcrl)
            goto end;
        pkey = load_key(bio_err, keyfile, keyformat, 0, NULL, NULL,
                        "CRL signing key");
        if (!pkey) {
            X509_CRL_free(newcrl);
            goto end;
        }
        delta = X509_CRL_diff(x, newcrl, pkey, digest, 0);
        X509_CRL_free(newcrl);
        EVP_PKEY_free(pkey);
        if (delta) {
            X509_CRL_free(x);
            x = delta;
        } else {
            BIO_puts(bio_err, "Error creating delta CRL\n");
            goto end;
        }
    }

    if (num) {
        for (i = 1; i <= num; i++) {
            if (issuer == i) {
                print_name(bio_out, "issuer=", X509_CRL_get_issuer(x),
                           nmflag);
            }
            if (crlnumber == i) {
                ASN1_INTEGER *crlnum;
                crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL);
                BIO_printf(bio_out, "crlNumber=");
                if (crlnum) {
                    i2a_ASN1_INTEGER(bio_out, crlnum);
                    ASN1_INTEGER_free(crlnum);
                } else
                    BIO_puts(bio_out, "<NONE>");
                BIO_printf(bio_out, "\n");
            }
            if (hash == i) {
                BIO_printf(bio_out, "%08lx\n",
                           X509_NAME_hash(X509_CRL_get_issuer(x)));
            }
#ifndef OPENSSL_NO_MD5
            if (hash_old == i) {
                BIO_printf(bio_out, "%08lx\n",
                           X509_NAME_hash_old(X509_CRL_get_issuer(x)));
            }
#endif
            if (lastupdate == i) {
                BIO_printf(bio_out, "lastUpdate=");
                ASN1_TIME_print(bio_out, X509_CRL_get_lastUpdate(x));
                BIO_printf(bio_out, "\n");
            }
            if (nextupdate == i) {
                BIO_printf(bio_out, "nextUpdate=");
                if (X509_CRL_get_nextUpdate(x))
                    ASN1_TIME_print(bio_out, X509_CRL_get_nextUpdate(x));
                else
                    BIO_printf(bio_out, "NONE");
                BIO_printf(bio_out, "\n");
            }
            if (fingerprint == i) {
                int j;
                unsigned int n;
                unsigned char md[EVP_MAX_MD_SIZE];

                if (!X509_CRL_digest(x, digest, md, &n)) {
                    BIO_printf(bio_err, "out of memory\n");
                    goto end;
                }
                BIO_printf(bio_out, "%s Fingerprint=",
                           OBJ_nid2sn(EVP_MD_type(digest)));
                for (j = 0; j < (int)n; j++) {
                    BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n)
                               ? '\n' : ':');
                }
            }
        }
    }

    out = BIO_new(BIO_s_file());
    if (out == NULL) {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (outfile == NULL) {
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
        {
            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
            out = BIO_push(tmpbio, out);
        }
#endif
    } else {
        if (BIO_write_filename(out, outfile) <= 0) {
            perror(outfile);
            goto end;
        }
    }

    if (text)
        X509_CRL_print(out, x);

    if (noout) {
        ret = 0;
        goto end;
    }

    if (badsig)
        x->signature->data[x->signature->length - 1] ^= 0x1;

    if (outformat == FORMAT_ASN1)
        i = (int)i2d_X509_CRL_bio(out, x);
    else if (outformat == FORMAT_PEM)
        i = PEM_write_bio_X509_CRL(out, x);
    else {
        BIO_printf(bio_err, "bad output format specified for outfile\n");
        goto end;
    }
    if (!i) {
        BIO_printf(bio_err, "unable to write CRL\n");
        goto end;
    }
    ret = 0;
 end:
    if (ret != 0)
        ERR_print_errors(bio_err);
    BIO_free_all(out);
    BIO_free_all(bio_out);
    bio_out = NULL;
    X509_CRL_free(x);
    if (store) {
        X509_STORE_CTX_cleanup(&ctx);
        X509_STORE_free(store);
    }
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Example #29
0
int check_validity_of_cert(
    const char *cFile, const unsigned char *md5_md, unsigned char *sfileMsg,
    const int sfsize, const char* caPath
) {
    int retval = 0;
    X509 *cert;
    X509_STORE *store;
    X509_LOOKUP *lookup;
    X509_STORE_CTX *ctx = 0;
    EVP_PKEY *pubKey;
    BIO *bio;

    bio = BIO_new(BIO_s_file());
    BIO_read_filename(bio, cFile);
    if (NULL == (cert = PEM_read_bio_X509(bio, NULL, 0, NULL))) {
	    BIO_vfree(bio);
	    return 0;
    }
    // verify certificate
    store = X509_STORE_new();
    lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
    X509_LOOKUP_add_dir(lookup, (char *)caPath, X509_FILETYPE_PEM);
    if ((ctx = X509_STORE_CTX_new()) != 0) {
        if (X509_STORE_CTX_init(ctx, store, cert, 0) == 1)
            retval = X509_verify_cert(ctx);
        X509_STORE_CTX_free(ctx);
    }
    X509_STORE_free(store);
    
    if (retval != 1) {
        fprintf(stderr,"ERROR: Cannot verify certificate ('%s')\n", cFile);
        return 0;
    }        
    pubKey = X509_get_pubkey(cert);
    if (!pubKey) {
        X509_free(cert);
        BIO_vfree(bio);
        return 0;
    }
    if (pubKey->type == EVP_PKEY_RSA) {
        BN_CTX *c = BN_CTX_new();
        if (!c) {
	        X509_free(cert);
	        EVP_PKEY_free(pubKey);
	        BIO_vfree(bio);
	        return 0;
	    }
	    if (!RSA_blinding_on(pubKey->pkey.rsa, c)) {
	        X509_free(cert);
	        EVP_PKEY_free(pubKey);
	        BIO_vfree(bio);
	        BN_CTX_free(c);
	        return 0;
	    }
	    retval = RSA_verify(NID_md5, md5_md, MD5_DIGEST_LENGTH, sfileMsg, sfsize, pubKey->pkey.rsa);
	    RSA_blinding_off(pubKey->pkey.rsa);
	    BN_CTX_free(c);
    }
    if (pubKey->type == EVP_PKEY_DSA) {
        fprintf(stderr, "ERROR: DSA keys are not supported.\n");
        return 0;
    }
    EVP_PKEY_free(pubKey);
    X509_free(cert);
    BIO_vfree(bio);
    return retval;
}
Example #30
0
/*============================================================================
 * OpcUa_P_OpenSSL_CertificateStore_Open
 *===========================================================================*/
OpcUa_StatusCode OpcUa_P_OpenSSL_PKI_OpenCertificateStore(
    OpcUa_PKIProvider*          a_pProvider,
    OpcUa_Void**                a_ppCertificateStore)           /* type depends on store implementation */
{
    OpcUa_P_OpenSSL_CertificateStore_Config*    pCertificateStoreCfg;
    X509_STORE*         pStore;
    X509_LOOKUP*        pLookup;
    char                CertFile[MAX_PATH];
    struct dirent **dirlist = NULL;
    int numCertificates = 0, i;

OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "PKI_OpenCertificateStore");

    OpcUa_ReturnErrorIfArgumentNull(a_pProvider);
    OpcUa_ReturnErrorIfArgumentNull(a_pProvider->Handle);
    OpcUa_ReturnErrorIfArgumentNull(a_ppCertificateStore);

    *a_ppCertificateStore = OpcUa_Null;

    pCertificateStoreCfg = (OpcUa_P_OpenSSL_CertificateStore_Config*)a_pProvider->Handle;

    if(!(*a_ppCertificateStore = pStore = X509_STORE_new()))
    {
        OpcUa_GotoErrorWithStatus(OpcUa_Bad);
    }

    X509_STORE_set_verify_cb_func(pStore, OpcUa_P_OpenSSL_CertificateStore_Verify_Callback);

    if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_USE_DEFAULT_CERT_CRL_LOOKUP_METHOD)
    {
        if(X509_STORE_set_default_paths(pStore) != 1)
        {
            OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_STORE_set_default_paths!\n");
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }
    }

    if(!(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_DONT_ADD_TRUST_LIST_TO_ROOT_CERTIFICATES))
    {
        if(pCertificateStoreCfg->CertificateTrustListLocation == OpcUa_Null || pCertificateStoreCfg->CertificateTrustListLocation[0] == '\0')
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        /* how to search for certificate & CRLs */
        if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())))
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        /* how to search for certificate & CRLs */
        numCertificates = scandir(pCertificateStoreCfg->CertificateTrustListLocation, &dirlist, certificate_filter_der, alphasort);
        for (i=0; i<numCertificates; i++)
        {
            uStatus = OpcUa_P_OpenSSL_BuildFullPath(pCertificateStoreCfg->CertificateTrustListLocation, dirlist[i]->d_name, MAX_PATH, CertFile);
            OpcUa_GotoErrorIfBad(uStatus);

            /* add CACertificate lookup */
            if(X509_LOOKUP_load_file(pLookup, CertFile, X509_FILETYPE_ASN1) != 1) /*DER encoded*/
            {
                OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_LOOKUP_load_file: skipping %s\n", CertFile);
            }
        }
        for (i=0; i<numCertificates; i++)
        {
            free(dirlist[i]);
        }
        free(dirlist);
        dirlist = NULL;
    }

    if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_ADD_UNTRUSTED_LIST_TO_ROOT_CERTIFICATES)
    {
        if(pCertificateStoreCfg->CertificateUntrustedListLocation == OpcUa_Null || pCertificateStoreCfg->CertificateUntrustedListLocation[0] == '\0')
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_UNTRUSTED_LIST_IS_INDEX)
        {
            /* how to search for certificate */
            if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir())))
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }

            /* add hash lookup */
            if(X509_LOOKUP_add_dir(pLookup, pCertificateStoreCfg->CertificateUntrustedListLocation, X509_FILETYPE_ASN1) != 1) /*DER encoded*/
            {
                OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_LOOKUP_add_dir!\n");
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }
        }
        else
        {
            /* how to search for certificate & CRLs */
            if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())))
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }

            numCertificates = scandir(pCertificateStoreCfg->CertificateUntrustedListLocation, &dirlist, certificate_filter_der, alphasort);
            for (i=0; i<numCertificates; i++)
            {
                uStatus = OpcUa_P_OpenSSL_BuildFullPath(pCertificateStoreCfg->CertificateUntrustedListLocation, dirlist[i]->d_name, MAX_PATH, CertFile);
                OpcUa_GotoErrorIfBad(uStatus);

                /* add CACertificate lookup */
                if(X509_LOOKUP_load_file(pLookup, CertFile, X509_FILETYPE_ASN1) != 1) /*DER encoded*/
                {
                    OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_LOOKUP_load_file: skipping %s\n", CertFile);
                }
            }
            for (i=0; i<numCertificates; i++)
            {
                free(dirlist[i]);
            }
            free(dirlist);
            dirlist = NULL;
        }
    }

    if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_CHECK_REVOCATION_ALL)
    {
        if(pCertificateStoreCfg->CertificateRevocationListLocation == OpcUa_Null || pCertificateStoreCfg->CertificateRevocationListLocation[0] == '\0')
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }

        if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_REVOCATION_LIST_IS_INDEX)
        {
            /* how to search for certificate & CRLs */
            if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_hash_dir())))
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }

            /* add CRL lookup */
            if(X509_LOOKUP_add_dir(pLookup, pCertificateStoreCfg->CertificateRevocationListLocation, X509_FILETYPE_PEM) != 1) /*PEM encoded*/
            {
                OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_LOOKUP_add_dir!\n");
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }
        }
        else if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_REVOCATION_LIST_IS_CONCATENATED_PEM_FILE)
        {
            /* how to search for certificate & CRLs */
            if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())))
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }

            /* add CRL lookup */
            if(X509_load_crl_file(pLookup, pCertificateStoreCfg->CertificateRevocationListLocation, X509_FILETYPE_PEM) != 1) /*PEM encoded*/
            {
                OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_load_crl_file!\n");
            }
        }
        else
        {
            /* how to search for certificate & CRLs */
            if(!(pLookup = X509_STORE_add_lookup(pStore, X509_LOOKUP_file())))
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }

            numCertificates = scandir(pCertificateStoreCfg->CertificateRevocationListLocation, &dirlist, certificate_filter_crl, alphasort);
            for (i=0; i<numCertificates; i++)
            {
                uStatus = OpcUa_P_OpenSSL_BuildFullPath(pCertificateStoreCfg->CertificateRevocationListLocation, dirlist[i]->d_name, MAX_PATH, CertFile);
                OpcUa_GotoErrorIfBad(uStatus);

                if(X509_load_crl_file(pLookup, CertFile, X509_FILETYPE_PEM) != 1) /*PEM encoded*/
                {
                    OpcUa_Trace(OPCUA_TRACE_LEVEL_WARNING, "error at X509_load_crl_file: skipping %s\n", CertFile);
                }
            }
            for (i=0; i<numCertificates; i++)
            {
                free(dirlist[i]);
            }
            free(dirlist);
            dirlist = NULL;
        }

        if((pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_CHECK_REVOCATION_ALL) == OPCUA_P_PKI_OPENSSL_CHECK_REVOCATION_ALL)
        {
            /* set the flags of the store so that CRLs are consulted */
            if(X509_STORE_set_flags(pStore, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL) != 1)
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }
        }
        else if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_CHECK_REVOCATION_ONLY_LEAF)
        {
            /* set the flags of the store so that CRLs are consulted */
            if(X509_STORE_set_flags(pStore, X509_V_FLAG_CRL_CHECK) != 1)
            {
                OpcUa_GotoErrorWithStatus(OpcUa_Bad);
            }
        }
    }

    if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_CHECK_SELF_SIGNED_SIGNATURE)
    {
        /* set the flags of the store so that CRLs are consulted */
        if(X509_STORE_set_flags(pStore, X509_V_FLAG_CHECK_SS_SIGNATURE) != 1)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }
    }

    if(pCertificateStoreCfg->Flags & OPCUA_P_PKI_OPENSSL_ALLOW_PROXY_CERTIFICATES)
    {
        /* set the flags of the store so that CRLs are consulted */
        if(X509_STORE_set_flags(pStore, X509_V_FLAG_ALLOW_PROXY_CERTS) != 1)
        {
            OpcUa_GotoErrorWithStatus(OpcUa_Bad);
        }
    }

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

    if(dirlist != NULL)
    {
        for (i=0; i<numCertificates; i++)
        {
            free(dirlist[i]);
        }
        free(dirlist);
    }

    if(*a_ppCertificateStore != OpcUa_Null)
    {
        X509_STORE_free((X509_STORE*)*a_ppCertificateStore);
        *a_ppCertificateStore = OpcUa_Null;
    }

OpcUa_FinishErrorHandling;
}