1use std::path::{Path, PathBuf};
9
10use clap::clap_app;
11use pcs::{DcapArtifactIssuer, PckID, WriteOptionsBuilder};
12use reqwest::Url;
13use rustc_serialize::hex::ToHex;
14use serde::de::{value, IntoDeserializer};
15use serde::Deserialize;
16
17use crate::{
18 AzureProvisioningClientBuilder, Error, IntelProvisioningClientBuilder,
19 PccsProvisioningClientBuilder, PcsVersion, ProvisioningClient, StatusCode,
20};
21
22const DEFAULT_ORIGIN: &'static str = "intel";
25const DEFAULT_API_VERSION: &'static str = "4";
26
27#[derive(Debug, Deserialize, Copy, Clone, Eq, PartialEq, Hash)]
28#[serde(rename_all = "kebab-case")]
29enum Origin {
30 Intel,
31 Azure,
32 Pccs,
33}
34
35fn str_deserialize<'a>(s: &'a str) -> value::StrDeserializer<'a, value::Error> {
36 s.into_deserializer()
37}
38
39fn parse_origin(p: &str) -> Result<Origin, String> {
40 Origin::deserialize(str_deserialize(p)).map_err(|e| e.to_string())
41}
42
43fn download_dcap_artifacts(
44 prov_client: &dyn ProvisioningClient,
45 pckid_file: &str,
46 output_dir: &str,
47 verbose: bool,
48) -> Result<(), Error> {
49 for (idx, pckid) in PckID::parse_file(&PathBuf::from(&pckid_file).as_path())?
50 .iter()
51 .enumerate()
52 {
53 let enc_ppid = &pckid.enc_ppid.as_slice();
54 if verbose {
55 println!("==[ entry {} ]==", idx);
56 println!(" Info:");
57 println!(" Encr. PPID: {}", enc_ppid.to_hex(),);
58 println!(" pce_id: {}", &&pckid.pce_id.to_le_bytes().to_hex());
59 println!(" cpu svn: {}", pckid.cpu_svn.as_slice().to_hex());
60 println!(
61 " pce isvsvn: {}",
62 pckid.pce_isvsvn.to_le_bytes().to_hex()
63 );
64 println!(" qe_id: {}", pckid.qe_id.as_slice().to_hex());
65 println!(" Storing artifacts:");
66 }
67
68 let pckcerts = prov_client.pckcerts_with_fallback(&pckid)?;
71
72 let pckcerts_file = pckcerts.write_to_file(
73 output_dir,
74 pckid.qe_id.as_slice(),
75 WriteOptionsBuilder::new().build(),
76 )?;
77
78 if verbose {
79 println!(" pckcerts: {}", pckcerts_file.unwrap().display());
80 }
81
82 let fmspc = pckcerts.fmspc()?;
83 let evaluation_data_numbers = prov_client.sgx_tcb_evaluation_data_numbers()?;
84
85 let file = evaluation_data_numbers
86 .write_to_file(output_dir, WriteOptionsBuilder::new().build())?;
87 if verbose {
88 println!(
89 " tcb evaluation data numbers: {}\n",
90 file.unwrap().display()
91 );
92 }
93
94 for number in evaluation_data_numbers.evaluation_data_numbers()?.numbers() {
95 let tcb_info = prov_client.sgx_tcbinfo(&fmspc, Some(number.number()));
96
97 match tcb_info {
98 Ok(tcb_info) => {
99 let file =
100 tcb_info.write_to_file(output_dir, WriteOptionsBuilder::new().build())?;
101 if verbose {
102 println!(" tcb info: {}", file.unwrap().display());
103 }
104 }
105 Err(Error::PCSError(StatusCode::Gone, _)) => {
106 if verbose {
107 println!(" tcb info: Gone (silently ignoring)");
108 }
109 }
110 Err(e) => {
111 return Err(e)?;
112 }
113 }
114
115 let qe_identity = prov_client.qe_identity(Some(number.number()));
116
117 match qe_identity {
118 Ok(qe_identity) => {
119 let file = qe_identity
120 .write_to_file(output_dir, WriteOptionsBuilder::new().build())?;
121 if verbose {
122 println!(" qe identity: {}\n", file.unwrap().display());
123 }
124 }
125 Err(Error::PCSError(StatusCode::Gone, _)) => {
126 if verbose {
127 println!(" qe identity: Gone (silently ignoring)\n");
128 }
129 }
130 Err(e) => {
131 return Err(e)?;
132 }
133 }
134 }
135 }
136 let pckcrl = prov_client
137 .pckcrl(DcapArtifactIssuer::PCKProcessorCA)
138 .and_then(|crl| {
139 crl.write_to_file_as(
140 output_dir,
141 DcapArtifactIssuer::PCKProcessorCA,
142 WriteOptionsBuilder::new().build(),
143 )
144 .map_err(|e| e.into())
145 })?;
146 if verbose {
147 println!("==[ generic ]==");
148 println!(" PCKProcessorCA Crl: {}", pckcrl.unwrap().display());
149 }
150
151 let pckcrl = prov_client
152 .pckcrl(DcapArtifactIssuer::PCKPlatformCA)
153 .and_then(|crl| {
154 crl.write_to_file_as(
155 output_dir,
156 DcapArtifactIssuer::PCKPlatformCA,
157 WriteOptionsBuilder::new().build(),
158 )
159 .map_err(|e| e.into())
160 })?;
161 if verbose {
162 println!(" PCKPlatformCA Crl: {}", pckcrl.unwrap().display());
163 }
164 Ok(())
165}
166
167pub fn main() {
168 fn is_directory(directory_path: String) -> Result<(), String> {
169 let path = Path::new(&directory_path);
170
171 match (path.exists(), path.is_dir()) {
172 (true, true) => return Ok(()),
173 (true, false) => {
174 return Err(format!(
175 "Path {} exists, but is not a directory",
176 directory_path
177 ))
178 }
179 (false, _) => return Err(format!("Directory {} does not exists", directory_path)),
180 };
181 }
182
183 fn is_file(filename: String) -> Result<(), String> {
184 if Path::new(&filename).exists() {
185 Ok(())
186 } else {
187 Err(format!("Cannot open {}", filename))
188 }
189 }
190
191 fn parse_pcs_version(value: &str) -> Result<PcsVersion, String> {
192 match value {
193 "3" => Err(format!("As of May 13, Intel has completed the End-of-Life of the deprecated API versions 3 of Intel PCS")),
194 "4" => Ok(PcsVersion::V4),
195 _ => Err(format!("Expected 4, found `{}`", value)),
196 }
197 }
198
199 fn is_url(value: String) -> Result<(), String> {
200 let url = Url::parse(&value)
201 .map_err(|e| format!("cannot parse `{}` as a valid URL: {}", value, e))?;
202
203 if url.scheme() != "http" && url.scheme() != "https" {
204 return Err(format!(
205 "Expected an http or https URL found: `{}`",
206 url.scheme()
207 ));
208 }
209 Ok(())
210 }
211
212 let matches = clap::clap_app!(("DCAP Artifact Retrieval Tool") =>
213 (author: "Fortanix")
214 (about: "Fortanix ecdsa artifact retrieval tool for DCAP attestation")
215 (
216 @arg ORIGIN: --("origin") +takes_value
217 validator(|s| parse_origin(s.as_str()).map(|_| ()))
218 "Origin for downloading artifacts. Options are: \"intel\", \"azure\" and \"pccs\". \
219 Note that Azure does not provide access to all artifacts. Intel will be contacted as a fallback. \
220 Default: \"intel\"."
221 )
222 (
223 @arg PCKID_FILE: --("pckid-file") +takes_value +required requires("PCKID_FILE")
224 validator(is_file)
225 "File describing the PCK identity (outputted by PCKIDRetrievalTool)."
226 )
227 (
228 @arg OUTPUT_DIR: --("output-dir") +takes_value +required requires("OUTPUT_DIR")
229 validator(is_directory)
230 "Destination folder for storing downloaded artifacts."
231 )
232 (
233 @arg API_VERSION: --("api-version") +takes_value
234 validator(|s| parse_pcs_version(s.as_str()).map(|_| ()))
235 "API version for provisioning service, supported value is 4. Default: \"4\"."
236 )
237 (
238 @arg API_KEY: --("api-key") +takes_value
239 "API key for authenticating with Intel provisioning service."
240 )
241 (
242 @arg PCCS_URL: --("pccs-url") +takes_value required_if("ORIGIN", "pccs")
243 validator(is_url)
244 "PCCS base URL. This is relevant only when using `--origin pccs`."
245 )
246 (
247 @arg INSECURE: -k --insecure
248 "Do not verify that server's hostname matches their TLS certificate and accept self-signed certificates. This is insecure."
249 )
250 (
251 @arg VERBOSE: -v --verbose
252 "Print additional information abut files that are fetched."
253 )
254 )
255 .get_matches();
256
257 let result = match (
258 matches.value_of("PCKID_FILE"),
259 matches.value_of("OUTPUT_DIR"),
260 ) {
261 (Some(pckid_file), Some(output_dir)) => {
262 let verboseness = matches.occurrences_of("VERBOSE");
263 let api_version = parse_pcs_version(
264 matches
265 .value_of("API_VERSION")
266 .unwrap_or(DEFAULT_API_VERSION),
267 )
268 .expect("validated");
269
270 let origin = parse_origin(matches.value_of("ORIGIN").unwrap_or(DEFAULT_ORIGIN))
271 .expect("validated");
272
273 let fetcher = match matches.is_present("INSECURE") {
274 false => crate::reqwest_client(),
275 true => crate::reqwest_client_insecure_tls(),
276 };
277
278 let client: Box<dyn ProvisioningClient> = match origin {
279 Origin::Intel => {
280 let mut client_builder = IntelProvisioningClientBuilder::new(api_version);
281 if let Some(api_key) = matches.value_of("API_KEY") {
282 client_builder.set_api_key(api_key.into());
283 }
284 Box::new(client_builder.build(fetcher))
285 }
286 Origin::Azure => {
287 let client_builder = AzureProvisioningClientBuilder::new(api_version);
288 Box::new(client_builder.build(fetcher))
289 }
290 Origin::Pccs => {
291 let pccs_url = matches.value_of("PCCS_URL").expect("validated").to_owned();
292 let client_builder = PccsProvisioningClientBuilder::new(api_version, pccs_url);
293 Box::new(client_builder.build(fetcher))
294 }
295 };
296 download_dcap_artifacts(&*client, pckid_file, output_dir, 0 < verboseness)
297 }
298 _ => unreachable!("validated"),
299 };
300
301 match result {
302 Ok(()) => {}
303 Err(Error::PCSError(StatusCode::NotFound, _)) => {
304 eprintln!("Error: Artifact not found. Perhaps specify a different origin?");
305 std::process::exit(1);
306 }
307 Err(err) => {
308 eprintln!("Error downloading artifact: {}", err);
309 std::process::exit(1);
310 }
311 }
312}