• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use core::{ffi, fmt, ptr, str};
15 use std::net::IpAddr;
16 
17 use libc::{c_int, c_long, c_uint};
18 
19 use super::bio::BioSlice;
20 use super::error::{error_get_lib, error_get_reason, ErrorStack};
21 use super::ffi::err::{ERR_clear_error, ERR_peek_last_error};
22 use super::ffi::pem::PEM_read_bio_X509;
23 use super::ffi::x509::{
24     d2i_X509, X509_STORE_add_cert, X509_STORE_free, X509_STORE_new, X509_VERIFY_PARAM_free,
25     X509_VERIFY_PARAM_set1_host, X509_VERIFY_PARAM_set1_ip, X509_VERIFY_PARAM_set_hostflags,
26     X509_verify_cert_error_string, STACK_X509, X509_STORE, X509_VERIFY_PARAM,
27 };
28 use super::foreign::{Foreign, ForeignRef};
29 use super::stack::Stackof;
30 use super::{check_ptr, check_ret, ssl_init};
31 use crate::util::c_openssl::ffi::x509::{X509_free, C_X509};
32 
33 foreign_type!(
34     type CStruct = C_X509;
35     fn drop = X509_free;
36     pub(crate) struct X509;
37     pub(crate) struct X509Ref;
38 );
39 
40 const ERR_LIB_PEM: c_int = 9;
41 const PEM_R_NO_START_LINE: c_int = 108;
42 
43 impl X509 {
from_pem(pem: &[u8]) -> Result<X509, ErrorStack>44     pub(crate) fn from_pem(pem: &[u8]) -> Result<X509, ErrorStack> {
45         ssl_init();
46         let bio = BioSlice::from_byte(pem)?;
47         let ptr = check_ptr(unsafe {
48             PEM_read_bio_X509(bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut())
49         })?;
50         Ok(X509::from_ptr(ptr))
51     }
52 
from_der(der: &[u8]) -> Result<X509, ErrorStack>53     pub(crate) fn from_der(der: &[u8]) -> Result<X509, ErrorStack> {
54         ssl_init();
55         let len =
56             ::std::cmp::min(der.len(), ::libc::c_long::max_value() as usize) as ::libc::c_long;
57         let ptr = check_ptr(unsafe { d2i_X509(ptr::null_mut(), &mut der.as_ptr(), len) })?;
58         Ok(X509::from_ptr(ptr))
59     }
60 
61     /// Deserializes a list of PEM-formatted certificates.
stack_from_pem(pem: &[u8]) -> Result<Vec<X509>, ErrorStack>62     pub(crate) fn stack_from_pem(pem: &[u8]) -> Result<Vec<X509>, ErrorStack> {
63         unsafe {
64             ssl_init();
65             let bio = BioSlice::from_byte(pem)?;
66 
67             let mut certs = vec![];
68             loop {
69                 let r = PEM_read_bio_X509(bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut());
70                 if r.is_null() {
71                     let err = ERR_peek_last_error();
72                     if error_get_lib(err) == ERR_LIB_PEM
73                         && error_get_reason(err) == PEM_R_NO_START_LINE
74                     {
75                         ERR_clear_error();
76                         break;
77                     }
78 
79                     return Err(ErrorStack::get());
80                 } else {
81                     certs.push(X509(r));
82                 }
83             }
84             Ok(certs)
85         }
86     }
87 }
88 
89 impl Stackof for X509 {
90     type StackType = STACK_X509;
91 }
92 
93 #[derive(Copy, Clone, PartialEq, Eq)]
94 pub(crate) struct X509VerifyResult(c_int);
95 
96 impl X509VerifyResult {
error_string(&self) -> &'static str97     fn error_string(&self) -> &'static str {
98         ssl_init();
99         unsafe {
100             let s = X509_verify_cert_error_string(self.0 as c_long);
101             str::from_utf8(ffi::CStr::from_ptr(s).to_bytes()).unwrap_or("")
102         }
103     }
104 
from_raw(err: c_int) -> X509VerifyResult105     pub(crate) fn from_raw(err: c_int) -> X509VerifyResult {
106         X509VerifyResult(err)
107     }
108 }
109 
110 impl fmt::Display for X509VerifyResult {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result111     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
112         fmt.write_str(self.error_string())
113     }
114 }
115 
116 #[cfg(test)]
117 impl fmt::Debug for X509VerifyResult {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result118     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
119         fmt.debug_struct("X509VerifyResult")
120             .field("code", &self.0)
121             .field("error", &self.error_string())
122             .finish()
123     }
124 }
125 
126 foreign_type!(
127     type CStruct = X509_STORE;
128     fn drop = X509_STORE_free;
129     pub(crate) struct X509Store;
130     pub(crate) struct X509StoreRef;
131 );
132 
133 impl X509Store {
new() -> Result<X509Store, ErrorStack>134     pub(crate) fn new() -> Result<X509Store, ErrorStack> {
135         ssl_init();
136         Ok(X509Store(check_ptr(unsafe { X509_STORE_new() })?))
137     }
138 }
139 
140 impl X509StoreRef {
add_cert(&mut self, cert: X509) -> Result<(), ErrorStack>141     pub(crate) fn add_cert(&mut self, cert: X509) -> Result<(), ErrorStack> {
142         check_ret(unsafe { X509_STORE_add_cert(self.as_ptr(), cert.as_ptr()) }).map(|_| ())
143     }
144 }
145 
146 foreign_type!(
147     type CStruct = X509_VERIFY_PARAM;
148     fn drop = X509_VERIFY_PARAM_free;
149     pub(crate) struct X509VerifyParam;
150     pub(crate) struct X509VerifyParamRef;
151 );
152 
153 pub(crate) const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4;
154 
155 impl X509VerifyParamRef {
set_hostflags(&mut self, hostflags: c_uint)156     pub(crate) fn set_hostflags(&mut self, hostflags: c_uint) {
157         unsafe {
158             X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags);
159         }
160     }
161 
set_host(&mut self, host: &str) -> Result<(), ErrorStack>162     pub(crate) fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> {
163         check_ret(unsafe {
164             X509_VERIFY_PARAM_set1_host(self.as_ptr(), host.as_ptr() as *const _, host.len())
165         })
166         .map(|_| ())
167     }
168 
set_ip(&mut self, ip_addr: IpAddr) -> Result<(), ErrorStack>169     pub(crate) fn set_ip(&mut self, ip_addr: IpAddr) -> Result<(), ErrorStack> {
170         let mut v = [0u8; 16];
171         let len = match ip_addr {
172             IpAddr::V4(addr) => {
173                 v[..4].copy_from_slice(&addr.octets());
174                 4
175             }
176             IpAddr::V6(addr) => {
177                 v.copy_from_slice(&addr.octets());
178                 16
179             }
180         };
181         check_ret(unsafe { X509_VERIFY_PARAM_set1_ip(self.as_ptr(), v.as_ptr() as *const _, len) })
182             .map(|_| ())
183     }
184 }
185