use ffi;
use foreign_types::{ForeignType, ForeignTypeRef};
use libc::{c_int, c_long};
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt;
use std::marker::PhantomData;
use std::mem;
use std::path::Path;
use std::ptr;
use std::slice;
use std::str;
use asn1::{Asn1BitStringRef, Asn1IntegerRef, Asn1ObjectRef, Asn1StringRef, Asn1TimeRef};
use bio::MemBioSlice;
use conf::ConfRef;
use error::ErrorStack;
use ex_data::Index;
use hash::{DigestBytes, MessageDigest};
use nid::Nid;
use pkey::{HasPrivate, HasPublic, PKey, PKeyRef, Public};
use ssl::SslRef;
use stack::{Stack, StackRef, Stackable};
use string::OpensslString;
use {cvt, cvt_n, cvt_p};
#[cfg(any(ossl102, libressl261))]
pub mod verify;
pub mod extension;
pub mod store;
#[cfg(test)]
mod tests;
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_STORE_CTX;
fn drop = ffi::X509_STORE_CTX_free;
pub struct X509StoreContext;
pub struct X509StoreContextRef;
}
impl X509StoreContext {
pub fn ssl_idx() -> Result<Index<X509StoreContext, SslRef>, ErrorStack> {
unsafe { cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx()).map(|idx| Index::from_raw(idx)) }
}
pub fn new() -> Result<X509StoreContext, ErrorStack> {
unsafe {
ffi::init();
cvt_p(ffi::X509_STORE_CTX_new()).map(X509StoreContext)
}
}
}
impl X509StoreContextRef {
pub fn ex_data<T>(&self, index: Index<X509StoreContext, T>) -> Option<&T> {
unsafe {
let data = ffi::X509_STORE_CTX_get_ex_data(self.as_ptr(), index.as_raw());
if data.is_null() {
None
} else {
Some(&*(data as *const T))
}
}
}
pub fn error(&self) -> X509VerifyResult {
unsafe { X509VerifyResult::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr())) }
}
pub fn init<F, T>(
&mut self,
trust: &store::X509StoreRef,
cert: &X509Ref,
cert_chain: &StackRef<X509>,
with_context: F,
) -> Result<T, ErrorStack>
where
F: FnOnce(&mut X509StoreContextRef) -> Result<T, ErrorStack>,
{
struct Cleanup<'a>(&'a mut X509StoreContextRef);
impl<'a> Drop for Cleanup<'a> {
fn drop(&mut self) {
unsafe {
ffi::X509_STORE_CTX_cleanup(self.0.as_ptr());
}
}
}
unsafe {
cvt(ffi::X509_STORE_CTX_init(
self.as_ptr(),
trust.as_ptr(),
cert.as_ptr(),
cert_chain.as_ptr(),
))?;
let cleanup = Cleanup(self);
with_context(cleanup.0)
}
}
pub fn verify_cert(&mut self) -> Result<bool, ErrorStack> {
unsafe { cvt_n(ffi::X509_verify_cert(self.as_ptr())).map(|n| n != 0) }
}
pub fn set_error(&mut self, result: X509VerifyResult) {
unsafe {
ffi::X509_STORE_CTX_set_error(self.as_ptr(), result.as_raw());
}
}
pub fn current_cert(&self) -> Option<&X509Ref> {
unsafe {
let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(X509Ref::from_ptr(ptr))
}
}
}
pub fn error_depth(&self) -> u32 {
unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 }
}
pub fn chain(&self) -> Option<&StackRef<X509>> {
unsafe {
let chain = X509_STORE_CTX_get0_chain(self.as_ptr());
if chain.is_null() {
None
} else {
Some(StackRef::from_ptr(chain))
}
}
}
}
pub struct X509Builder(X509);
impl X509Builder {
pub fn new() -> Result<X509Builder, ErrorStack> {
unsafe {
ffi::init();
cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p)))
}
}
pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> {
unsafe { cvt(X509_set1_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) }
}
pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> {
unsafe { cvt(X509_set1_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) }
}
pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) }
}
pub fn set_serial_number(&mut self, serial_number: &Asn1IntegerRef) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_set_serialNumber(
self.0.as_ptr(),
serial_number.as_ptr(),
))
.map(|_| ())
}
}
pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_set_issuer_name(
self.0.as_ptr(),
issuer_name.as_ptr(),
))
.map(|_| ())
}
}
pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_set_subject_name(
self.0.as_ptr(),
subject_name.as_ptr(),
))
.map(|_| ())
}
}
pub fn set_pubkey<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where
T: HasPublic,
{
unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) }
}
pub fn x509v3_context<'a>(
&'a self,
issuer: Option<&'a X509Ref>,
conf: Option<&'a ConfRef>,
) -> X509v3Context<'a> {
unsafe {
let mut ctx = mem::zeroed();
let issuer = match issuer {
Some(issuer) => issuer.as_ptr(),
None => self.0.as_ptr(),
};
let subject = self.0.as_ptr();
ffi::X509V3_set_ctx(
&mut ctx,
issuer,
subject,
ptr::null_mut(),
ptr::null_mut(),
0,
);
if let Some(conf) = conf {
ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr());
}
X509v3Context(ctx, PhantomData)
}
}
pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> {
self.append_extension2(&extension)
}
pub fn append_extension2(&mut self, extension: &X509ExtensionRef) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1))?;
Ok(())
}
}
pub fn sign<T>(&mut self, key: &PKeyRef<T>, hash: MessageDigest) -> Result<(), ErrorStack>
where
T: HasPrivate,
{
unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) }
}
pub fn build(self) -> X509 {
self.0
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509;
fn drop = ffi::X509_free;
pub struct X509;
pub struct X509Ref;
}
impl X509Ref {
pub fn subject_name(&self) -> &X509NameRef {
unsafe {
let name = ffi::X509_get_subject_name(self.as_ptr());
assert!(!name.is_null());
X509NameRef::from_ptr(name)
}
}
pub fn issuer_name(&self) -> &X509NameRef {
unsafe {
let name = ffi::X509_get_issuer_name(self.as_ptr());
assert!(!name.is_null());
X509NameRef::from_ptr(name)
}
}
pub fn subject_alt_names(&self) -> Option<Stack<GeneralName>> {
unsafe {
let stack = ffi::X509_get_ext_d2i(
self.as_ptr(),
ffi::NID_subject_alt_name,
ptr::null_mut(),
ptr::null_mut(),
);
if stack.is_null() {
None
} else {
Some(Stack::from_ptr(stack as *mut _))
}
}
}
pub fn issuer_alt_names(&self) -> Option<Stack<GeneralName>> {
unsafe {
let stack = ffi::X509_get_ext_d2i(
self.as_ptr(),
ffi::NID_issuer_alt_name,
ptr::null_mut(),
ptr::null_mut(),
);
if stack.is_null() {
None
} else {
Some(Stack::from_ptr(stack as *mut _))
}
}
}
pub fn public_key(&self) -> Result<PKey<Public>, ErrorStack> {
unsafe {
let pkey = cvt_p(ffi::X509_get_pubkey(self.as_ptr()))?;
Ok(PKey::from_ptr(pkey))
}
}
pub fn digest(&self, hash_type: MessageDigest) -> Result<DigestBytes, ErrorStack> {
unsafe {
let mut digest = DigestBytes {
buf: [0; ffi::EVP_MAX_MD_SIZE as usize],
len: ffi::EVP_MAX_MD_SIZE as usize,
};
let mut len = ffi::EVP_MAX_MD_SIZE;
cvt(ffi::X509_digest(
self.as_ptr(),
hash_type.as_ptr(),
digest.buf.as_mut_ptr() as *mut _,
&mut len,
))?;
digest.len = len as usize;
Ok(digest)
}
}
#[deprecated(since = "0.10.9", note = "renamed to digest")]
pub fn fingerprint(&self, hash_type: MessageDigest) -> Result<Vec<u8>, ErrorStack> {
self.digest(hash_type).map(|b| b.to_vec())
}
pub fn not_after(&self) -> &Asn1TimeRef {
unsafe {
let date = X509_getm_notAfter(self.as_ptr());
assert!(!date.is_null());
Asn1TimeRef::from_ptr(date)
}
}
pub fn not_before(&self) -> &Asn1TimeRef {
unsafe {
let date = X509_getm_notBefore(self.as_ptr());
assert!(!date.is_null());
Asn1TimeRef::from_ptr(date)
}
}
pub fn signature(&self) -> &Asn1BitStringRef {
unsafe {
let mut signature = ptr::null();
X509_get0_signature(&mut signature, ptr::null_mut(), self.as_ptr());
assert!(!signature.is_null());
Asn1BitStringRef::from_ptr(signature as *mut _)
}
}
pub fn signature_algorithm(&self) -> &X509AlgorithmRef {
unsafe {
let mut algor = ptr::null();
X509_get0_signature(ptr::null_mut(), &mut algor, self.as_ptr());
assert!(!algor.is_null());
X509AlgorithmRef::from_ptr(algor as *mut _)
}
}
pub fn ocsp_responders(&self) -> Result<Stack<OpensslString>, ErrorStack> {
unsafe { cvt_p(ffi::X509_get1_ocsp(self.as_ptr())).map(|p| Stack::from_ptr(p)) }
}
pub fn issued(&self, subject: &X509Ref) -> X509VerifyResult {
unsafe {
let r = ffi::X509_check_issued(self.as_ptr(), subject.as_ptr());
X509VerifyResult::from_raw(r)
}
}
pub fn verify<T>(&self, key: &PKeyRef<T>) -> Result<bool, ErrorStack>
where
T: HasPublic,
{
unsafe { cvt_n(ffi::X509_verify(self.as_ptr(), key.as_ptr())).map(|n| n != 0) }
}
pub fn serial_number(&self) -> &Asn1IntegerRef {
unsafe {
let r = ffi::X509_get_serialNumber(self.as_ptr());
assert!(!r.is_null());
Asn1IntegerRef::from_ptr(r)
}
}
to_pem! {
to_pem,
ffi::PEM_write_bio_X509
}
to_der! {
to_der,
ffi::i2d_X509
}
}
impl ToOwned for X509Ref {
type Owned = X509;
fn to_owned(&self) -> X509 {
unsafe {
X509_up_ref(self.as_ptr());
X509::from_ptr(self.as_ptr())
}
}
}
impl X509 {
pub fn builder() -> Result<X509Builder, ErrorStack> {
X509Builder::new()
}
from_pem! {
from_pem,
X509,
ffi::PEM_read_bio_X509
}
from_der! {
from_der,
X509,
ffi::d2i_X509
}
pub fn stack_from_pem(pem: &[u8]) -> Result<Vec<X509>, ErrorStack> {
unsafe {
ffi::init();
let bio = MemBioSlice::new(pem)?;
let mut certs = vec![];
loop {
let r =
ffi::PEM_read_bio_X509(bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut());
if r.is_null() {
let err = ffi::ERR_peek_last_error();
if ffi::ERR_GET_LIB(err) == ffi::ERR_LIB_PEM
&& ffi::ERR_GET_REASON(err) == ffi::PEM_R_NO_START_LINE
{
ffi::ERR_clear_error();
break;
}
return Err(ErrorStack::get());
} else {
certs.push(X509(r));
}
}
Ok(certs)
}
}
}
impl Clone for X509 {
fn clone(&self) -> X509 {
X509Ref::to_owned(self)
}
}
impl fmt::Debug for X509 {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let serial = match &self.serial_number().to_bn() {
Ok(bn) => match bn.to_hex_str() {
Ok(hex) => hex.to_string(),
Err(_) => "".to_string(),
},
Err(_) => "".to_string(),
};
let mut debug_struct = formatter.debug_struct("X509");
debug_struct.field("serial_number", &serial);
debug_struct.field("signature_algorithm", &self.signature_algorithm().object());
debug_struct.field("issuer", &self.issuer_name());
debug_struct.field("subject", &self.subject_name());
if let Some(subject_alt_names) = &self.subject_alt_names() {
debug_struct.field("subject_alt_names", subject_alt_names);
}
debug_struct.field("not_before", &self.not_before());
debug_struct.field("not_after", &self.not_after());
if let Ok(public_key) = &self.public_key() {
debug_struct.field("public_key", public_key);
};
debug_struct.finish()
}
}
impl AsRef<X509Ref> for X509Ref {
fn as_ref(&self) -> &X509Ref {
self
}
}
impl Stackable for X509 {
type StackType = ffi::stack_st_X509;
}
pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>);
impl<'a> X509v3Context<'a> {
pub fn as_ptr(&self) -> *mut ffi::X509V3_CTX {
&self.0 as *const _ as *mut _
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_EXTENSION;
fn drop = ffi::X509_EXTENSION_free;
pub struct X509Extension;
pub struct X509ExtensionRef;
}
impl Stackable for X509Extension {
type StackType = ffi::stack_st_X509_EXTENSION;
}
impl X509Extension {
pub fn new(
conf: Option<&ConfRef>,
context: Option<&X509v3Context>,
name: &str,
value: &str,
) -> Result<X509Extension, ErrorStack> {
let name = CString::new(name).unwrap();
let value = CString::new(value).unwrap();
unsafe {
ffi::init();
let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr);
let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr);
let name = name.as_ptr() as *mut _;
let value = value.as_ptr() as *mut _;
cvt_p(ffi::X509V3_EXT_nconf(conf, context, name, value)).map(X509Extension)
}
}
pub fn new_nid(
conf: Option<&ConfRef>,
context: Option<&X509v3Context>,
name: Nid,
value: &str,
) -> Result<X509Extension, ErrorStack> {
let value = CString::new(value).unwrap();
unsafe {
ffi::init();
let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr);
let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr);
let name = name.as_raw();
let value = value.as_ptr() as *mut _;
cvt_p(ffi::X509V3_EXT_nconf_nid(conf, context, name, value)).map(X509Extension)
}
}
}
pub struct X509NameBuilder(X509Name);
impl X509NameBuilder {
pub fn new() -> Result<X509NameBuilder, ErrorStack> {
unsafe {
ffi::init();
cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p)))
}
}
pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> {
unsafe {
let field = CString::new(field).unwrap();
assert!(value.len() <= c_int::max_value() as usize);
cvt(ffi::X509_NAME_add_entry_by_txt(
self.0.as_ptr(),
field.as_ptr() as *mut _,
ffi::MBSTRING_UTF8,
value.as_ptr(),
value.len() as c_int,
-1,
0,
))
.map(|_| ())
}
}
pub fn append_entry_by_nid(&mut self, field: Nid, value: &str) -> Result<(), ErrorStack> {
unsafe {
assert!(value.len() <= c_int::max_value() as usize);
cvt(ffi::X509_NAME_add_entry_by_NID(
self.0.as_ptr(),
field.as_raw(),
ffi::MBSTRING_UTF8,
value.as_ptr() as *mut _,
value.len() as c_int,
-1,
0,
))
.map(|_| ())
}
}
pub fn build(self) -> X509Name {
self.0
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_NAME;
fn drop = ffi::X509_NAME_free;
pub struct X509Name;
pub struct X509NameRef;
}
impl X509Name {
pub fn builder() -> Result<X509NameBuilder, ErrorStack> {
X509NameBuilder::new()
}
pub fn load_client_ca_file<P: AsRef<Path>>(file: P) -> Result<Stack<X509Name>, ErrorStack> {
let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
unsafe { cvt_p(ffi::SSL_load_client_CA_file(file.as_ptr())).map(|p| Stack::from_ptr(p)) }
}
}
impl Stackable for X509Name {
type StackType = ffi::stack_st_X509_NAME;
}
impl X509NameRef {
pub fn entries_by_nid(&self, nid: Nid) -> X509NameEntries<'_> {
X509NameEntries {
name: self,
nid: Some(nid),
loc: -1,
}
}
pub fn entries(&self) -> X509NameEntries<'_> {
X509NameEntries {
name: self,
nid: None,
loc: -1,
}
}
}
impl fmt::Debug for X509NameRef {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_list().entries(self.entries()).finish()
}
}
pub struct X509NameEntries<'a> {
name: &'a X509NameRef,
nid: Option<Nid>,
loc: c_int,
}
impl<'a> Iterator for X509NameEntries<'a> {
type Item = &'a X509NameEntryRef;
fn next(&mut self) -> Option<&'a X509NameEntryRef> {
unsafe {
match self.nid {
Some(nid) => {
self.loc =
ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), nid.as_raw(), self.loc);
if self.loc == -1 {
return None;
}
}
None => {
self.loc += 1;
if self.loc >= ffi::X509_NAME_entry_count(self.name.as_ptr()) {
return None;
}
}
}
let entry = ffi::X509_NAME_get_entry(self.name.as_ptr(), self.loc);
assert!(!entry.is_null());
Some(X509NameEntryRef::from_ptr(entry))
}
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_NAME_ENTRY;
fn drop = ffi::X509_NAME_ENTRY_free;
pub struct X509NameEntry;
pub struct X509NameEntryRef;
}
impl X509NameEntryRef {
pub fn data(&self) -> &Asn1StringRef {
unsafe {
let data = ffi::X509_NAME_ENTRY_get_data(self.as_ptr());
Asn1StringRef::from_ptr(data)
}
}
pub fn object(&self) -> &Asn1ObjectRef {
unsafe {
let object = ffi::X509_NAME_ENTRY_get_object(self.as_ptr());
Asn1ObjectRef::from_ptr(object)
}
}
}
impl fmt::Debug for X509NameEntryRef {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_fmt(format_args!("{:?} = {:?}", self.object(), self.data()))
}
}
pub struct X509ReqBuilder(X509Req);
impl X509ReqBuilder {
pub fn new() -> Result<X509ReqBuilder, ErrorStack> {
unsafe {
ffi::init();
cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p)))
}
}
pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::X509_REQ_set_version(self.0.as_ptr(), version.into())).map(|_| ()) }
}
pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_REQ_set_subject_name(
self.0.as_ptr(),
subject_name.as_ptr(),
))
.map(|_| ())
}
}
pub fn set_pubkey<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where
T: HasPublic,
{
unsafe { cvt(ffi::X509_REQ_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) }
}
pub fn x509v3_context<'a>(&'a self, conf: Option<&'a ConfRef>) -> X509v3Context<'a> {
unsafe {
let mut ctx = mem::zeroed();
ffi::X509V3_set_ctx(
&mut ctx,
ptr::null_mut(),
ptr::null_mut(),
self.0.as_ptr(),
ptr::null_mut(),
0,
);
if let Some(conf) = conf {
ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr());
}
X509v3Context(ctx, PhantomData)
}
}
pub fn add_extensions(
&mut self,
extensions: &StackRef<X509Extension>,
) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::X509_REQ_add_extensions(
self.0.as_ptr(),
extensions.as_ptr(),
))
.map(|_| ())
}
}
pub fn sign<T>(&mut self, key: &PKeyRef<T>, hash: MessageDigest) -> Result<(), ErrorStack>
where
T: HasPrivate,
{
unsafe {
cvt(ffi::X509_REQ_sign(
self.0.as_ptr(),
key.as_ptr(),
hash.as_ptr(),
))
.map(|_| ())
}
}
pub fn build(self) -> X509Req {
self.0
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_REQ;
fn drop = ffi::X509_REQ_free;
pub struct X509Req;
pub struct X509ReqRef;
}
impl X509Req {
pub fn builder() -> Result<X509ReqBuilder, ErrorStack> {
X509ReqBuilder::new()
}
from_pem! {
from_pem,
X509Req,
ffi::PEM_read_bio_X509_REQ
}
from_der! {
from_der,
X509Req,
ffi::d2i_X509_REQ
}
}
impl X509ReqRef {
to_pem! {
to_pem,
ffi::PEM_write_bio_X509_REQ
}
to_der! {
to_der,
ffi::i2d_X509_REQ
}
pub fn version(&self) -> i32 {
unsafe { X509_REQ_get_version(self.as_ptr()) as i32 }
}
pub fn subject_name(&self) -> &X509NameRef {
unsafe {
let name = X509_REQ_get_subject_name(self.as_ptr());
assert!(!name.is_null());
X509NameRef::from_ptr(name)
}
}
pub fn public_key(&self) -> Result<PKey<Public>, ErrorStack> {
unsafe {
let key = cvt_p(ffi::X509_REQ_get_pubkey(self.as_ptr()))?;
Ok(PKey::from_ptr(key))
}
}
pub fn verify<T>(&self, key: &PKeyRef<T>) -> Result<bool, ErrorStack>
where
T: HasPublic,
{
unsafe { cvt_n(ffi::X509_REQ_verify(self.as_ptr(), key.as_ptr())).map(|n| n != 0) }
}
pub fn extensions(&self) -> Result<Stack<X509Extension>, ErrorStack> {
unsafe {
let extensions = cvt_p(ffi::X509_REQ_get_extensions(self.as_ptr()))?;
Ok(Stack::from_ptr(extensions))
}
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct X509VerifyResult(c_int);
impl fmt::Debug for X509VerifyResult {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("X509VerifyResult")
.field("code", &self.0)
.field("error", &self.error_string())
.finish()
}
}
impl fmt::Display for X509VerifyResult {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(self.error_string())
}
}
impl Error for X509VerifyResult {}
impl X509VerifyResult {
pub unsafe fn from_raw(err: c_int) -> X509VerifyResult {
X509VerifyResult(err)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn as_raw(&self) -> c_int {
self.0
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn error_string(&self) -> &'static str {
ffi::init();
unsafe {
let s = ffi::X509_verify_cert_error_string(self.0 as c_long);
str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap()
}
}
pub const OK: X509VerifyResult = X509VerifyResult(ffi::X509_V_OK);
pub const APPLICATION_VERIFICATION: X509VerifyResult =
X509VerifyResult(ffi::X509_V_ERR_APPLICATION_VERIFICATION);
}
foreign_type_and_impl_send_sync! {
type CType = ffi::GENERAL_NAME;
fn drop = ffi::GENERAL_NAME_free;
pub struct GeneralName;
pub struct GeneralNameRef;
}
impl GeneralNameRef {
fn ia5_string(&self, ffi_type: c_int) -> Option<&str> {
unsafe {
if (*self.as_ptr()).type_ != ffi_type {
return None;
}
let ptr = ASN1_STRING_get0_data((*self.as_ptr()).d as *mut _);
let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _);
let slice = slice::from_raw_parts(ptr as *const u8, len as usize);
str::from_utf8(slice).ok()
}
}
pub fn email(&self) -> Option<&str> {
self.ia5_string(ffi::GEN_EMAIL)
}
pub fn dnsname(&self) -> Option<&str> {
self.ia5_string(ffi::GEN_DNS)
}
pub fn uri(&self) -> Option<&str> {
self.ia5_string(ffi::GEN_URI)
}
pub fn ipaddress(&self) -> Option<&[u8]> {
unsafe {
if (*self.as_ptr()).type_ != ffi::GEN_IPADD {
return None;
}
let ptr = ASN1_STRING_get0_data((*self.as_ptr()).d as *mut _);
let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _);
Some(slice::from_raw_parts(ptr as *const u8, len as usize))
}
}
}
impl fmt::Debug for GeneralNameRef {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if let Some(email) = self.email() {
formatter.write_str(email)
} else if let Some(dnsname) = self.dnsname() {
formatter.write_str(dnsname)
} else if let Some(uri) = self.uri() {
formatter.write_str(uri)
} else if let Some(ipaddress) = self.ipaddress() {
let result = String::from_utf8_lossy(ipaddress);
formatter.write_str(&result)
} else {
formatter.write_str("(empty)")
}
}
}
impl Stackable for GeneralName {
type StackType = ffi::stack_st_GENERAL_NAME;
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_ALGOR;
fn drop = ffi::X509_ALGOR_free;
pub struct X509Algorithm;
pub struct X509AlgorithmRef;
}
impl X509AlgorithmRef {
pub fn object(&self) -> &Asn1ObjectRef {
unsafe {
let mut oid = ptr::null();
X509_ALGOR_get0(&mut oid, ptr::null_mut(), ptr::null_mut(), self.as_ptr());
assert!(!oid.is_null());
Asn1ObjectRef::from_ptr(oid as *mut _)
}
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::X509_OBJECT;
fn drop = X509_OBJECT_free;
pub struct X509Object;
pub struct X509ObjectRef;
}
impl X509ObjectRef {
pub fn x509(&self) -> Option<&X509Ref> {
unsafe {
let ptr = X509_OBJECT_get0_X509(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(X509Ref::from_ptr(ptr))
}
}
}
}
impl Stackable for X509Object {
type StackType = ffi::stack_st_X509_OBJECT;
}
cfg_if! {
if #[cfg(any(ossl110, libressl273))] {
use ffi::{X509_getm_notAfter, X509_getm_notBefore, X509_up_ref, X509_get0_signature};
} else {
#[allow(bad_style)]
unsafe fn X509_getm_notAfter(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME {
(*(*(*x).cert_info).validity).notAfter
}
#[allow(bad_style)]
unsafe fn X509_getm_notBefore(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME {
(*(*(*x).cert_info).validity).notBefore
}
#[allow(bad_style)]
unsafe fn X509_up_ref(x: *mut ffi::X509) {
ffi::CRYPTO_add_lock(
&mut (*x).references,
1,
ffi::CRYPTO_LOCK_X509,
"mod.rs\0".as_ptr() as *const _,
line!() as c_int,
);
}
#[allow(bad_style)]
unsafe fn X509_get0_signature(
psig: *mut *const ffi::ASN1_BIT_STRING,
palg: *mut *const ffi::X509_ALGOR,
x: *const ffi::X509,
) {
if !psig.is_null() {
*psig = (*x).signature;
}
if !palg.is_null() {
*palg = (*x).sig_alg;
}
}
}
}
cfg_if! {
if #[cfg(ossl110)] {
use ffi::{
X509_ALGOR_get0, ASN1_STRING_get0_data, X509_STORE_CTX_get0_chain, X509_set1_notAfter,
X509_set1_notBefore, X509_REQ_get_version, X509_REQ_get_subject_name,
};
} else {
use ffi::{
ASN1_STRING_data as ASN1_STRING_get0_data,
X509_STORE_CTX_get_chain as X509_STORE_CTX_get0_chain,
X509_set_notAfter as X509_set1_notAfter,
X509_set_notBefore as X509_set1_notBefore,
};
#[allow(bad_style)]
unsafe fn X509_REQ_get_version(x: *mut ffi::X509_REQ) -> ::libc::c_long {
ffi::ASN1_INTEGER_get((*(*x).req_info).version)
}
#[allow(bad_style)]
unsafe fn X509_REQ_get_subject_name(x: *mut ffi::X509_REQ) -> *mut ::ffi::X509_NAME {
(*(*x).req_info).subject
}
#[allow(bad_style)]
unsafe fn X509_ALGOR_get0(
paobj: *mut *const ffi::ASN1_OBJECT,
pptype: *mut c_int,
pval: *mut *mut ::libc::c_void,
alg: *const ffi::X509_ALGOR,
) {
if !paobj.is_null() {
*paobj = (*alg).algorithm;
}
assert!(pptype.is_null());
assert!(pval.is_null());
}
}
}
cfg_if! {
if #[cfg(any(ossl110, libressl270))] {
use ffi::X509_OBJECT_get0_X509;
} else {
#[allow(bad_style)]
unsafe fn X509_OBJECT_get0_X509(x: *mut ffi::X509_OBJECT) -> *mut ffi::X509 {
if (*x).type_ == ffi::X509_LU_X509 {
(*x).data.x509
} else {
ptr::null_mut()
}
}
}
}
cfg_if! {
if #[cfg(ossl110)] {
use ffi::X509_OBJECT_free;
} else {
#[allow(bad_style)]
unsafe fn X509_OBJECT_free(x: *mut ffi::X509_OBJECT) {
ffi::X509_OBJECT_free_contents(x);
ffi::CRYPTO_free(x as *mut libc::c_void);
}
}
}