Ejemplo n.º 1
1
void openssl_x509_info()
{
	FILE *fp;
	wchar_t *pUtf8;
	X509 *x509Cert;
	long Nid, Version;
	ASN1_INTEGER *Serial;
	X509_NAME *issuer, *subject;
	X509_NAME_ENTRY *name_entry;
	ASN1_TIME *timea, *timeb;
	char msginfo[MAX1_LEN];
	const unsigned char *uCert;
	unsigned char tmp[MAX4_LEN];
	int certLen, i, eNum, msgLen, nUtf8;

	OpenSSL_add_all_algorithms();
	printf("\nX509_Issuer info:\n");

	fp = fopen(U2CERTF, "rb");
	certLen = fread(tmp, 1, 4096, fp);
	fclose(fp);
	uCert = tmp;
	x509Cert = d2i_X509(NULL, &uCert, certLen);
	Version = X509_get_version(x509Cert);
	printf("\tX509 Version: %ld\n", Version);

	Serial = X509_get_serialNumber(x509Cert);
	printf("\tserialNumber is: ");
	for (i = 0; i < Serial->length; i++)
		printf("%02x", Serial->data[i]);
	printf("\n");

	issuer = X509_get_issuer_name(x509Cert);
	eNum = sk_X509_NAME_ENTRY_num(issuer->entries);
	for (i = 0; i < eNum; i++) {
		name_entry = sk_X509_NAME_ENTRY_value(issuer->entries, i);
		if (name_entry->value->type == V_ASN1_UTF8STRING) {
			nUtf8 = 2 * name_entry->value->length;
			pUtf8 = (wchar_t *) malloc(nUtf8);
			if (pUtf8 == NULL)
				return;
			memset(pUtf8, 0, nUtf8);
			mbstowcs(pUtf8, (char *)name_entry->value->data,
					 name_entry->value->length);
			wcstombs(msginfo, pUtf8, nUtf8);
			msgLen = nUtf8;
			msginfo[msgLen] = '\0';
			free(pUtf8);
			pUtf8 = NULL;
		} else {
			msgLen = name_entry->value->length;
			memcpy(msginfo, name_entry->value->data, msgLen);
			msginfo[msgLen] = '\0';
		}

		Nid = OBJ_obj2nid(name_entry->object);
		switch (Nid) {
		case NID_countryName:
			printf("\tissuer's countryName: %s\n", msginfo);
			break;

		case NID_stateOrProvinceName:
			printf("\tissuer's provinceName: %s\n", msginfo);
			break;

		case NID_localityName:
			printf("\tissuer's localityName: %s\n", msginfo);
			break;

		case NID_organizationName:
			printf("\tissuer's organizationName: %s\n", msginfo);
			break;

		case NID_organizationalUnitName:
			printf("\tissuer's organizationalUnitName: %s\n", msginfo);
			break;

		case NID_commonName:
			printf("\tissuer's commonName: %s\n", msginfo);
			break;

		case NID_pkcs9_emailAddress:
			printf("\tissuer's emailAddress: %s\n", msginfo);
			break;

		default:
			break;
		}
	}

	subject = X509_get_subject_name(x509Cert);
	eNum = sk_X509_NAME_ENTRY_num(subject->entries);
	for (i = 0; i < eNum; i++) {
		name_entry = sk_X509_NAME_ENTRY_value(subject->entries, i);
		if (name_entry->value->type == V_ASN1_UTF8STRING) {
			nUtf8 = 2 * name_entry->value->length;
			pUtf8 = (wchar_t *) malloc(nUtf8);
			if (pUtf8 == NULL)
				return;
			memset(pUtf8, 0, nUtf8);
			mbstowcs(pUtf8, (char *)name_entry->value->data,
					 name_entry->value->length);
			wcstombs(msginfo, pUtf8, nUtf8);
			msgLen = nUtf8;
			msginfo[msgLen] = '\0';
			free(pUtf8);
			pUtf8 = NULL;
		} else {
			msgLen = name_entry->value->length;
			memcpy(msginfo, name_entry->value->data, msgLen);
			msginfo[msgLen] = '\0';
		}

		Nid = OBJ_obj2nid(name_entry->object);
		switch (Nid) {
		case NID_countryName:
			printf("\tsubject's countryName: %s\n", msginfo);
			break;

		case NID_stateOrProvinceName:
			printf("\tsubject's ProvinceName: %s\n", msginfo);
			break;

		case NID_localityName:
			printf("\tsubject's localityName: %s\n", msginfo);
			break;

		case NID_organizationName:
			printf("\tsubject's organizationName: %s\n", msginfo);
			break;

		case NID_organizationalUnitName:
			printf("\tsubject's organizationalUnitName: %s\n", msginfo);
			break;

		case NID_commonName:
			printf("\tsubject's commonName: %s\n", msginfo);
			break;

		case NID_pkcs9_emailAddress:
			printf("\tsubject's emailAddress: %s\n", msginfo);
			break;

		default:
			break;
		}
	}

	timea = X509_get_notAfter(x509Cert);
	timeb = X509_get_notBefore(x509Cert);
	printf("\tCert notAfter: %s, notBefore: %s\n", timea->data, timeb->data);
	X509_free(x509Cert);

	return;
}
Ejemplo n.º 2
0
int tlsops_cert_version(struct sip_msg *msg, pv_param_t *param,
		pv_value_t *res)
{
	static char buf[INT2STR_MAX_LEN];
	X509* cert;
	struct tcp_connection* c;
	char* version;
	int my;

	if (param->pvn.u.isname.name.n & CERT_PEER) {
		my = 0;
	} else if (param->pvn.u.isname.name.n & CERT_LOCAL) {
		my = 1;
	} else {
		LM_CRIT("bug in call to tlsops_cert_version\n");
		return pv_get_null(msg, param, res);
	}

	if (get_cert(&cert, &c, msg, my) < 0) return -1;
	version = int2str(X509_get_version(cert), &res->rs.len);
	memcpy(buf, version, res->rs.len);
	res->rs.s = buf;
	res->flags = PV_VAL_STR;
	if (!my) X509_free(cert);
	tcpconn_put(c);
	return 0;
}
Ejemplo n.º 3
0
int
tls_parse_cert(struct tls *ctx, struct tls_cert **cert_p, const char *fingerprint_algo, X509 *x509)
{
	struct tls_cert *cert = NULL;
	X509_NAME *subject, *issuer;
	int ret = -1;
	long version;

	*cert_p = NULL;

	version = X509_get_version(x509);
	if (version < 0) {
		tls_set_errorx(ctx, "invalid version");
		return -1;
	}

	subject = X509_get_subject_name(x509);
	if (!subject) {
		tls_set_errorx(ctx, "cert does not have subject");
		return -1;
	}

	issuer = X509_get_issuer_name(x509);
	if (!issuer) {
		tls_set_errorx(ctx, "cert does not have issuer");
		return -1;
	}

	cert = calloc(sizeof *cert, 1);
	if (!cert) {
		tls_set_error(ctx, "calloc");
		goto failed;
	}
	cert->version = version;

	if (fingerprint_algo) {
		cert->fingerprint = tls_calc_fingerprint(ctx, x509, fingerprint_algo, &cert->fingerprint_size);
		if (!cert->fingerprint)
			goto failed;
	}

	ret = tls_get_dname(ctx, subject, &cert->subject);
	if (ret == 0)
		ret = tls_get_dname(ctx, issuer, &cert->issuer);
	if (ret == 0)
		ret = tls_cert_get_altnames(ctx, cert, x509);
	if (ret == 0)
		ret = tls_parse_time(ctx, X509_get_notBefore(x509), &cert->not_before);
	if (ret == 0)
		ret = tls_parse_time(ctx, X509_get_notAfter(x509), &cert->not_after);
	if (ret == 0)
		ret = tls_parse_bigint(ctx, X509_get_serialNumber(x509), &cert->serial);
	if (ret == 0) {
		*cert_p = cert;
		return 0;
	}
failed:
	tls_cert_free(cert);
	return ret;
}
Ejemplo n.º 4
0
@return: Version number as a Python integer\n\
";

static PyObject *
crypto_X509_get_version(crypto_X509Obj *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, ":get_version"))
        return NULL;

    return PyLong_FromLong((long)X509_get_version(self->x509));
}
Ejemplo n.º 5
0
static int get_cert_version(str* res, int local, sip_msg_t* msg)
{
	static char buf[INT2STR_MAX_LEN];
	X509* cert;
	struct tcp_connection* c;
	char* version;

	if (get_cert(&cert, &c, msg, local) < 0) return -1;
	version = int2str(X509_get_version(cert), &res->len);
	memcpy(buf, version, res->len);
	res->s = buf;
	if (!local) X509_free(cert);
	tcpconn_put(c);
	return 0;
}
Ejemplo n.º 6
0
Datum x509_get_version(PG_FUNCTION_ARGS) {
	bytea *raw;
	X509 *cert;
	int version;

	// check for null value.
	raw = PG_GETARG_BYTEA_P(0);
	if (raw == NULL || VARSIZE(raw) == VARHDRSZ) {
		PG_RETURN_NULL();
	}

	cert = x509_from_bytea(raw);
	if (cert == NULL) {
		ereport(ERROR,
				(errcode(ERRCODE_DATA_CORRUPTED), errmsg(
						"unable to decode X509 record")));
	}

	version = X509_get_version(cert);
	X509_free(cert);

	PG_RETURN_INT32(version);
}
Ejemplo n.º 7
0
	bool verify_certificate(bool preverified,
		boost::asio::ssl::verify_context& ctx)
	{
		// The verify callback can be used to check whether the certificate that is
		// being presented is valid for the peer. For example, RFC 2818 describes
		// the steps involved in doing this for HTTPS. Consult the OpenSSL
		// documentation for more details. Note that the callback is called once
		// for each certificate in the certificate chain, starting from the root
		// certificate authority.

		// In this example we will simply print the certificate's subject name.
#ifdef _DEBUG
		char subject_name[256];
		std::stringstream ss;
		std::string str;
		X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
		X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);

		//std::cout << "Verifying " << subject_name << "\n";

		ss << "name: " << subject_name << "\nversion: " << X509_get_version(cert);
		str = ss.str();

		std::copy(str.begin(), str.end(), std::back_inserter(extern_info));

		//X509_NAME_oneline(X509_get_issuer_name(cert), subject_name, 256);
		//std::cout << "issuer_name " << subject_name << "\n";

		//auto p = X509_get1_email(cert);
		//auto n = X509_get_serialNumber(cert);
		//auto v = X509_get_version(cert);
		//auto k = X509_get_pubkey(cert);
#endif
		//return preverified;
		return true;
	}
Ejemplo n.º 8
0
/**
 * Handle a completed fetch (CURLMSG_DONE from curl_multi_info_read()).
 *
 * \param curl_handle curl easy handle of fetch
 * \param result The result code of the completed fetch.
 */
static void fetch_curl_done(CURL *curl_handle, CURLcode result)
{
	fetch_msg msg;
	bool finished = false;
	bool error = false;
	bool cert = false;
	bool abort_fetch;
	struct curl_fetch_info *f;
	char **_hideous_hack = (char **) (void *) &f;
	CURLcode code;
	struct cert_info certs[MAX_CERTS];
	memset(certs, 0, sizeof(certs));

	/* find the structure associated with this fetch */
	/* For some reason, cURL thinks CURLINFO_PRIVATE should be a string?! */
	code = curl_easy_getinfo(curl_handle, CURLINFO_PRIVATE, _hideous_hack);
	assert(code == CURLE_OK);

	abort_fetch = f->abort;
	LOG("done %s", nsurl_access(f->url));

	if (abort_fetch == false && (result == CURLE_OK ||
			(result == CURLE_WRITE_ERROR && f->stopped == false))) {
		/* fetch completed normally or the server fed us a junk gzip
		 * stream (usually in the form of garbage at the end of the
		 * stream). Curl will have fed us all but the last chunk of
		 * decoded data, which is sad as, if we'd received the last
		 * chunk, too, we'd be able to render the whole object.
		 * As is, we'll just have to accept that the end of the
		 * object will be truncated in this case and leave it to
		 * the content handlers to cope.
		 */
		if (f->stopped ||
				(!f->had_headers &&
					fetch_curl_process_headers(f)))
			; /* redirect with no body or similar */
		else
			finished = true;
	} else if (result == CURLE_PARTIAL_FILE) {
		/* CURLE_PARTIAL_FILE occurs if the received body of a
		 * response is smaller than that specified in the
		 * Content-Length header. */
		if (!f->had_headers && fetch_curl_process_headers(f))
			; /* redirect with partial body, or similar */
		else {
			finished = true;
		}
	} else if (result == CURLE_WRITE_ERROR && f->stopped) {
		/* CURLE_WRITE_ERROR occurs when fetch_curl_data
		 * returns 0, which we use to abort intentionally */
		;
	} else if (result == CURLE_SSL_PEER_CERTIFICATE ||
			result == CURLE_SSL_CACERT) {
		memcpy(certs, f->cert_data, sizeof(certs));
		memset(f->cert_data, 0, sizeof(f->cert_data));
		cert = true;
	} else {
		LOG("Unknown cURL response code %d", result);
		error = true;
	}

	fetch_curl_stop(f);

	if (abort_fetch)
		; /* fetch was aborted: no callback */
	else if (finished) {
		msg.type = FETCH_FINISHED;
		fetch_send_callback(&msg, f->fetch_handle);
	} else if (cert) {
		int i;
		BIO *mem;
		BUF_MEM *buf;
		struct ssl_cert_info ssl_certs[MAX_CERTS];

		for (i = 0; i < MAX_CERTS && certs[i].cert; i++) {
			ssl_certs[i].version =
				X509_get_version(certs[i].cert);

			mem = BIO_new(BIO_s_mem());
			ASN1_TIME_print(mem,
					X509_get_notBefore(certs[i].cert));
			BIO_get_mem_ptr(mem, &buf);
			(void) BIO_set_close(mem, BIO_NOCLOSE);
			BIO_free(mem);
			memcpy(ssl_certs[i].not_before,
			       buf->data,
			       min(sizeof(ssl_certs[i].not_before) - 1,
				   (unsigned)buf->length));
			ssl_certs[i].not_before[min(sizeof(ssl_certs[i].not_before) - 1,
						    (unsigned)buf->length)] = 0;
			BUF_MEM_free(buf);

			mem = BIO_new(BIO_s_mem());
			ASN1_TIME_print(mem,
					X509_get_notAfter(certs[i].cert));
			BIO_get_mem_ptr(mem, &buf);
			(void) BIO_set_close(mem, BIO_NOCLOSE);
			BIO_free(mem);
			memcpy(ssl_certs[i].not_after,
			       buf->data,
			       min(sizeof(ssl_certs[i].not_after) - 1,
				   (unsigned)buf->length));
			ssl_certs[i].not_after[min(sizeof(ssl_certs[i].not_after) - 1,
						 (unsigned)buf->length)] = 0;

			BUF_MEM_free(buf);

			ssl_certs[i].sig_type =
				X509_get_signature_type(certs[i].cert);
			ssl_certs[i].serial =
				ASN1_INTEGER_get(
					X509_get_serialNumber(certs[i].cert));
			mem = BIO_new(BIO_s_mem());
			X509_NAME_print_ex(mem,
				X509_get_issuer_name(certs[i].cert),
				0, XN_FLAG_SEP_CPLUS_SPC |
					XN_FLAG_DN_REV | XN_FLAG_FN_NONE);
			BIO_get_mem_ptr(mem, &buf);
			(void) BIO_set_close(mem, BIO_NOCLOSE);
			BIO_free(mem);
			memcpy(ssl_certs[i].issuer,
			       buf->data,
			       min(sizeof(ssl_certs[i].issuer) - 1,
				   (unsigned) buf->length));
			ssl_certs[i].issuer[min(sizeof(ssl_certs[i].issuer) - 1,
						(unsigned) buf->length)] = 0;
			BUF_MEM_free(buf);

			mem = BIO_new(BIO_s_mem());
			X509_NAME_print_ex(mem,
				X509_get_subject_name(certs[i].cert),
					   0,
					   XN_FLAG_SEP_CPLUS_SPC |
					   XN_FLAG_DN_REV |
					   XN_FLAG_FN_NONE);
			BIO_get_mem_ptr(mem, &buf);
			(void) BIO_set_close(mem, BIO_NOCLOSE);
			BIO_free(mem);
			memcpy(ssl_certs[i].subject,
			       buf->data,
			       min(sizeof(ssl_certs[i].subject) - 1,
				   (unsigned)buf->length));
			ssl_certs[i].subject[min(sizeof(ssl_certs[i].subject) - 1,
						 (unsigned) buf->length)] = 0;
			BUF_MEM_free(buf);

			ssl_certs[i].cert_type =
				X509_certificate_type(certs[i].cert,
					X509_get_pubkey(certs[i].cert));

			/* and clean up */
			certs[i].cert->references--;
			if (certs[i].cert->references == 0)
				X509_free(certs[i].cert);
		}

		msg.type = FETCH_CERT_ERR;
		msg.data.cert_err.certs = ssl_certs;
		msg.data.cert_err.num_certs = i;
		fetch_send_callback(&msg, f->fetch_handle);
	} else if (error) {
		switch (result) {
		case CURLE_SSL_CONNECT_ERROR:
			msg.type = FETCH_SSL_ERR;
			break;

		case CURLE_OPERATION_TIMEDOUT:
			msg.type = FETCH_TIMEDOUT;
			msg.data.error = curl_easy_strerror(result);
			break;

		default:
			msg.type = FETCH_ERROR;
			msg.data.error = curl_easy_strerror(result);
		}

		fetch_send_callback(&msg, f->fetch_handle);
	}

	fetch_free(f->fetch_handle);
}
Ejemplo n.º 9
0
/* X509 ***********************************************************************/
long HsOpenSSL_X509_get_version(X509* x509) {
    return X509_get_version(x509);
}
Ejemplo n.º 10
0
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags,
                  unsigned long cflag)
{
    long l;
    int ret = 0, i;
    char *m = NULL, mlch = ' ';
    int nmindent = 0;
    ASN1_INTEGER *bs;
    EVP_PKEY *pkey = NULL;
    const char *neg;

    if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
        mlch = '\n';
        nmindent = 12;
    }

    if (nmflags == X509_FLAG_COMPAT)
        nmindent = 16;

    if (!(cflag & X509_FLAG_NO_HEADER)) {
        if (BIO_write(bp, "Certificate:\n", 13) <= 0)
            goto err;
        if (BIO_write(bp, "    Data:\n", 10) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_VERSION)) {
        l = X509_get_version(x);
        if (BIO_printf(bp, "%8sVersion: %lu (0x%lx)\n", "", l + 1, l) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_SERIAL)) {

        if (BIO_write(bp, "        Serial Number:", 22) <= 0)
            goto err;

        bs = X509_get_serialNumber(x);
        if (bs->length <= (int)sizeof(long)) {
                ERR_set_mark();
                l = ASN1_INTEGER_get(bs);
                ERR_pop_to_mark();
        } else {
            l = -1;
        }
        if (l != -1) {
            if (bs->type == V_ASN1_NEG_INTEGER) {
                l = -l;
                neg = "-";
            } else
                neg = "";
            if (BIO_printf(bp, " %s%lu (%s0x%lx)\n", neg, l, neg, l) <= 0)
                goto err;
        } else {
            neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : "";
            if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0)
                goto err;

            for (i = 0; i < bs->length; i++) {
                if (BIO_printf(bp, "%02x%c", bs->data[i],
                               ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
                    goto err;
            }
        }

    }

    if (!(cflag & X509_FLAG_NO_SIGNAME)) {
        X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x);
        if (X509_signature_print(bp, tsig_alg, NULL) <= 0)
            goto err;
    }

    if (!(cflag & X509_FLAG_NO_ISSUER)) {
        if (BIO_printf(bp, "        Issuer:%c", mlch) <= 0)
            goto err;
        if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags)
            < 0)
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_VALIDITY)) {
        if (BIO_write(bp, "        Validity\n", 17) <= 0)
            goto err;
        if (BIO_write(bp, "            Not Before: ", 24) <= 0)
            goto err;
        if (!ASN1_TIME_print(bp, X509_get_notBefore(x)))
            goto err;
        if (BIO_write(bp, "\n            Not After : ", 25) <= 0)
            goto err;
        if (!ASN1_TIME_print(bp, X509_get_notAfter(x)))
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_SUBJECT)) {
        if (BIO_printf(bp, "        Subject:%c", mlch) <= 0)
            goto err;
        if (X509_NAME_print_ex
            (bp, X509_get_subject_name(x), nmindent, nmflags) < 0)
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_PUBKEY)) {
        X509_PUBKEY *xpkey = X509_get_X509_PUBKEY(x);
        ASN1_OBJECT *xpoid;
        X509_PUBKEY_get0_param(&xpoid, NULL, NULL, NULL, xpkey);
        if (BIO_write(bp, "        Subject Public Key Info:\n", 33) <= 0)
            goto err;
        if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
            goto err;
        if (i2a_ASN1_OBJECT(bp, xpoid) <= 0)
            goto err;
        if (BIO_puts(bp, "\n") <= 0)
            goto err;

        pkey = X509_get_pubkey(x);
        if (pkey == NULL) {
            BIO_printf(bp, "%12sUnable to load Public Key\n", "");
            ERR_print_errors(bp);
        } else {
            EVP_PKEY_print_public(bp, pkey, 16, NULL);
            EVP_PKEY_free(pkey);
        }
    }

    if (!(cflag & X509_FLAG_NO_IDS)) {
        ASN1_BIT_STRING *iuid, *suid;
        X509_get0_uids(&iuid, &suid, x);
        if (iuid != NULL) {
            if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0)
                goto err;
            if (!X509_signature_dump(bp, iuid, 12))
                goto err;
        }
        if (suid != NULL) {
            if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0)
                goto err;
            if (!X509_signature_dump(bp, suid, 12))
                goto err;
        }
    }

    if (!(cflag & X509_FLAG_NO_EXTENSIONS))
        X509V3_extensions_print(bp, "X509v3 extensions",
                                X509_get0_extensions(x), cflag, 8);

    if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
        X509_ALGOR *sig_alg;
        ASN1_BIT_STRING *sig;
        X509_get0_signature(&sig, &sig_alg, x);
        if (X509_signature_print(bp, sig_alg, sig) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_AUX)) {
        if (!X509_aux_print(bp, x, 0))
            goto err;
    }
    ret = 1;
 err:
    OPENSSL_free(m);
    return (ret);
}
Ejemplo n.º 11
0
CERTIFICATE_CLASS::CERTIFICATE_CLASS(X509* x509_ptr)

//  DESCRIPTION     : Constructor that fills in the certificate values.
//  PRECONDITIONS   :
//  POSTCONDITIONS  :
//  EXCEPTIONS      : 
//  NOTES           :
//<<===========================================================================
{
	char* name_ptr;
	EVP_PKEY* publicKey_ptr;
		
	versionM = X509_get_version(x509_ptr) + 1/* change to 1 based*/;

	name_ptr = X509_NAME_oneline(X509_get_subject_name(x509_ptr), NULL, 0);
	if (name_ptr != NULL)
	{
		subjectM = name_ptr;
		OPENSSL_free(name_ptr);
	}
	else
	{
		subjectM = "";
	}

	name_ptr = X509_NAME_oneline(X509_get_issuer_name(x509_ptr), NULL, 0);
	if (name_ptr != NULL)
	{
		issuerM = name_ptr;;
		OPENSSL_free(name_ptr);
	}
	else
	{
		issuerM = "";
	}

	OPENSSL_CLASS::asn1TimeToTm(X509_get_notBefore(x509_ptr), effectiveDateM);

	OPENSSL_CLASS::asn1TimeToTm(X509_get_notAfter(x509_ptr), expirationDateM);
	
	signatureKeyLengthM = 0;
	signatureAlgorithmM = "";
	publicKey_ptr = X509_get_pubkey(x509_ptr);
	if (publicKey_ptr != NULL)
	{
		if (publicKey_ptr->type == EVP_PKEY_RSA)
		{
			signatureAlgorithmM = "RSA";
			if ((publicKey_ptr->pkey.rsa != NULL) && (publicKey_ptr->pkey.rsa->n != NULL))
			{
				signatureKeyLengthM = BN_num_bits(publicKey_ptr->pkey.rsa->n);
			}
		}
		else if (publicKey_ptr->type == EVP_PKEY_DSA)
		{
			signatureAlgorithmM = "DSA";
			if ((publicKey_ptr->pkey.dsa != NULL) && (publicKey_ptr->pkey.dsa->p != NULL))
			{
				signatureKeyLengthM = BN_num_bits(publicKey_ptr->pkey.dsa->p);
			}
		}

		EVP_PKEY_free(publicKey_ptr);
	}

	OPENSSL_CLASS::serialNumberToString(X509_get_serialNumber(x509_ptr), serialNumberM);
}
Ejemplo n.º 12
0
void anubis_dump_server_certificate(SSL *ssl) {
    X509 *x509Cert = SSL_get_peer_certificate(ssl);
    char buffer[1024];
    BIO *bio = NULL;
    char *buf = NULL;
    
    if(!x509Cert) {
        anubis_ssl_perror("SSL_get_peer_certificate()");
        return;
    }
    
    bio = BIO_new(BIO_s_mem());
    if(!bio) {
        anubis_ssl_perror("BIO_new()");
        X509_free(x509Cert);
        return;
    }//end if
    
    BIO_reset(bio);
    if(!PEM_write_bio_X509(bio, x509Cert)) {
        anubis_ssl_perror("PEM_write_bio_X509()");
        BIO_free(bio);
        X509_free(x509Cert);
        return;
    }
    BIO_get_mem_data(bio, &buf);
    anubis_out("Server certificate:\n%s", buf);
    // Cert Version
    long version = 0;
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_VERSION)) {
        version = X509_get_version(x509Cert);
        fprintf(out_stream, "Version: %ld\n", version);
    }//end if
    
    // Cert Serial No. - Code adapted from OpenSSL's crypto/asn1/t_x509.c
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_SERIAL)) {
        ASN1_INTEGER *bs;
        long l;
        int i;
        const char *neg;
        bs = X509_get_serialNumber(x509Cert);
        
        if (bs->length <= 4) {
            l = ASN1_INTEGER_get(bs);
            if (l < 0) {
                l= -l;
                neg = "-";
            }
            else
                neg = "";
            
            fprintf(out_stream, "Serial Number: %lu (%#lx)\n", l, l);
        }
        else {
            neg = (bs->type == V_ASN1_NEG_INTEGER)?" (Negative)":"";
            fprintf(out_stream, "Serial Number: %s", neg);
            for (i = 0; i < bs->length; i++) {
                fprintf(out_stream, "%02x%c", bs->data[i], (i+1 == bs->length)?'\n':':');
            }
        }
    }
    
    // Signature Algo...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_SIGNAME)) {
        i2a_ASN1_OBJECT(bio, x509Cert->cert_info->signature->algorithm);
        BIO_get_mem_data(bio, &buf);
        fprintf(out_stream, "Signature Algorithm:\n%s\n", buf);
    }
    
    // SSL Certificate Issuer...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_ISSUER)) {
        X509_NAME_oneline(X509_get_issuer_name(x509Cert), buffer, sizeof(buffer) - 1);
        fprintf(out_stream, "Issuer: %s\n", buffer);
    }
    
    // Validity...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_VALIDITY)) {
        BIO_reset(bio);
        ASN1_TIME_print(bio, X509_get_notBefore(x509Cert));
        BIO_get_mem_data(bio, &buf);
        fprintf(out_stream, "Not Valid Before: %s\n", buf);
        
        BIO_reset(bio);
        ASN1_TIME_print(bio, X509_get_notAfter(x509Cert));
        BIO_get_mem_data(bio, &buf);
        fprintf(out_stream, "Not Valid After: %s\n", buf);
    }
    
    // SSL Certificate Subject...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_SUBJECT)) {
        X509_NAME_oneline(X509_get_subject_name(x509Cert), buffer, sizeof(buffer) - 1);
        fprintf(out_stream, "Subject: %s\n", buffer);
    }
    
    // Public Key Algo...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_PUBKEY)) {
        BIO_reset(bio);
        i2a_ASN1_OBJECT(bio, x509Cert->cert_info->key->algor->algorithm);
        BIO_get_mem_data(bio, &buf);
        fprintf(out_stream, "Public Key Algorithm: %s\n", buf);
        
        // Public Key...
        EVP_PKEY *publicKey = NULL;
        publicKey = X509_get_pubkey(x509Cert);
        if (publicKey == NULL) {
            anubis_err("Public Key Could not load\n");
        }
        else {
            BIO_reset(bio);
            char *publicKeyType = NULL;
            int publicKeyLength = -1;
            switch (publicKey->type) {
                case EVP_PKEY_RSA:
                    
                    publicKeyType = "RSA";
                    
                    if (publicKey->pkey.rsa) {
                        publicKeyLength = BN_num_bits(publicKey->pkey.rsa->n);
                        RSA_print(bio, publicKey->pkey.rsa, 0);
                        BIO_get_mem_data(bio, &buf);
                    }
                    break;
                case EVP_PKEY_DSA:
                    
                    publicKeyType = "DSA";
                    
                    if (publicKey->pkey.dsa) {
                        DSA_print(bio, publicKey->pkey.dsa, 0);
                        BIO_get_mem_data(bio, &buf);
                    }
                    break;
                case EVP_PKEY_EC:
                    publicKeyType = "EC";
                    
                    if (publicKey->pkey.ec)  {
                        EC_KEY_print(bio, publicKey->pkey.ec, 0);
                        BIO_get_mem_data(bio, &buf);
                    }
                    break;
                default:
                    publicKeyType = "Unknown";
                    break;
            }
            
            EVP_PKEY_free(publicKey);
            fprintf(out_stream, "%d Public Key: ", publicKeyLength);
            if(!strcasecmp(publicKeyType, "RSA")) {
                fprintf(out_stream, "(%d bits)", publicKeyLength);
            }
            fprintf(out_stream, "\n");
            fprintf(out_stream, "%s\n", buf);
        }
    }
    
    // X509 v3...
    if (!(X509_FLAG_COMPAT & X509_FLAG_NO_EXTENSIONS) && sk_X509_EXTENSION_num(x509Cert->cert_info->extensions) > 0) {
        X509_EXTENSION *extension = NULL;
        ASN1_OBJECT *asn1Object = NULL;
        int tempInt2 = 0;
        BIO_reset(bio);
        for (int tempInt = 0; tempInt < sk_X509_EXTENSION_num(x509Cert->cert_info->extensions); tempInt++) {
            // Get Extension...
            extension = sk_X509_EXTENSION_value(x509Cert->cert_info->extensions, tempInt);
            
            asn1Object = X509_EXTENSION_get_object(extension);
            i2a_ASN1_OBJECT(bio, asn1Object);
            tempInt2 = X509_EXTENSION_get_critical(extension);
            BIO_printf(bio, ": %s\n", tempInt2 ? "critical" : "");
            
            // Print Extension value...
            if (!X509V3_EXT_print(bio, extension, X509_FLAG_COMPAT, 8)) {
                M_ASN1_OCTET_STRING_print(bio, extension->value);
            }
            BIO_printf(bio, "\n");
        }//end for
        
        BIO_get_mem_data(bio, &buf);
        fprintf(out_stream, "x509v3 Extensions: %s\n", buf);
    }//end if x509v3
    
    /*
    long verifyError = 0;
    // Verify Certificate...
    verifyError = SSL_get_verify_result(ssl);
    const char *verifyCertificate = "";
    if (verifyError == X509_V_OK)
        verifyCertificate = "Certificate passed verification";
    else
        verifyCertificate = X509_verify_cert_error_string(verifyError);
    fprintf(out_stream, "Validation: %s\n", verifyCertificate);
    */
    
    BIO_free(bio);
    X509_free(x509Cert);
    fflush(out_stream);
}//end anubis_dump_server_certificate
Ejemplo n.º 13
0
int SslCertificate::GetVersion() const
{
	ASSERT(!IsEmpty());
	return X509_get_version(cert);
}
Ejemplo n.º 14
0
/**
 * setup callback to allow the user to examine certificates which have
 * failed to validate during fetch.
 */
static void
curl_start_cert_validate(struct curl_fetch_info *f,
			 struct cert_info *certs)
{
	int depth;
	BIO *mem;
	BUF_MEM *buf;
	struct ssl_cert_info ssl_certs[MAX_CERTS];
	fetch_msg msg;

	for (depth = 0; depth <= f->cert_depth; depth++) {
		assert(certs[depth].cert != NULL);

		/* get certificate version */
		ssl_certs[depth].version = X509_get_version(certs[depth].cert);

		/* not before date */
		mem = BIO_new(BIO_s_mem());
		ASN1_TIME_print(mem, X509_get_notBefore(certs[depth].cert));
		BIO_get_mem_ptr(mem, &buf);
		(void) BIO_set_close(mem, BIO_NOCLOSE);
		BIO_free(mem);
		memcpy(ssl_certs[depth].not_before,
		       buf->data,
		       min(sizeof(ssl_certs[depth].not_before) - 1,
			   (unsigned)buf->length));
		ssl_certs[depth].not_before[min(sizeof(ssl_certs[depth].not_before) - 1,
					    (unsigned)buf->length)] = 0;
		BUF_MEM_free(buf);

		/* not after date */
		mem = BIO_new(BIO_s_mem());
		ASN1_TIME_print(mem,
				X509_get_notAfter(certs[depth].cert));
		BIO_get_mem_ptr(mem, &buf);
		(void) BIO_set_close(mem, BIO_NOCLOSE);
		BIO_free(mem);
		memcpy(ssl_certs[depth].not_after,
		       buf->data,
		       min(sizeof(ssl_certs[depth].not_after) - 1,
			   (unsigned)buf->length));
		ssl_certs[depth].not_after[min(sizeof(ssl_certs[depth].not_after) - 1,
					   (unsigned)buf->length)] = 0;
		BUF_MEM_free(buf);

		/* signature type */
		ssl_certs[depth].sig_type =
			X509_get_signature_type(certs[depth].cert);

		/* serial number */
		ssl_certs[depth].serial =
			ASN1_INTEGER_get(
				X509_get_serialNumber(certs[depth].cert));

		/* issuer name */
		mem = BIO_new(BIO_s_mem());
		X509_NAME_print_ex(mem,
				   X509_get_issuer_name(certs[depth].cert),
				   0, XN_FLAG_SEP_CPLUS_SPC |
				   XN_FLAG_DN_REV | XN_FLAG_FN_NONE);
		BIO_get_mem_ptr(mem, &buf);
		(void) BIO_set_close(mem, BIO_NOCLOSE);
		BIO_free(mem);
		memcpy(ssl_certs[depth].issuer,
		       buf->data,
		       min(sizeof(ssl_certs[depth].issuer) - 1,
			   (unsigned) buf->length));
		ssl_certs[depth].issuer[min(sizeof(ssl_certs[depth].issuer) - 1,
					(unsigned) buf->length)] = 0;
		BUF_MEM_free(buf);

		/* subject */
		mem = BIO_new(BIO_s_mem());
		X509_NAME_print_ex(mem,
				   X509_get_subject_name(certs[depth].cert),
				   0,
				   XN_FLAG_SEP_CPLUS_SPC |
				   XN_FLAG_DN_REV |
				   XN_FLAG_FN_NONE);
		BIO_get_mem_ptr(mem, &buf);
		(void) BIO_set_close(mem, BIO_NOCLOSE);
		BIO_free(mem);
		memcpy(ssl_certs[depth].subject,
		       buf->data,
		       min(sizeof(ssl_certs[depth].subject) - 1,
			   (unsigned)buf->length));
		ssl_certs[depth].subject[min(sizeof(ssl_certs[depth].subject) - 1,
					 (unsigned) buf->length)] = 0;
		BUF_MEM_free(buf);

		/* type of certificate */
		ssl_certs[depth].cert_type =
			X509_certificate_type(certs[depth].cert,
					      X509_get_pubkey(certs[depth].cert));

		/* and clean up */
		certs[depth].cert->references--;
		if (certs[depth].cert->references == 0) {
			X509_free(certs[depth].cert);
		}
	}

	msg.type = FETCH_CERT_ERR;
	msg.data.cert_err.certs = ssl_certs;
	msg.data.cert_err.num_certs = depth;
	fetch_send_callback(&msg, f->fetch_handle);
}
Ejemplo n.º 15
0
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, unsigned long cflag)
	{
	long l;
	int ret=0,i;
	char *m=NULL,mlch = ' ';
	int nmindent = 0;
	X509_CINF *ci;
	ASN1_INTEGER *bs;
	EVP_PKEY *pkey=NULL;
	const char *neg;
	ASN1_STRING *str=NULL;

	if((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
			mlch = '\n';
			nmindent = 12;
	}

	if(nmflags == X509_FLAG_COMPAT)
		nmindent = 16;

	ci=x->cert_info;
	if(!(cflag & X509_FLAG_NO_HEADER))
		{
		if (BIO_write(bp,"Certificate:\n",13) <= 0) goto err;
		if (BIO_write(bp,"    Data:\n",10) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_VERSION))
		{
		l=X509_get_version(x);
		if (BIO_printf(bp,"%8sVersion: %lu (0x%lx)\n","",l+1,l) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_SERIAL))
		{

		if (BIO_write(bp,"        Serial Number:",22) <= 0) goto err;

		bs=X509_get_serialNumber(x);
		if (bs->length <= 4)
			{
			l=ASN1_INTEGER_get(bs);
			if (l < 0)
				{
				l= -l;
				neg="-";
				}
			else
				neg="";
			if (BIO_printf(bp," %s%lu (%s0x%lx)\n",neg,l,neg,l) <= 0)
				goto err;
			}
		else
			{
			neg=(bs->type == V_ASN1_NEG_INTEGER)?" (Negative)":"";
			if (BIO_printf(bp,"\n%12s%s","",neg) <= 0) goto err;

			for (i=0; i<bs->length; i++)
				{
				if (BIO_printf(bp,"%02x%c",bs->data[i],
					((i+1 == bs->length)?'\n':':')) <= 0)
					goto err;
				}
			}

		}

	if(!(cflag & X509_FLAG_NO_SIGNAME))
		{
		if (BIO_printf(bp,"%8sSignature Algorithm: ","") <= 0) 
			goto err;
		if (i2a_ASN1_OBJECT(bp, ci->signature->algorithm) <= 0)
			goto err;
		if (BIO_puts(bp, "\n") <= 0)
			goto err;
		}

	if(!(cflag & X509_FLAG_NO_ISSUER))
		{
		if (BIO_printf(bp,"        Issuer:%c",mlch) <= 0) goto err;
		if (X509_NAME_print_ex(bp,X509_get_issuer_name(x),nmindent, nmflags) < 0) goto err;
		if (BIO_write(bp,"\n",1) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_VALIDITY))
		{
		if (BIO_write(bp,"        Validity\n",17) <= 0) goto err;
		if (BIO_write(bp,"            Not Before: ",24) <= 0) goto err;
		if (!ASN1_TIME_print(bp,X509_get_notBefore(x))) goto err;
		if (BIO_write(bp,"\n            Not After : ",25) <= 0) goto err;
		if (!ASN1_TIME_print(bp,X509_get_notAfter(x))) goto err;
		if (BIO_write(bp,"\n",1) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_SUBJECT))
		{
		if (BIO_printf(bp,"        Subject:%c",mlch) <= 0) goto err;
		if (X509_NAME_print_ex(bp,X509_get_subject_name(x),nmindent, nmflags) < 0) goto err;
		if (BIO_write(bp,"\n",1) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_PUBKEY))
		{
		if (BIO_write(bp,"        Subject Public Key Info:\n",33) <= 0)
			goto err;
		if (BIO_printf(bp,"%12sPublic Key Algorithm: ","") <= 0)
			goto err;
		if (i2a_ASN1_OBJECT(bp, ci->key->algor->algorithm) <= 0)
			goto err;
		if (BIO_puts(bp, "\n") <= 0)
			goto err;

		pkey=X509_get_pubkey(x);
		if (pkey == NULL)
			{
			BIO_printf(bp,"%12sUnable to load Public Key\n","");
			ERR_print_errors(bp);
			}
		else
#ifndef OPENSSL_NO_RSA
		if (pkey->type == EVP_PKEY_RSA)
			{
			BIO_printf(bp,"%12sRSA Public Key: (%d bit)\n","",
			BN_num_bits(pkey->pkey.rsa->n));
			RSA_print(bp,pkey->pkey.rsa,16);
			}
		else
#endif
#ifndef OPENSSL_NO_DSA
		if (pkey->type == EVP_PKEY_DSA)
			{
			BIO_printf(bp,"%12sDSA Public Key:\n","");
			DSA_print(bp,pkey->pkey.dsa,16);
			}
		else
#endif
#ifndef OPENSSL_NO_EC
		if (pkey->type == EVP_PKEY_EC)
			{
			BIO_printf(bp, "%12sEC Public Key:\n","");
			EC_KEY_print(bp, pkey->pkey.ec, 16);
			}
		else
#endif
			BIO_printf(bp,"%12sUnknown Public Key:\n","");

		EVP_PKEY_free(pkey);
		}

	if (!(cflag & X509_FLAG_NO_EXTENSIONS))
		X509V3_extensions_print(bp, "X509v3 extensions",
					ci->extensions, cflag, 8);

	if(!(cflag & X509_FLAG_NO_SIGDUMP))
		{
		if(X509_signature_print(bp, x->sig_alg, x->signature) <= 0) goto err;
		}
	if(!(cflag & X509_FLAG_NO_AUX))
		{
		if (!X509_CERT_AUX_print(bp, x->aux, 0)) goto err;
		}
	ret=1;
err:
	if (str != NULL) ASN1_STRING_free(str);
	if (m != NULL) OPENSSL_free(m);
	return(ret);
	}
Ejemplo n.º 16
0
static char *ssl_var_lookup_ssl_cert(apr_pool_t *p, request_rec *r, X509 *xs,
                                     char *var)
{
    char *result;
    BOOL resdup;
    X509_NAME *xsname;
    int nid;

    result = NULL;
    resdup = TRUE;

    if (strcEQ(var, "M_VERSION")) {
        result = apr_psprintf(p, "%lu", X509_get_version(xs)+1);
        resdup = FALSE;
    }
    else if (strcEQ(var, "M_SERIAL")) {
        result = ssl_var_lookup_ssl_cert_serial(p, xs);
    }
    else if (strcEQ(var, "V_START")) {
        result = ssl_var_lookup_ssl_cert_valid(p, X509_get_notBefore(xs));
    }
    else if (strcEQ(var, "V_END")) {
        result = ssl_var_lookup_ssl_cert_valid(p, X509_get_notAfter(xs));
    }
    else if (strcEQ(var, "V_REMAIN")) {
        result = ssl_var_lookup_ssl_cert_remain(p, X509_get_notAfter(xs));
        resdup = FALSE;
    }
    else if (*var && strcEQ(var+1, "_DN")) {
        if (*var == 'S')
            xsname = X509_get_subject_name(xs);
        else if (*var == 'I')
            xsname = X509_get_issuer_name(xs);
        else
            return NULL;
        result = ssl_var_lookup_ssl_cert_dn_oneline(p, r, xsname);
        resdup = FALSE;
    }
    else if (strlen(var) > 5 && strcEQn(var+1, "_DN_", 4)) {
        if (*var == 'S')
            xsname = X509_get_subject_name(xs);
        else if (*var == 'I')
            xsname = X509_get_issuer_name(xs);
        else
            return NULL;
        result = ssl_var_lookup_ssl_cert_dn(p, xsname, var+5);
        resdup = FALSE;
    }
    else if (strlen(var) > 4 && strcEQn(var, "SAN_", 4)) {
        result = ssl_var_lookup_ssl_cert_san(p, xs, var+4);
        resdup = FALSE;
    }
    else if (strcEQ(var, "A_SIG")) {
#if MODSSL_USE_OPENSSL_PRE_1_1_API
        nid = OBJ_obj2nid((ASN1_OBJECT *)(xs->cert_info->signature->algorithm));
#else
        const ASN1_OBJECT *paobj;
        X509_ALGOR_get0(&paobj, NULL, NULL, X509_get0_tbs_sigalg(xs));
        nid = OBJ_obj2nid(paobj);
#endif
        result = apr_pstrdup(p,
                             (nid == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(nid));
        resdup = FALSE;
    }
    else if (strcEQ(var, "A_KEY")) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
        nid = OBJ_obj2nid((ASN1_OBJECT *)(xs->cert_info->key->algor->algorithm));
#else
        ASN1_OBJECT *paobj;
        X509_PUBKEY_get0_param(&paobj, NULL, 0, NULL, X509_get_X509_PUBKEY(xs));
        nid = OBJ_obj2nid(paobj);
#endif
        result = apr_pstrdup(p,
                             (nid == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(nid));
        resdup = FALSE;
    }
    else if (strcEQ(var, "CERT")) {
        result = ssl_var_lookup_ssl_cert_PEM(p, xs);
    }

    if (resdup)
        result = apr_pstrdup(p, result);
    return result;
}
Ejemplo n.º 17
0
/*
 * Check for:
 *  - cert identity matching domain name
 *  - cert is within validity perios
 *  - digital sig is valid
 * Notes:
 * The default certificate format for openssl is PEM, which is base64
 * encoded DER with header/footer lines.
 * Certs in SSL protocol travel on the wire using DER encoding of ASN.1.
 * Refer to RFC 5280 for X.509 PKI Cert and CRL Profile
 * d2i (Der to Internal) APIs are used to convert certs on wire into internal
 * storage format for certs.
 */
verifyCertificate(sslStruct *sslC) {
	uchar *buff, *subj, *issuer;
	int version;
	const uchar *ptr, *tmpPtr;
	const uchar *data;
	size_t len, msgLen, totalCertLen, serverCertLen;
	size_t parsedLen = 0;
	size_t verifyCertLen;
	int count = 0;

#define CERT_LEN_INDEX 1
	// buff[0] points to Handshake Type - certificate
	buff = cfg.sslC->buff;
	len = cfg.sslC->buffLen; // Length of Certificate Packet
	msgLen = GET_BE16(&buff[CERT_LEN_INDEX+1]); // len - 4

	// From here is the payload. Starts from Cert Len (includes all Certs)
	totalCertLen = GET_BE16(&buff[CERT_LEN_INDEX+1+3]);
	// Now is the 1st Certificate - i.e. Server Cert
	serverCertLen = GET_BE16(&buff[CERT_LEN_INDEX+1+3+3]);
	printf(" Pkg Len = %d, Total Cert Len = %d\n", msgLen, totalCertLen);
    printf(" Server Certificate verification, Len: %d\n", serverCertLen);

	// Parse the Server Cert
	ptr = &buff[10];
	X509 *cert = d2i_X509(NULL, &ptr, serverCertLen);	
	if (cert == NULL) {
		printf("\n d2i_X509 returns NULL for Cert verification");
		return -1;
	}
	printf(".........Server Certificate........................\n");
	subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
	issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
	version = ((int)X509_get_version(cert)) + 1; // 0 indexed
	printf("Subject: %s, \nIssuer: %s, \n Version: %d", 
		subj, issuer, version);
	// Get Public Key Algorith Name
	int pkey = OBJ_obj2nid(cert->cert_info->key->algor->algorithm);
	if (pkey == NID_undef) {
		printf ("\n Cert Verify: unable to find signature algo");
		goto clean;
	}
	char sigalgo[100];
	const char * sslbuf = OBJ_nid2ln(pkey);
	if (strlen(sslbuf) > 100) {
		printf ("\n Cert Verify: len is greater than allocated");
		goto clean;
	}
	strncpy(sigalgo, sslbuf, 100);
	printf(", Public Key Algorithm Algorithm: %s", sigalgo);
	EVP_PKEY *public_key = X509_get_pubkey(cert);
	if (pkey == NID_rsaEncryption) {
		if (public_key == NULL) {
			printf("\nUnable to get public key from certificate");
			return -1;
		}
		char *rsa_e_dec, *rsa_n_hex;
		sslC->rsa_key = public_key->pkey.rsa;
		// Both the following are printable strings and need to be freed 
		// by caling OPENSSL_free()
		rsa_e_dec = BN_bn2dec(sslC->rsa_key->e); // RSA Exponent
		rsa_n_hex = BN_bn2hex(sslC->rsa_key->n); // RSA Modulus
		//printf("\n RSA Exponent = %s, \n RSA Modulus = %s", rsa_e_dec, rsa_n_hex);
	}
	EVP_PKEY_free(public_key);
clean:
	OPENSSL_free(subj); 
	OPENSSL_free(issuer); 

	// Parse the Server Cert Chain
	ptr = &buff[10+serverCertLen]; // Set ptr to point to next Cert Len field
	parsedLen = serverCertLen+3;
	tmpPtr = ptr+3;
	while (parsedLen < totalCertLen) {
		printf("\n.........Server Certificate Chain %d.............", count++);
		//printf("\n Len: Parsed: %d, Total: %d", parsedLen, totalCertLen);
		verifyCertLen = GET_BE16(&ptr[1]);
		printf("\nCert Chain Len: %d", verifyCertLen);
		X509 *cert = d2i_X509(NULL, &tmpPtr, serverCertLen);	
		if (cert == NULL) {
			printf("\n d2i_X509 returns NULL for Cert verification chain");
			return -1;
		}
		subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
		printf("\nSubject: %s", subj);
		OPENSSL_free(subj); 
		ptr += verifyCertLen + 3; // Set ptr to point to next Cert Len field
		tmpPtr = ptr+3;
		parsedLen += verifyCertLen+3;
	} // End parsing Cert Chain
	printf("\n..................................................\n");
}
Ejemplo n.º 18
0
IoCertificate *IoCertificate_version(IoCertificate *self, IoObject *locals, IoMessage *m)
{
	return IONUMBER(X509_get_version(X509(self)) + 1);
}
Ejemplo n.º 19
0
static PyObject *
_decode_certificate (X509 *certificate, int verbose) {

	PyObject *retval = NULL;
	BIO *biobuf = NULL;
	PyObject *peer;
	PyObject *peer_alt_names = NULL;
	PyObject *issuer;
	PyObject *version;
	PyObject *sn_obj;
	ASN1_INTEGER *serialNumber;
	char buf[2048];
	int len;
	ASN1_TIME *notBefore, *notAfter;
	PyObject *pnotBefore, *pnotAfter;

	retval = PyDict_New();
	if (retval == NULL)
		return NULL;

	peer = _create_tuple_for_X509_NAME(
		X509_get_subject_name(certificate));
	if (peer == NULL)
		goto fail0;
	if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
		Py_DECREF(peer);
		goto fail0;
	}
	Py_DECREF(peer);

	if (verbose) {
		issuer = _create_tuple_for_X509_NAME(
			X509_get_issuer_name(certificate));
		if (issuer == NULL)
			goto fail0;
		if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
			Py_DECREF(issuer);
			goto fail0;
		}
		Py_DECREF(issuer);

		version = PyLong_FromLong(X509_get_version(certificate) + 1);
		if (PyDict_SetItemString(retval, "version", version) < 0) {
			Py_DECREF(version);
			goto fail0;
		}
		Py_DECREF(version);
	}

	/* get a memory buffer */
	biobuf = BIO_new(BIO_s_mem());

	if (verbose) {

		(void) BIO_reset(biobuf);
		serialNumber = X509_get_serialNumber(certificate);
		/* should not exceed 20 octets, 160 bits, so buf is big enough */
		i2a_ASN1_INTEGER(biobuf, serialNumber);
		len = BIO_gets(biobuf, buf, sizeof(buf)-1);
		if (len < 0) {
			_setSSLError(NULL, 0, __FILE__, __LINE__);
			goto fail1;
		}
		sn_obj = PyUnicode_FromStringAndSize(buf, len);
		if (sn_obj == NULL)
			goto fail1;
		if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
			Py_DECREF(sn_obj);
			goto fail1;
		}
		Py_DECREF(sn_obj);

		(void) BIO_reset(biobuf);
		notBefore = X509_get_notBefore(certificate);
		ASN1_TIME_print(biobuf, notBefore);
		len = BIO_gets(biobuf, buf, sizeof(buf)-1);
		if (len < 0) {
			_setSSLError(NULL, 0, __FILE__, __LINE__);
			goto fail1;
		}
		pnotBefore = PyUnicode_FromStringAndSize(buf, len);
		if (pnotBefore == NULL)
			goto fail1;
		if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
			Py_DECREF(pnotBefore);
			goto fail1;
		}
		Py_DECREF(pnotBefore);
	}

	(void) BIO_reset(biobuf);
	notAfter = X509_get_notAfter(certificate);
	ASN1_TIME_print(biobuf, notAfter);
	len = BIO_gets(biobuf, buf, sizeof(buf)-1);
	if (len < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		goto fail1;
	}
	pnotAfter = PyUnicode_FromStringAndSize(buf, len);
	if (pnotAfter == NULL)
		goto fail1;
	if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
		Py_DECREF(pnotAfter);
		goto fail1;
	}
	Py_DECREF(pnotAfter);

	/* Now look for subjectAltName */

	peer_alt_names = _get_peer_alt_names(certificate);
	if (peer_alt_names == NULL)
		goto fail1;
	else if (peer_alt_names != Py_None) {
		if (PyDict_SetItemString(retval, "subjectAltName",
					 peer_alt_names) < 0) {
			Py_DECREF(peer_alt_names);
			goto fail1;
		}
		Py_DECREF(peer_alt_names);
	}

	BIO_free(biobuf);
	return retval;

  fail1:
	if (biobuf != NULL)
		BIO_free(biobuf);
  fail0:
	Py_XDECREF(retval);
	return NULL;
}
int HttpCgiTool::buildCommonEnv(IEnv *pEnv, HttpSession *pSession)
{
    int count = 0;
    HttpReq *pReq = pSession->getReq();
    const char *pTemp;
    int n;
    char buf[128];
    RadixNode *pNode;

    pTemp = pReq->getAuthUser();
    if (pTemp)
    {
        //NOTE: only Basic is support now
        pEnv->add("AUTH_TYPE", 9, "Basic", 5);
        pEnv->add("REMOTE_USER", 11, pTemp, strlen(pTemp));
        count += 2;
    }
    //ADD_ENV("REMOTE_IDENT", "" )        //TODO: not supported yet
    //extensions of CGI/1.1
    const AutoStr2 *pDocRoot = pReq->getDocRoot();
    pEnv->add("DOCUMENT_ROOT", 13,
              pDocRoot->c_str(), pDocRoot->len() - 1);
    pEnv->add("REMOTE_ADDR", 11, pSession->getPeerAddrString(),
              pSession->getPeerAddrStrLen());

    n = ls_snprintf(buf, 10, "%hu", pSession->getRemotePort());
    pEnv->add("REMOTE_PORT", 11, buf, n);

    n = pSession->getServerAddrStr(buf, 128);

    pEnv->add("SERVER_ADDR", 11, buf, n);

    pEnv->add("SERVER_NAME", 11, pReq->getHostStr(),  pReq->getHostStrLen());
    const AutoStr2 &sPort = pReq->getPortStr();
    pEnv->add("SERVER_PORT", 11, sPort.c_str(), sPort.len());
    pEnv->add("REQUEST_URI", 11, pReq->getOrgReqURL(),
              pReq->getOrgReqURLLen());
    count += 7;

    n = pReq->getPathInfoLen();
    if (n > 0)
    {
        int m;
        char achTranslated[10240];
        m =  pReq->translatePath(pReq->getPathInfo(), n,
                                 achTranslated, sizeof(achTranslated));
        if (m != -1)
        {
            pEnv->add("PATH_TRANSLATED", 15, achTranslated, m);
            ++count;
        }
        pEnv->add("PATH_INFO", 9, pReq->getPathInfo(), n);
        ++count;
    }

    //add geo IP env here
    if (pReq->isGeoIpOn())
    {
        GeoInfo *pInfo = pSession->getClientInfo()->getGeoInfo();
        if (pInfo)
        {
            pEnv->add("GEOIP_ADDR", 10, pSession->getPeerAddrString(),
                      pSession->getPeerAddrStrLen());
            count += pInfo->addGeoEnv(pEnv) + 1;
        }
    }
    n = pReq->getEnvCount();
    count += n;
    if ((pNode = (RadixNode *)pReq->getEnvNode()) != NULL)
        pNode->for_each2(addEnv, pEnv);

    if (pSession->getStream()->isSpdy())
    {
        const char *pProto = HioStream::getProtocolName((HiosProtocol)
                             pSession->getStream()->getProtocol());
        pEnv->add("X_SPDY", 6, pProto, strlen(pProto));
        ++count;
    }

    if (pSession->isSSL())
    {
        SslConnection *pSSL = pSession->getSSL();
        pEnv->add("HTTPS", 5, "on",  2);
        const char *pVersion = pSSL->getVersion();
        n = strlen(pVersion);
        pEnv->add("SSL_VERSION", 11, pVersion, n);
        count += 2;
        SSL_SESSION *pSession = pSSL->getSession();
        if (pSession)
        {
            int idLen = SslConnection::getSessionIdLen(pSession);
            n = idLen * 2;
            assert(n < (int)sizeof(buf));
            StringTool::hexEncode(
                (char *)SslConnection::getSessionId(pSession),
                idLen, buf);
            pEnv->add("SSL_SESSION_ID", 14, buf, n);
            ++count;
        }

        const SSL_CIPHER *pCipher = pSSL->getCurrentCipher();
        if (pCipher)
        {
            const char *pName = pSSL->getCipherName();
            n = strlen(pName);
            pEnv->add("SSL_CIPHER", 10, pName, n);
            int algkeysize;
            int keysize = SslConnection::getCipherBits(pCipher, &algkeysize);
            n = ls_snprintf(buf, 20, "%d", keysize);
            pEnv->add("SSL_CIPHER_USEKEYSIZE", 21, buf, n);
            n = ls_snprintf(buf, 20, "%d", algkeysize);
            pEnv->add("SSL_CIPHER_ALGKEYSIZE", 21, buf, n);
            count += 3;
        }

        int i = pSSL->getVerifyMode();
        if (i != 0)
        {
            char achBuf[4096];
            X509 *pClientCert = pSSL->getPeerCertificate();
            if (pSSL->isVerifyOk())
            {
                if (pClientCert)
                {
                    //IMPROVE: too many deep copy here.
                    //n = SslCert::PEMWriteCert( pClientCert, achBuf, 4096 );
                    //if ((n>0)&&( n <= 4096 ))
                    //{
                    //    pEnv->add( "SSL_CLIENT_CERT", 15, achBuf, n );
                    //    ++count;
                    //}
                    n = snprintf(achBuf, sizeof(achBuf), "%lu",
                                 X509_get_version(pClientCert) + 1);
                    pEnv->add("SSL_CLIENT_M_VERSION", 20, achBuf, n);
                    ++count;
                    n = lookup_ssl_cert_serial(pClientCert, achBuf, 4096);
                    if (n != -1)
                    {
                        pEnv->add("SSL_CLIENT_M_SERIAL", 19, achBuf, n);
                        ++count;
                    }
                    X509_NAME_oneline(X509_get_subject_name(pClientCert), achBuf, 4096);
                    pEnv->add("SSL_CLIENT_S_DN", 15, achBuf, strlen(achBuf));
                    ++count;
                    X509_NAME_oneline(X509_get_issuer_name(pClientCert), achBuf, 4096);
                    pEnv->add("SSL_CLIENT_I_DN", 15, achBuf, strlen(achBuf));
                    ++count;
                    if (SslConnection::isClientVerifyOptional(i))
                    {
                        strcpy(achBuf, "GENEROUS");
                        n = 8;
                    }
                    else
                    {
                        strcpy(achBuf, "SUCCESS");
                        n = 7;
                    }
                }
                else
                {
                    strcpy(achBuf, "NONE");
                    n = 4;
                }
            }
            else
                n = pSSL->buildVerifyErrorString(achBuf, sizeof(achBuf));
            pEnv->add("SSL_CLIENT_VERIFY", 17, achBuf, n);
            ++count;
        }

    }
    return count;
}
Ejemplo n.º 21
0
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags,
                  unsigned long cflag)
{
    long l;
    int ret = 0, i;
    char *m = NULL, mlch = ' ';
    int nmindent = 0;
    X509_CINF *ci;
    ASN1_INTEGER *bs;
    EVP_PKEY *pkey = NULL;
    const char *neg;

    if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
        mlch = '\n';
        nmindent = 12;
    }

    if (nmflags == X509_FLAG_COMPAT)
        nmindent = 16;

    ci = x->cert_info;
    if (!(cflag & X509_FLAG_NO_HEADER)) {
        if (BIO_write(bp, "Certificate:\n", 13) <= 0)
            goto err;
        if (BIO_write(bp, "    Data:\n", 10) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_VERSION)) {
        l = X509_get_version(x);
        if (BIO_printf(bp, "%8sVersion: %lu (0x%lx)\n", "", l + 1, l) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_SERIAL)) {

        if (BIO_write(bp, "        Serial Number:", 22) <= 0)
            goto err;

        bs = X509_get_serialNumber(x);
        if (bs->length < (int)sizeof(long)
            || (bs->length == sizeof(long) && (bs->data[0] & 0x80) == 0)) {
            l = ASN1_INTEGER_get(bs);
            if (bs->type == V_ASN1_NEG_INTEGER) {
                l = -l;
                neg = "-";
            } else
                neg = "";
            if (BIO_printf(bp, " %s%lu (%s0x%lx)\n", neg, l, neg, l) <= 0)
                goto err;
        } else {
            neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : "";
            if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0)
                goto err;

            for (i = 0; i < bs->length; i++) {
                if (BIO_printf(bp, "%02x%c", bs->data[i],
                               ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
                    goto err;
            }
        }

    }

    if (!(cflag & X509_FLAG_NO_SIGNAME)) {
        if (X509_signature_print(bp, ci->signature, NULL) <= 0)
            goto err;
    }

    if (!(cflag & X509_FLAG_NO_ISSUER)) {
        if (BIO_printf(bp, "        Issuer:%c", mlch) <= 0)
            goto err;
        if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags)
            < 0)
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_VALIDITY)) {
        if (BIO_write(bp, "        Validity\n", 17) <= 0)
            goto err;
        if (BIO_write(bp, "            Not Before: ", 24) <= 0)
            goto err;
        if (!ASN1_TIME_print(bp, X509_get_notBefore(x)))
            goto err;
        if (BIO_write(bp, "\n            Not After : ", 25) <= 0)
            goto err;
        if (!ASN1_TIME_print(bp, X509_get_notAfter(x)))
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_SUBJECT)) {
        if (BIO_printf(bp, "        Subject:%c", mlch) <= 0)
            goto err;
        if (X509_NAME_print_ex
            (bp, X509_get_subject_name(x), nmindent, nmflags) < 0)
            goto err;
        if (BIO_write(bp, "\n", 1) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_PUBKEY)) {
        if (BIO_write(bp, "        Subject Public Key Info:\n", 33) <= 0)
            goto err;
        if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
            goto err;
        if (i2a_ASN1_OBJECT(bp, ci->key->algor->algorithm) <= 0)
            goto err;
        if (BIO_puts(bp, "\n") <= 0)
            goto err;

        pkey = X509_get_pubkey(x);
        if (pkey == NULL) {
            BIO_printf(bp, "%12sUnable to load Public Key\n", "");
            ERR_print_errors(bp);
        } else {
            EVP_PKEY_print_public(bp, pkey, 16, NULL);
            EVP_PKEY_free(pkey);
        }
    }

    if (!(cflag & X509_FLAG_NO_IDS)) {
        if (ci->issuerUID) {
            if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0)
                goto err;
            if (!X509_signature_dump(bp, ci->issuerUID, 12))
                goto err;
        }
        if (ci->subjectUID) {
            if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0)
                goto err;
            if (!X509_signature_dump(bp, ci->subjectUID, 12))
                goto err;
        }
    }

    if (!(cflag & X509_FLAG_NO_EXTENSIONS))
        X509V3_extensions_print(bp, "X509v3 extensions",
                                ci->extensions, cflag, 8);

    if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
        if (X509_signature_print(bp, x->sig_alg, x->signature) <= 0)
            goto err;
    }
    if (!(cflag & X509_FLAG_NO_AUX)) {
        if (!X509_CERT_AUX_print(bp, x->aux, 0))
            goto err;
    }
    ret = 1;
 err:
    if (m != NULL)
        OPENSSL_free(m);
    return (ret);
}
Ejemplo n.º 22
0
void check(unsigned char *cert_buffer, size_t cert_len, CertFormat format, CertType type)
{
	X509_NAME *issuer;
	X509_NAME *subject;
	int ret;
	X509 *x509;
	int ca;
	struct tm tm_before;
	struct tm tm_after;

	Clear();

	x509 = LoadCert(cert_buffer, cert_len, format);
	if (x509 == NULL)
	{
		SetError(ERR_INVALID);
		return;
	}

	ca = X509_check_ca(x509);
	if (ca > 0 && type == SubscriberCertificate)
	{
		SetWarning(WARN_CHECKED_AS_SUBSCRIBER);
	}
	else if (ca == 0 && type != SubscriberCertificate)
	{
		SetWarning(WARN_CHECKED_AS_CA);
	}

	ret = X509_get_version(x509);
	if (ret != 2)
	{
		SetError(ERR_NOT_VERSION3);
	}
	//CheckASN1_integer(x509->cert_info->version);

	issuer = X509_get_issuer_name(x509);
	if (issuer == NULL)
	{
		SetError(ERR_INVALID);
		return;
	}
	CheckDN(issuer);

	CheckSerial(x509);
	CheckTime(x509, &tm_before, &tm_after, type);

	/* Required by CAB base 9.1.3 */
	if (!IsNameObjPresent(issuer, obj_organizationName))
	{
		SetError(ERR_ISSUER_ORG_NAME);
	}

	/* Required by CAB base 9.1.4 */
	if (!IsNameObjPresent(issuer, obj_countryName))
	{
		SetError(ERR_ISSUER_COUNTRY);
	}

	subject = X509_get_subject_name(x509);
	if (subject == NULL)
	{
		SetError(ERR_INVALID);
		return;
	}
	CheckDN(subject);

	CheckDuplicateExtensions(x509);

	/* Prohibited in CAB base 7.1.4.2.2d */
	if (!IsNameObjPresent(subject, obj_organizationName)
		&& !IsNameObjPresent(subject, obj_givenName)
		&& !IsNameObjPresent(subject, obj_surname)
		&& IsNameObjPresent(subject, obj_StreetAddress))
	{
		SetError(ERR_SUBJECT_ADDR);
	}

	/* Required in CAB base 7.1.4.2.2e and 7.1.4.2.2f */
	if (((IsNameObjPresent(subject, obj_organizationName) && type == SubscriberCertificate) ||
		IsNameObjPresent(subject, obj_givenName) ||
		IsNameObjPresent(subject, obj_surname))
		&& !IsNameObjPresent(subject, obj_stateOrProvinceName)
		&& !IsNameObjPresent(subject, obj_localityName))
	{
		SetError(ERR_SUBJECT_ORG_NO_PLACE);
	}

	/* Prohibited in CAB base 7.1.4.2.2e or 7.1.4.2.2f */
	if (!IsNameObjPresent(subject, obj_organizationName)
		&& !IsNameObjPresent(subject, obj_givenName)
		&& !IsNameObjPresent(subject, obj_surname)
		&& (IsNameObjPresent(subject, obj_localityName)
			|| IsNameObjPresent(subject, obj_stateOrProvinceName)))
	{
		SetError(ERR_SUBJECT_NO_ORG_PLACE);
	}

	/* Required by CAB base 7.1.4.2.2g */
	if (!IsNameObjPresent(subject, obj_organizationName)
		&& !IsNameObjPresent(subject, obj_givenName)
		&& !IsNameObjPresent(subject, obj_surname)
		&& IsNameObjPresent(subject, obj_postalCode))
	{
		SetError(ERR_SUBJECT_POSTAL);
	}

	/* Required by CAB base 7.1.4.2.2h */
	if ((IsNameObjPresent(subject, obj_organizationName) ||
		IsNameObjPresent(subject, obj_givenName) ||
		IsNameObjPresent(subject, obj_surname))
		&& !IsNameObjPresent(subject, obj_countryName))
	{
		SetError(ERR_SUBJECT_COUNTRY);
	}

	CheckPolicy(x509, type, subject);
	CheckEKU(x509, type);
	CheckSAN(x509, type);

	/* Deprecated in CAB base 7.1.4.2.2a */
	if (IsNameObjPresent(subject, obj_commonName))
	{
		if (type == SubscriberCertificate)
		{
			SetInfo(INF_SUBJECT_CN);
		}
	}
	else if (type != SubscriberCertificate)
	{
		SetWarning(WARN_NO_CN);
	}

	CheckCRL(x509);
	CheckAIA(x509, type);
	CheckPublicKey(x509, tm_after);

	X509_free(x509);
}
Ejemplo n.º 23
0
static void x509v3_cache_extensions(X509 *x)
{
  BASIC_CONSTRAINTS *bs;
  PROXY_CERT_INFO_EXTENSION *pci;
  ASN1_BIT_STRING *usage;
  ASN1_BIT_STRING *ns;
  EXTENDED_KEY_USAGE *extusage;
  X509_EXTENSION *ex;
  
  int i;
  if(x->ex_flags & EXFLAG_SET) return;
#ifndef OPENSSL_NO_SHA
  X509_digest(x, EVP_sha1(), x->sha1_hash, NULL);
#endif
  /* Does subject name match issuer ? */
  if(!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x)))
       x->ex_flags |= EXFLAG_SS;
  /* V1 should mean no extensions ... */
  if(!X509_get_version(x)) x->ex_flags |= EXFLAG_V1;
  /* Handle basic constraints */
  if((bs=X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL))) {
    if(bs->ca) x->ex_flags |= EXFLAG_CA;
    if(bs->pathlen) {
      if((bs->pathlen->type == V_ASN1_NEG_INTEGER)
            || !bs->ca) {
        x->ex_flags |= EXFLAG_INVALID;
        x->ex_pathlen = 0;
      } else x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
    } else x->ex_pathlen = -1;
    BASIC_CONSTRAINTS_free(bs);
    x->ex_flags |= EXFLAG_BCONS;
  }
  /* Handle proxy certificates */
  if((pci=X509_get_ext_d2i(x, NID_proxyCertInfo, NULL, NULL))) {
    if (x->ex_flags & EXFLAG_CA
        || X509_get_ext_by_NID(x, NID_subject_alt_name, 0) >= 0
        || X509_get_ext_by_NID(x, NID_issuer_alt_name, 0) >= 0) {
      x->ex_flags |= EXFLAG_INVALID;
    }
    if (pci->pcPathLengthConstraint) {
      x->ex_pcpathlen =
        ASN1_INTEGER_get(pci->pcPathLengthConstraint);
    } else x->ex_pcpathlen = -1;
    PROXY_CERT_INFO_EXTENSION_free(pci);
    x->ex_flags |= EXFLAG_PROXY;
  }
  /* Handle key usage */
  if((usage=X509_get_ext_d2i(x, NID_key_usage, NULL, NULL))) {
    if(usage->length > 0) {
      x->ex_kusage = usage->data[0];
      if(usage->length > 1) 
        x->ex_kusage |= usage->data[1] << 8;
    } else x->ex_kusage = 0;
    x->ex_flags |= EXFLAG_KUSAGE;
    ASN1_BIT_STRING_free(usage);
  }
  x->ex_xkusage = 0;
  if((extusage=X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL))) {
    x->ex_flags |= EXFLAG_XKUSAGE;
    for(i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
      switch(OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage,i))) {
        case NID_server_auth:
        x->ex_xkusage |= XKU_SSL_SERVER;
        break;

        case NID_client_auth:
        x->ex_xkusage |= XKU_SSL_CLIENT;
        break;

        case NID_email_protect:
        x->ex_xkusage |= XKU_SMIME;
        break;

        case NID_code_sign:
        x->ex_xkusage |= XKU_CODE_SIGN;
        break;

        case NID_ms_sgc:
        case NID_ns_sgc:
        x->ex_xkusage |= XKU_SGC;
        break;

        case NID_OCSP_sign:
        x->ex_xkusage |= XKU_OCSP_SIGN;
        break;

        case NID_time_stamp:
        x->ex_xkusage |= XKU_TIMESTAMP;
        break;

        case NID_dvcs:
        x->ex_xkusage |= XKU_DVCS;
        break;
      }
    }
    sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
  }

  if((ns=X509_get_ext_d2i(x, NID_netscape_cert_type, NULL, NULL))) {
    if(ns->length > 0) x->ex_nscert = ns->data[0];
    else x->ex_nscert = 0;
    x->ex_flags |= EXFLAG_NSCERT;
    ASN1_BIT_STRING_free(ns);
  }
  x->skid =X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL);
  x->akid =X509_get_ext_d2i(x, NID_authority_key_identifier, NULL, NULL);
  for (i = 0; i < X509_get_ext_count(x); i++)
    {
    ex = X509_get_ext(x, i);
    if (!X509_EXTENSION_get_critical(ex))
      continue;
    if (!X509_supported_extension(ex))
      {
      x->ex_flags |= EXFLAG_CRITICAL;
      break;
      }
    }
  x->ex_flags |= EXFLAG_SET;
}
Ejemplo n.º 24
0
int X509Certificate_OpenSSL::getVersion() const
{
	return (int)X509_get_version(m_data->cert);	
}