Add a scepclient option to specify a CA identifier to fetch certs for
[strongswan.git] / src / scepclient / scep.c
1 /*
2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2005 Jan Hutter, Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <string.h>
18 #include <stdlib.h>
19
20 #include <library.h>
21 #include <utils/debug.h>
22 #include <asn1/asn1.h>
23 #include <asn1/asn1_parser.h>
24 #include <asn1/oid.h>
25 #include <crypto/pkcs9.h>
26 #include <crypto/rngs/rng.h>
27 #include <crypto/hashers/hasher.h>
28
29 #include "scep.h"
30
31 static const char *pkiStatus_values[] = { "0", "2", "3" };
32
33 static const char *pkiStatus_names[] = {
34 "SUCCESS",
35 "FAILURE",
36 "PENDING",
37 "UNKNOWN"
38 };
39
40 static const char *msgType_values[] = { "3", "19", "20", "21", "22" };
41
42 static const char *msgType_names[] = {
43 "CertRep",
44 "PKCSReq",
45 "GetCertInitial",
46 "GetCert",
47 "GetCRL",
48 "Unknown"
49 };
50
51 static const char *failInfo_reasons[] = {
52 "badAlg - unrecognized or unsupported algorithm identifier",
53 "badMessageCheck - integrity check failed",
54 "badRequest - transaction not permitted or supported",
55 "badTime - Message time field was not sufficiently close to the system time",
56 "badCertId - No certificate could be identified matching the provided criteria"
57 };
58
59 const scep_attributes_t empty_scep_attributes = {
60 SCEP_Unknown_MSG , /* msgType */
61 SCEP_UNKNOWN , /* pkiStatus */
62 SCEP_unknown_REASON, /* failInfo */
63 { NULL, 0 } , /* transID */
64 { NULL, 0 } , /* senderNonce */
65 { NULL, 0 } , /* recipientNonce */
66 };
67
68 /**
69 * Extract X.501 attributes
70 */
71 void extract_attributes(pkcs7_t *pkcs7, scep_attributes_t *attrs)
72 {
73 pkcs9_t *attributes = pkcs7->get_attributes(pkcs7);
74 chunk_t attr;
75
76 attr = attributes->get_attribute(attributes, OID_PKI_MESSAGE_TYPE);
77 if (attr.ptr)
78 {
79 scep_msg_t m;
80
81 for (m = SCEP_CertRep_MSG; m < SCEP_Unknown_MSG; m++)
82 {
83 if (strncmp(msgType_values[m], attr.ptr, attr.len) == 0)
84 {
85 attrs->msgType = m;
86 }
87 }
88 DBG2(DBG_APP, "messageType: %s", msgType_names[attrs->msgType]);
89 }
90 attr = attributes->get_attribute(attributes, OID_PKI_STATUS);
91 if (attr.ptr)
92 {
93 pkiStatus_t s;
94
95 for (s = SCEP_SUCCESS; s < SCEP_UNKNOWN; s++)
96 {
97 if (strncmp(pkiStatus_values[s], attr.ptr, attr.len) == 0)
98 {
99 attrs->pkiStatus = s;
100 }
101 }
102 DBG2(DBG_APP, "pkiStatus: %s", pkiStatus_names[attrs->pkiStatus]);
103 }
104 attr = attributes->get_attribute(attributes, OID_PKI_FAIL_INFO);
105 if (attr.ptr)
106 {
107 if (attr.len == 1 && *attr.ptr >= '0' && *attr.ptr <= '4')
108 {
109 attrs->failInfo = (failInfo_t)(*attr.ptr - '0');
110 }
111 if (attrs->failInfo != SCEP_unknown_REASON)
112 {
113 DBG1(DBG_APP, "failInfo: %s", failInfo_reasons[attrs->failInfo]);
114 }
115 }
116 attrs->senderNonce = attributes->get_attribute(attributes,
117 OID_PKI_SENDER_NONCE);
118 attrs->recipientNonce = attributes->get_attribute(attributes,
119 OID_PKI_RECIPIENT_NONCE);
120 attrs->transID = attributes->get_attribute(attributes,
121 OID_PKI_TRANS_ID);
122 }
123
124 /**
125 * Generates a unique fingerprint of the pkcs10 request
126 * by computing an MD5 hash over it
127 */
128 chunk_t scep_generate_pkcs10_fingerprint(chunk_t pkcs10)
129 {
130 chunk_t digest = chunk_alloca(HASH_SIZE_MD5);
131 hasher_t *hasher;
132
133 hasher = lib->crypto->create_hasher(lib->crypto, HASH_MD5);
134 if (!hasher || !hasher->get_hash(hasher, pkcs10, digest.ptr))
135 {
136 DESTROY_IF(hasher);
137 return chunk_empty;
138 }
139 hasher->destroy(hasher);
140
141 return chunk_to_hex(digest, NULL, FALSE);
142 }
143
144 /**
145 * Generate a transaction id as the MD5 hash of an public key
146 * the transaction id is also used as a unique serial number
147 */
148 void scep_generate_transaction_id(public_key_t *key, chunk_t *transID,
149 chunk_t *serialNumber)
150 {
151 chunk_t digest = chunk_alloca(HASH_SIZE_MD5);
152 chunk_t keyEncoding = chunk_empty, keyInfo;
153 hasher_t *hasher;
154 bool msb_set;
155 u_char *pos;
156
157 key->get_encoding(key, PUBKEY_ASN1_DER, &keyEncoding);
158
159 keyInfo = asn1_wrap(ASN1_SEQUENCE, "mm",
160 asn1_algorithmIdentifier(OID_RSA_ENCRYPTION),
161 asn1_bitstring("m", keyEncoding));
162
163 hasher = lib->crypto->create_hasher(lib->crypto, HASH_MD5);
164 if (!hasher || !hasher->get_hash(hasher, keyInfo, digest.ptr))
165 {
166 memset(digest.ptr, 0, digest.len);
167 }
168 DESTROY_IF(hasher);
169 free(keyInfo.ptr);
170
171 /* is the most significant bit of the digest set? */
172 msb_set = (*digest.ptr & 0x80) == 0x80;
173
174 /* allocate space for the serialNumber */
175 serialNumber->len = msb_set + digest.len;
176 serialNumber->ptr = malloc(serialNumber->len);
177
178 /* the serial number as the two's complement of the digest */
179 pos = serialNumber->ptr;
180 if (msb_set)
181 {
182 *pos++ = 0x00;
183 }
184 memcpy(pos, digest.ptr, digest.len);
185
186 /* the transaction id is the serial number in hex format */
187 *transID = chunk_to_hex(digest, NULL, TRUE);
188 }
189
190 /**
191 * Adds a senderNonce attribute to the given pkcs9 attribute list
192 */
193 static bool add_senderNonce_attribute(pkcs9_t *pkcs9)
194 {
195 const size_t nonce_len = 16;
196 u_char nonce_buf[nonce_len];
197 chunk_t senderNonce = { nonce_buf, nonce_len };
198 rng_t *rng;
199
200 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
201 if (!rng || !rng->get_bytes(rng, nonce_len, nonce_buf))
202 {
203 DESTROY_IF(rng);
204 return FALSE;
205 }
206 rng->destroy(rng);
207
208 pkcs9->set_attribute(pkcs9, OID_PKI_SENDER_NONCE, senderNonce);
209 return TRUE;
210 }
211
212 /**
213 * Builds a pkcs7 enveloped and signed scep request
214 */
215 chunk_t scep_build_request(chunk_t data, chunk_t transID, scep_msg_t msg,
216 certificate_t *enc_cert, encryption_algorithm_t enc_alg,
217 size_t key_size, certificate_t *signer_cert,
218 hash_algorithm_t digest_alg, private_key_t *private_key)
219 {
220 chunk_t request, msgType = {
221 (u_char*)msgType_values[msg],
222 strlen(msgType_values[msg]),
223 };
224 pkcs7_t *pkcs7;
225 pkcs9_t *pkcs9;
226
227 pkcs7 = pkcs7_create_from_data(data);
228 if (!pkcs7->build_envelopedData(pkcs7, enc_cert, enc_alg, key_size))
229 {
230 pkcs7->destroy(pkcs7);
231 return chunk_empty;
232 }
233
234 pkcs9 = pkcs9_create();
235 pkcs9->set_attribute(pkcs9, OID_PKI_TRANS_ID, transID);
236 pkcs9->set_attribute(pkcs9, OID_PKI_MESSAGE_TYPE, msgType);
237 if (!add_senderNonce_attribute(pkcs9))
238 {
239 pkcs9->destroy(pkcs9);
240 pkcs7->destroy(pkcs7);
241 return chunk_empty;
242 }
243
244 pkcs7->set_attributes(pkcs7, pkcs9);
245 pkcs7->set_certificate(pkcs7, signer_cert->get_ref(signer_cert));
246 if (!pkcs7->build_signedData(pkcs7, private_key, digest_alg))
247 {
248 pkcs7->destroy(pkcs7);
249 return chunk_empty;
250 }
251 request = pkcs7->get_contentInfo(pkcs7);
252 pkcs7->destroy(pkcs7);
253 return request;
254 }
255
256 /**
257 * Converts a binary request to base64 with 64 characters per line
258 * newline and '+' characters are escaped by %0A and %2B, respectively
259 */
260 static char* escape_http_request(chunk_t req)
261 {
262 char *escaped_req = NULL;
263 char *p1, *p2;
264 int lines = 0;
265 int plus = 0;
266 int n = 0;
267
268 /* compute and allocate the size of the base64-encoded request */
269 int len = 1 + 4 * ((req.len + 2) / 3);
270 char *encoded_req = malloc(len);
271
272 /* do the base64 conversion */
273 chunk_t base64 = chunk_to_base64(req, encoded_req);
274 len = base64.len + 1;
275
276 /* compute newline characters to be inserted every 64 characters */
277 lines = (len - 2) / 64;
278
279 /* count number of + characters to be escaped */
280 p1 = encoded_req;
281 while (*p1 != '\0')
282 {
283 if (*p1++ == '+')
284 {
285 plus++;
286 }
287 }
288
289 escaped_req = malloc(len + 3 * (lines + plus));
290
291 /* escape special characters in the request */
292 p1 = encoded_req;
293 p2 = escaped_req;
294 while (*p1 != '\0')
295 {
296 if (n == 64)
297 {
298 memcpy(p2, "%0A", 3);
299 p2 += 3;
300 n = 0;
301 }
302 if (*p1 == '+')
303 {
304 memcpy(p2, "%2B", 3);
305 p2 += 3;
306 }
307 else
308 {
309 *p2++ = *p1;
310 }
311 p1++;
312 n++;
313 }
314 *p2 = '\0';
315 free(encoded_req);
316 return escaped_req;
317 }
318
319 /**
320 * Send a SCEP request via HTTP and wait for a response
321 */
322 bool scep_http_request(const char *url, chunk_t msg, scep_op_t op,
323 bool http_get_request, chunk_t *response)
324 {
325 int len;
326 status_t status;
327 char *complete_url = NULL;
328
329 /* initialize response */
330 *response = chunk_empty;
331
332 DBG2(DBG_APP, "sending scep request to '%s'", url);
333
334 if (op == SCEP_PKI_OPERATION)
335 {
336 const char operation[] = "PKIOperation";
337
338 if (http_get_request)
339 {
340 char *escaped_req = escape_http_request(msg);
341
342 /* form complete url */
343 len = strlen(url) + 20 + strlen(operation) + strlen(escaped_req) + 1;
344 complete_url = malloc(len);
345 snprintf(complete_url, len, "%s?operation=%s&message=%s"
346 , url, operation, escaped_req);
347 free(escaped_req);
348
349 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
350 FETCH_HTTP_VERSION_1_0,
351 FETCH_REQUEST_HEADER, "Pragma:",
352 FETCH_REQUEST_HEADER, "Host:",
353 FETCH_REQUEST_HEADER, "Accept:",
354 FETCH_END);
355 }
356 else /* HTTP_POST */
357 {
358 /* form complete url */
359 len = strlen(url) + 11 + strlen(operation) + 1;
360 complete_url = malloc(len);
361 snprintf(complete_url, len, "%s?operation=%s", url, operation);
362
363 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
364 FETCH_HTTP_VERSION_1_0,
365 FETCH_REQUEST_DATA, msg,
366 FETCH_REQUEST_TYPE, "",
367 FETCH_REQUEST_HEADER, "Expect:",
368 FETCH_END);
369 }
370 }
371 else /* SCEP_GET_CA_CERT */
372 {
373 const char operation[] = "GetCACert";
374 int i;
375
376 /* escape spaces, TODO: complete URL escape */
377 for (i = 0; i < msg.len; i++)
378 {
379 if (msg.ptr[i] == ' ')
380 {
381 msg.ptr[i] = '+';
382 }
383 }
384
385 /* form complete url */
386 len = strlen(url) + 32 + strlen(operation) + msg.len + 1;
387 complete_url = malloc(len);
388 snprintf(complete_url, len, "%s?operation=%s&message=%.*s",
389 url, operation, (int)msg.len, msg.ptr);
390
391 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
392 FETCH_HTTP_VERSION_1_0,
393 FETCH_END);
394 }
395
396 free(complete_url);
397 return (status == SUCCESS);
398 }
399
400 err_t scep_parse_response(chunk_t response, chunk_t transID, pkcs7_t **data,
401 scep_attributes_t *attrs, certificate_t *signer_cert)
402 {
403 pkcs7_t *pkcs7;
404
405 pkcs7 = pkcs7_create_from_chunk(response, 0);
406 if (!pkcs7 || !pkcs7->parse_signedData(pkcs7, signer_cert))
407 {
408 DESTROY_IF(pkcs7);
409 return "error parsing the scep response";
410 }
411 extract_attributes(pkcs7, attrs);
412 if (!chunk_equals(transID, attrs->transID))
413 {
414 pkcs7->destroy(pkcs7);
415 return "transaction ID of scep response does not match";
416 }
417 *data = pkcs7;
418 return NULL;
419 }