scepclient: Generate uppercase transaction ID.
[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 <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 hasher->get_hash(hasher, pkcs10, digest.ptr);
135 hasher->destroy(hasher);
136
137 return chunk_to_hex(digest, NULL, FALSE);
138 }
139
140 /**
141 * Generate a transaction id as the MD5 hash of an public key
142 * the transaction id is also used as a unique serial number
143 */
144 void scep_generate_transaction_id(public_key_t *key, chunk_t *transID,
145 chunk_t *serialNumber)
146 {
147 chunk_t digest = chunk_alloca(HASH_SIZE_MD5);
148 chunk_t keyEncoding = chunk_empty, keyInfo;
149 hasher_t *hasher;
150 bool msb_set;
151 u_char *pos;
152
153 key->get_encoding(key, PUBKEY_ASN1_DER, &keyEncoding);
154
155 keyInfo = asn1_wrap(ASN1_SEQUENCE, "mm",
156 asn1_algorithmIdentifier(OID_RSA_ENCRYPTION),
157 asn1_bitstring("m", keyEncoding));
158
159 hasher = lib->crypto->create_hasher(lib->crypto, HASH_MD5);
160 hasher->get_hash(hasher, keyInfo, digest.ptr);
161 hasher->destroy(hasher);
162 free(keyInfo.ptr);
163
164 /* is the most significant bit of the digest set? */
165 msb_set = (*digest.ptr & 0x80) == 0x80;
166
167 /* allocate space for the serialNumber */
168 serialNumber->len = msb_set + digest.len;
169 serialNumber->ptr = malloc(serialNumber->len);
170
171 /* the serial number as the two's complement of the digest */
172 pos = serialNumber->ptr;
173 if (msb_set)
174 {
175 *pos++ = 0x00;
176 }
177 memcpy(pos, digest.ptr, digest.len);
178
179 /* the transaction id is the serial number in hex format */
180 *transID = chunk_to_hex(digest, NULL, TRUE);
181 }
182
183 /**
184 * Adds a senderNonce attribute to the given pkcs9 attribute list
185 */
186 static void add_senderNonce_attribute(pkcs9_t *pkcs9)
187 {
188 const size_t nonce_len = 16;
189 u_char nonce_buf[nonce_len];
190 chunk_t senderNonce = { nonce_buf, nonce_len };
191 rng_t *rng;
192
193 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
194 rng->get_bytes(rng, nonce_len, nonce_buf);
195 rng->destroy(rng);
196
197 pkcs9->set_attribute(pkcs9, OID_PKI_SENDER_NONCE, senderNonce);
198 }
199
200 /**
201 * Builds a pkcs7 enveloped and signed scep request
202 */
203 chunk_t scep_build_request(chunk_t data, chunk_t transID, scep_msg_t msg,
204 certificate_t *enc_cert, encryption_algorithm_t enc_alg,
205 size_t key_size, certificate_t *signer_cert,
206 hash_algorithm_t digest_alg, private_key_t *private_key)
207 {
208 chunk_t request, msgType = {
209 (u_char*)msgType_values[msg],
210 strlen(msgType_values[msg]),
211 };
212 pkcs7_t *pkcs7;
213 pkcs9_t *pkcs9;
214
215 pkcs7 = pkcs7_create_from_data(data);
216 if (!pkcs7->build_envelopedData(pkcs7, enc_cert, enc_alg, key_size))
217 {
218 pkcs7->destroy(pkcs7);
219 return chunk_empty;
220 }
221
222 pkcs9 = pkcs9_create();
223 pkcs9->set_attribute(pkcs9, OID_PKI_TRANS_ID, transID);
224 pkcs9->set_attribute(pkcs9, OID_PKI_MESSAGE_TYPE, msgType);
225 add_senderNonce_attribute(pkcs9);
226
227 pkcs7->set_attributes(pkcs7, pkcs9);
228 pkcs7->set_certificate(pkcs7, signer_cert->get_ref(signer_cert));
229 if (!pkcs7->build_signedData(pkcs7, private_key, digest_alg))
230 {
231 pkcs7->destroy(pkcs7);
232 return chunk_empty;
233 }
234 request = pkcs7->get_contentInfo(pkcs7);
235 pkcs7->destroy(pkcs7);
236 return request;
237 }
238
239 /**
240 * Converts a binary request to base64 with 64 characters per line
241 * newline and '+' characters are escaped by %0A and %2B, respectively
242 */
243 static char* escape_http_request(chunk_t req)
244 {
245 char *escaped_req = NULL;
246 char *p1, *p2;
247 int lines = 0;
248 int plus = 0;
249 int n = 0;
250
251 /* compute and allocate the size of the base64-encoded request */
252 int len = 1 + 4 * ((req.len + 2) / 3);
253 char *encoded_req = malloc(len);
254
255 /* do the base64 conversion */
256 chunk_t base64 = chunk_to_base64(req, encoded_req);
257 len = base64.len + 1;
258
259 /* compute newline characters to be inserted every 64 characters */
260 lines = (len - 2) / 64;
261
262 /* count number of + characters to be escaped */
263 p1 = encoded_req;
264 while (*p1 != '\0')
265 {
266 if (*p1++ == '+')
267 {
268 plus++;
269 }
270 }
271
272 escaped_req = malloc(len + 3 * (lines + plus));
273
274 /* escape special characters in the request */
275 p1 = encoded_req;
276 p2 = escaped_req;
277 while (*p1 != '\0')
278 {
279 if (n == 64)
280 {
281 memcpy(p2, "%0A", 3);
282 p2 += 3;
283 n = 0;
284 }
285 if (*p1 == '+')
286 {
287 memcpy(p2, "%2B", 3);
288 p2 += 3;
289 }
290 else
291 {
292 *p2++ = *p1;
293 }
294 p1++;
295 n++;
296 }
297 *p2 = '\0';
298 free(encoded_req);
299 return escaped_req;
300 }
301
302 /**
303 * Send a SCEP request via HTTP and wait for a response
304 */
305 bool scep_http_request(const char *url, chunk_t pkcs7, scep_op_t op,
306 bool http_get_request, chunk_t *response)
307 {
308 int len;
309 status_t status;
310 char *complete_url = NULL;
311
312 /* initialize response */
313 *response = chunk_empty;
314
315 DBG2(DBG_APP, "sending scep request to '%s'", url);
316
317 if (op == SCEP_PKI_OPERATION)
318 {
319 const char operation[] = "PKIOperation";
320
321 if (http_get_request)
322 {
323 char *escaped_req = escape_http_request(pkcs7);
324
325 /* form complete url */
326 len = strlen(url) + 20 + strlen(operation) + strlen(escaped_req) + 1;
327 complete_url = malloc(len);
328 snprintf(complete_url, len, "%s?operation=%s&message=%s"
329 , url, operation, escaped_req);
330 free(escaped_req);
331
332 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
333 FETCH_HTTP_VERSION_1_0,
334 FETCH_REQUEST_HEADER, "Pragma:",
335 FETCH_REQUEST_HEADER, "Host:",
336 FETCH_REQUEST_HEADER, "Accept:",
337 FETCH_END);
338 }
339 else /* HTTP_POST */
340 {
341 /* form complete url */
342 len = strlen(url) + 11 + strlen(operation) + 1;
343 complete_url = malloc(len);
344 snprintf(complete_url, len, "%s?operation=%s", url, operation);
345
346 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
347 FETCH_HTTP_VERSION_1_0,
348 FETCH_REQUEST_DATA, pkcs7,
349 FETCH_REQUEST_TYPE, "",
350 FETCH_REQUEST_HEADER, "Expect:",
351 FETCH_END);
352 }
353 }
354 else /* SCEP_GET_CA_CERT */
355 {
356 const char operation[] = "GetCACert";
357
358 /* form complete url */
359 len = strlen(url) + 32 + strlen(operation) + 1;
360 complete_url = malloc(len);
361 snprintf(complete_url, len, "%s?operation=%s&message=CAIdentifier",
362 url, operation);
363
364 status = lib->fetcher->fetch(lib->fetcher, complete_url, response,
365 FETCH_HTTP_VERSION_1_0,
366 FETCH_END);
367 }
368
369 free(complete_url);
370 return (status == SUCCESS);
371 }
372
373 err_t scep_parse_response(chunk_t response, chunk_t transID, pkcs7_t **data,
374 scep_attributes_t *attrs, certificate_t *signer_cert)
375 {
376 pkcs7_t *pkcs7;
377
378 pkcs7 = pkcs7_create_from_chunk(response, 0);
379 if (!pkcs7 || !pkcs7->parse_signedData(pkcs7, signer_cert))
380 {
381 DESTROY_IF(pkcs7);
382 return "error parsing the scep response";
383 }
384 extract_attributes(pkcs7, attrs);
385 if (!chunk_equals(transID, attrs->transID))
386 {
387 pkcs7->destroy(pkcs7);
388 return "transaction ID of scep response does not match";
389 }
390 *data = pkcs7;
391 return NULL;
392 }