Move PKCS#9 attribute lists to pkcs7 plugin, as we currently use it there only
[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/rngs/rng.h>
26 #include <crypto/hashers/hasher.h>
27
28 #include "scep.h"
29
30 static const char *pkiStatus_values[] = { "0", "2", "3" };
31
32 static const char *pkiStatus_names[] = {
33 "SUCCESS",
34 "FAILURE",
35 "PENDING",
36 "UNKNOWN"
37 };
38
39 static const char *msgType_values[] = { "3", "19", "20", "21", "22" };
40
41 static const char *msgType_names[] = {
42 "CertRep",
43 "PKCSReq",
44 "GetCertInitial",
45 "GetCert",
46 "GetCRL",
47 "Unknown"
48 };
49
50 static const char *failInfo_reasons[] = {
51 "badAlg - unrecognized or unsupported algorithm identifier",
52 "badMessageCheck - integrity check failed",
53 "badRequest - transaction not permitted or supported",
54 "badTime - Message time field was not sufficiently close to the system time",
55 "badCertId - No certificate could be identified matching the provided criteria"
56 };
57
58 const scep_attributes_t empty_scep_attributes = {
59 SCEP_Unknown_MSG , /* msgType */
60 SCEP_UNKNOWN , /* pkiStatus */
61 SCEP_unknown_REASON, /* failInfo */
62 { NULL, 0 } , /* transID */
63 { NULL, 0 } , /* senderNonce */
64 { NULL, 0 } , /* recipientNonce */
65 };
66
67 /**
68 * Extract X.501 attributes
69 */
70 void extract_attributes(pkcs7_t *pkcs7, enumerator_t *enumerator,
71 scep_attributes_t *attrs)
72 {
73 chunk_t attr;
74
75 if (pkcs7->get_attribute(pkcs7, OID_PKI_MESSAGE_TYPE, enumerator, &attr))
76 {
77 scep_msg_t m;
78
79 for (m = SCEP_CertRep_MSG; m < SCEP_Unknown_MSG; m++)
80 {
81 if (strncmp(msgType_values[m], attr.ptr, attr.len) == 0)
82 {
83 attrs->msgType = m;
84 }
85 }
86 DBG2(DBG_APP, "messageType: %s", msgType_names[attrs->msgType]);
87 free(attr.ptr);
88 }
89 if (pkcs7->get_attribute(pkcs7, OID_PKI_STATUS, enumerator, &attr))
90 {
91 pkiStatus_t s;
92
93 for (s = SCEP_SUCCESS; s < SCEP_UNKNOWN; s++)
94 {
95 if (strncmp(pkiStatus_values[s], attr.ptr, attr.len) == 0)
96 {
97 attrs->pkiStatus = s;
98 }
99 }
100 DBG2(DBG_APP, "pkiStatus: %s", pkiStatus_names[attrs->pkiStatus]);
101 free(attr.ptr);
102 }
103 if (pkcs7->get_attribute(pkcs7, OID_PKI_FAIL_INFO, enumerator, &attr))
104 {
105 if (attr.len == 1 && *attr.ptr >= '0' && *attr.ptr <= '4')
106 {
107 attrs->failInfo = (failInfo_t)(*attr.ptr - '0');
108 }
109 if (attrs->failInfo != SCEP_unknown_REASON)
110 {
111 DBG1(DBG_APP, "failInfo: %s", failInfo_reasons[attrs->failInfo]);
112 }
113 free(attr.ptr);
114 }
115
116 pkcs7->get_attribute(pkcs7, OID_PKI_SENDER_NONCE, enumerator,
117 &attrs->senderNonce);
118 pkcs7->get_attribute(pkcs7, OID_PKI_RECIPIENT_NONCE, enumerator,
119 &attrs->recipientNonce);
120 pkcs7->get_attribute(pkcs7, OID_PKI_TRANS_ID, enumerator,
121 &attrs->transID);
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 * Builds a pkcs7 enveloped and signed scep request
192 */
193 chunk_t scep_build_request(chunk_t data, chunk_t transID, scep_msg_t msg,
194 certificate_t *enc_cert, encryption_algorithm_t enc_alg,
195 size_t key_size, certificate_t *signer_cert,
196 hash_algorithm_t digest_alg, private_key_t *private_key)
197 {
198 chunk_t request;
199 container_t *container;
200 char nonce[16];
201 rng_t *rng;
202 chunk_t senderNonce, msgType;
203
204 /* generate senderNonce */
205 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
206 if (!rng || !rng->get_bytes(rng, sizeof(nonce), nonce))
207 {
208 DESTROY_IF(rng);
209 return chunk_empty;
210 }
211 rng->destroy(rng);
212
213 /* encrypt data in enveloped-data PKCS#7 */
214 container = lib->creds->create(lib->creds,
215 CRED_CONTAINER, CONTAINER_PKCS7_ENVELOPED_DATA,
216 BUILD_BLOB, data,
217 BUILD_CERT, enc_cert,
218 BUILD_ENCRYPTION_ALG, enc_alg,
219 BUILD_KEY_SIZE, (int)key_size,
220 BUILD_END);
221 if (!container)
222 {
223 return chunk_empty;
224 }
225 if (!container->get_encoding(container, &request))
226 {
227 container->destroy(container);
228 return chunk_empty;
229 }
230 container->destroy(container);
231
232 /* sign enveloped-data in a signed-data PKCS#7 */
233 senderNonce = asn1_wrap(ASN1_OCTET_STRING, "c", chunk_from_thing(nonce));
234 transID = asn1_wrap(ASN1_PRINTABLESTRING, "c", transID);
235 msgType = asn1_wrap(ASN1_PRINTABLESTRING, "c",
236 chunk_create((char*)msgType_values[msg],
237 strlen(msgType_values[msg])));
238
239 container = lib->creds->create(lib->creds,
240 CRED_CONTAINER, CONTAINER_PKCS7_SIGNED_DATA,
241 BUILD_BLOB, request,
242 BUILD_SIGNING_CERT, signer_cert,
243 BUILD_SIGNING_KEY, private_key,
244 BUILD_DIGEST_ALG, digest_alg,
245 BUILD_PKCS7_ATTRIBUTE, OID_PKI_SENDER_NONCE, senderNonce,
246 BUILD_PKCS7_ATTRIBUTE, OID_PKI_TRANS_ID, transID,
247 BUILD_PKCS7_ATTRIBUTE, OID_PKI_MESSAGE_TYPE, msgType,
248 BUILD_END);
249
250 free(request.ptr);
251 free(senderNonce.ptr);
252 free(transID.ptr);
253 free(msgType.ptr);
254
255 if (!container)
256 {
257 return chunk_empty;
258 }
259 if (!container->get_encoding(container, &request))
260 {
261 container->destroy(container);
262 return chunk_empty;
263 }
264 container->destroy(container);
265
266 return request;
267 }
268
269 /**
270 * Converts a binary request to base64 with 64 characters per line
271 * newline and '+' characters are escaped by %0A and %2B, respectively
272 */
273 static char* escape_http_request(chunk_t req)
274 {
275 char *escaped_req = NULL;
276 char *p1, *p2;
277 int lines = 0;
278 int plus = 0;
279 int n = 0;
280
281 /* compute and allocate the size of the base64-encoded request */
282 int len = 1 + 4 * ((req.len + 2) / 3);
283 char *encoded_req = malloc(len);
284
285 /* do the base64 conversion */
286 chunk_t base64 = chunk_to_base64(req, encoded_req);
287 len = base64.len + 1;
288
289 /* compute newline characters to be inserted every 64 characters */
290 lines = (len - 2) / 64;
291
292 /* count number of + characters to be escaped */
293 p1 = encoded_req;
294 while (*p1 != '\0')
295 {
296 if (*p1++ == '+')
297 {
298 plus++;
299 }
300 }
301
302 escaped_req = malloc(len + 3 * (lines + plus));
303
304 /* escape special characters in the request */
305 p1 = encoded_req;
306 p2 = escaped_req;
307 while (*p1 != '\0')
308 {
309 if (n == 64)
310 {
311 memcpy(p2, "%0A", 3);
312 p2 += 3;
313 n = 0;
314 }
315 if (*p1 == '+')
316 {
317 memcpy(p2, "%2B", 3);
318 p2 += 3;
319 }
320 else
321 {
322 *p2++ = *p1;
323 }
324 p1++;
325 n++;
326 }
327 *p2 = '\0';
328 free(encoded_req);
329 return escaped_req;
330 }
331
332 /**
333 * Send a SCEP request via HTTP and wait for a response
334 */
335 bool scep_http_request(const char *url, chunk_t msg, scep_op_t op,
336 bool http_get_request, chunk_t *response)
337 {
338 int len;
339 status_t status;
340 char *complete_url = NULL;
341
342 /* initialize response */
343 *response = chunk_empty;
344
345 DBG2(DBG_APP, "sending scep request to '%s'", url);
346
347 if (op == SCEP_PKI_OPERATION)
348 {
349 const char operation[] = "PKIOperation";
350
351 if (http_get_request)
352 {
353 char *escaped_req = escape_http_request(msg);
354
355 /* form complete url */
356 len = strlen(url) + 20 + strlen(operation) + strlen(escaped_req) + 1;
357 complete_url = malloc(len);
358 snprintf(complete_url, len, "%s?operation=%s&message=%s"
359 , url, operation, escaped_req);
360 free(escaped_req);
361
362 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
363 FETCH_HTTP_VERSION_1_0,
364 FETCH_REQUEST_HEADER, "Pragma:",
365 FETCH_REQUEST_HEADER, "Host:",
366 FETCH_REQUEST_HEADER, "Accept:",
367 FETCH_END);
368 }
369 else /* HTTP_POST */
370 {
371 /* form complete url */
372 len = strlen(url) + 11 + strlen(operation) + 1;
373 complete_url = malloc(len);
374 snprintf(complete_url, len, "%s?operation=%s", url, operation);
375
376 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
377 FETCH_HTTP_VERSION_1_0,
378 FETCH_REQUEST_DATA, msg,
379 FETCH_REQUEST_TYPE, "",
380 FETCH_REQUEST_HEADER, "Expect:",
381 FETCH_END);
382 }
383 }
384 else /* SCEP_GET_CA_CERT */
385 {
386 const char operation[] = "GetCACert";
387 int i;
388
389 /* escape spaces, TODO: complete URL escape */
390 for (i = 0; i < msg.len; i++)
391 {
392 if (msg.ptr[i] == ' ')
393 {
394 msg.ptr[i] = '+';
395 }
396 }
397
398 /* form complete url */
399 len = strlen(url) + 32 + strlen(operation) + msg.len + 1;
400 complete_url = malloc(len);
401 snprintf(complete_url, len, "%s?operation=%s&message=%.*s",
402 url, operation, (int)msg.len, msg.ptr);
403
404 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
405 FETCH_HTTP_VERSION_1_0,
406 FETCH_END);
407 }
408
409 free(complete_url);
410 return (status == SUCCESS);
411 }
412
413 err_t scep_parse_response(chunk_t response, chunk_t transID,
414 container_t **out, scep_attributes_t *attrs)
415 {
416 enumerator_t *enumerator;
417 bool verified = FALSE;
418 container_t *container;
419 auth_cfg_t *auth;
420
421 container = lib->creds->create(lib->creds, CRED_CONTAINER, CONTAINER_PKCS7,
422 BUILD_BLOB_ASN1_DER, response, BUILD_END);
423 if (!container)
424 {
425 return "error parsing the scep response";
426 }
427 if (container->get_type(container) != CONTAINER_PKCS7_SIGNED_DATA)
428 {
429 container->destroy(container);
430 return "scep response is not PKCS#7 signed-data";
431 }
432
433 enumerator = container->create_signature_enumerator(container);
434 while (enumerator->enumerate(enumerator, &auth))
435 {
436 verified = TRUE;
437 extract_attributes((pkcs7_t*)container, enumerator, attrs);
438 if (!chunk_equals(transID, attrs->transID))
439 {
440 enumerator->destroy(enumerator);
441 container->destroy(container);
442 return "transaction ID of scep response does not match";
443 }
444 }
445 enumerator->destroy(enumerator);
446 if (!verified)
447 {
448 container->destroy(container);
449 return "unable to verify PKCS#7 container";
450 }
451 *out = container;
452 return NULL;
453 }