summaryrefslogtreecommitdiffstats
path: root/lasso/xml/tools.c
blob: de2b609e852edeb7b03fbd20fcfb65884ac2cbbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/* $Id$ 
 *
 * Lasso - A free implementation of the Liberty Alliance specifications.
 *
 * Copyright (C) 2004 Entr'ouvert
 * http://lasso.entrouvert.org
 * 
 * Authors: Nicolas Clapies <nclapies@entrouvert.com>
 *          Valery Febvre <vfebvre@easter-eggs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <string.h>
#include <time.h>

#include <libxml/uri.h>

#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/engine.h>

#include <xmlsec/base64.h>
#include <xmlsec/xmltree.h>

#include <lasso/xml/tools.h>

#include <lasso/xml/errors.h>
#include <lasso/xml/strings.h>


/**
 * lasso_build_random_sequence:
 * @buffer: buffer to fill with random sequence
 * @size: the sequence size in byte (character)
 * 
 * Builds a random sequence of [0-9A-F] characters of size @size.
 * 
 * Return value: None
 **/
void
lasso_build_random_sequence(char *buffer, unsigned int size)
{
	char *t;
	unsigned int rnd, i;

	t = buffer;
	while (t-buffer < (int)size) {
		rnd = g_random_int();
		for (i=0; i<sizeof(int); i++) {
			*(t++) = '0' + ((rnd>>i*4)&0xf);
			if (*(t-1) > '9') *(t-1) += 7;
		}
	}
}

/**
 * lasso_build_unique_id:
 * @size: the ID's length (between 32 and 40)
 * 
 * Builds an ID which has an unicity probability of 2^(-size*4).
 * 
 * Return value: a "unique" ID (begin always with _ character)
 **/
char*
lasso_build_unique_id(unsigned int size)
{
	/*
	 * When generating one-time-use identifiers for Principals, in the
	 * case that a pseudorandom technique is employed, the probability
	 * of two randomly chosen identifiers being identical MUST be less
	 * than or equal to 2-128 and SHOULD be less than or equal to 2-160.
	 * These levels correspond, respectively, to use of strong 128-bit
	 * and 160-bit hash functions, in conjunction with sufficient input
	 * entropy.
	 *   -- 3.1.4 Name Identifier Construction
	 *      in « Liberty ID-FF Protocols and Schema Specification »
	 */
	char *result;

	g_assert(size >= 32);

	result = malloc(size+2); /* trailing \0 and leading _ */
	result[0] = '_';
	lasso_build_random_sequence(result+1, size);
	result[size+1] = 0;
	return result;
}

/**
 * lasso_get_current_time:
 * 
 * Returns the current time, format is "yyyy-mm-ddThh:mm:ssZ".
 * 
 * Return value: a string
 **/
char*
lasso_get_current_time()
{
	time_t now;
	struct tm *tm;
	char *ret;

	ret = malloc(21);
	now = time(NULL);
	tm = gmtime(&now);
	strftime(ret, 21, "%Y-%m-%dT%H:%M:%SZ", tm);

	return ret;
}

/**
 * lasso_get_pem_file_type:
 * @pem_file: a pem file
 * 
 * Gets the type of a pem file.
 * 
 * Return value: the pem file type
 **/
lassoPemFileType
lasso_get_pem_file_type(const char *pem_file)
{
	BIO* bio;
	EVP_PKEY *pkey;
	X509 *cert;
	lassoPemFileType type = LASSO_PEM_FILE_TYPE_UNKNOWN;

	g_return_val_if_fail(pem_file != NULL, LASSO_PARAM_ERROR_INVALID_VALUE);

	bio = BIO_new_file(pem_file, "rb");
	if (bio == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Failed to open %s pem file", pem_file);
		return -1;
	}

	pkey = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);
	if (pkey != NULL) {
		type = LASSO_PEM_FILE_TYPE_PUB_KEY;
		EVP_PKEY_free(pkey);
	} else {
		BIO_reset(bio);
		pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
		if (pkey != NULL) {
			type = LASSO_PEM_FILE_TYPE_PRIVATE_KEY;
			EVP_PKEY_free(pkey);
		} else {
			BIO_reset(bio);
			cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
			if (cert != NULL) {
				type = LASSO_PEM_FILE_TYPE_CERT;
				X509_free(cert);
			}
		}
	}
	BIO_free(bio);

	return type;
}

/**
 * lasso_get_public_key_from_pem_cert_file:
 * @pem_cert_file: an X509 pem certificate file
 * 
 * Gets the public key in an X509 pem certificate file.
 * 
 * Return value: a public key or NULL if an error occurs.
 **/
xmlSecKeyPtr
lasso_get_public_key_from_pem_cert_file(const char *pem_cert_file)
{
	FILE *fd;
	X509 *pem_cert;
	xmlSecKeyDataPtr data;
	xmlSecKeyPtr key = NULL;

	g_return_val_if_fail(pem_cert_file != NULL, NULL);

	/* load pem certificate from file */
	fd = fopen(pem_cert_file, "r");
	if (fd == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Failed to open %s pem certificate file",
				pem_cert_file);
		return NULL;
	}
	/* read the pem X509 certificate */
	pem_cert = PEM_read_X509(fd, NULL, NULL, NULL);
	fclose(fd);
	if (pem_cert == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Failed to read X509 certificate");
		return NULL;
	}

	/* get public key value in certificate */
	data = xmlSecOpenSSLX509CertGetKey(pem_cert);
	if (data != NULL) {
		/* create key and set key value */
		key = xmlSecKeyCreate();
		xmlSecKeySetValue(key, data);
	} else {
		message(G_LOG_LEVEL_CRITICAL,
				"Failed to get the public key in the X509 certificate");
	}
	X509_free(pem_cert);

	return key;
}

/**
 * lasso_load_certs_from_pem_certs_chain_file:
 * @pem_certs_chain_file: a CA certificate chain file
 * 
 * Creates a keys manager and loads inside all the CA certificates of
 * @pem_certs_chain_file. Caller is responsible for freeing it with
 * xmlSecKeysMngrDestroy() function.
 * 
 * Return value: a newly allocated keys manager or NULL if an error occurs.
 **/
xmlSecKeysMngrPtr
lasso_load_certs_from_pem_certs_chain_file(const char* pem_certs_chain_file)
{
	xmlSecKeysMngrPtr keys_mngr;
	GIOChannel *gioc;
	gchar *line;
	gsize len, pos;
	GString *cert = NULL;
	gint ret;

	g_return_val_if_fail(pem_certs_chain_file != NULL, NULL);

	/* create keys manager */
	keys_mngr = xmlSecKeysMngrCreate();
	if (keys_mngr == NULL) {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_KEYS_MNGR_CREATION_FAILED));
		return NULL;
	}
	/* initialize keys manager */
	if (xmlSecCryptoAppDefaultKeysMngrInit(keys_mngr) < 0) {
		message(G_LOG_LEVEL_CRITICAL,
				lasso_strerror(LASSO_DS_ERROR_KEYS_MNGR_INIT_FAILED));
		xmlSecKeysMngrDestroy(keys_mngr);
		return NULL;
	}    

	gioc = g_io_channel_new_file(pem_certs_chain_file, "r", NULL);
	while (g_io_channel_read_line(gioc, &line, &len, &pos, NULL) == G_IO_STATUS_NORMAL) {
		if (g_strstr_len(line, 64, "BEGIN CERTIFICATE") != NULL) {
			cert = g_string_new(line);
		} else if (g_strstr_len(line, 64, "END CERTIFICATE") != NULL) {
			g_string_append(cert, line);
			/* load the new certificate found in the keys manager */
			ret = xmlSecCryptoAppKeysMngrCertLoadMemory(keys_mngr,
					(const xmlSecByte*) cert->str,
					(xmlSecSize) cert->len,
					xmlSecKeyDataFormatPem,
					xmlSecKeyDataTypeTrusted);
			g_string_free(cert, TRUE);
			cert = NULL;
			if (ret < 0) {
				if (line) {
					g_free(line);
					xmlSecKeysMngrDestroy(keys_mngr);
				}
				g_io_channel_shutdown(gioc, TRUE, NULL);
				return NULL;
			}
		} else if (cert != NULL && line != NULL && line[0] != '\0') {
			g_string_append(cert, line);
		} else {
			debug("Empty line found in the CA certificate chain file")
		}
		/* free last line read */
		if (line != NULL) {
			g_free(line);
			line = NULL;
		}
	}

	g_io_channel_shutdown(gioc, TRUE, NULL);

	return keys_mngr;
}

/**
 * lasso_query_sign:
 * @query: a query (an url-encoded node)
 * @sign_method: the Signature transform method
 * @private_key_file: the private key
 * 
 * Signs a query (url-encoded message).
 * 
 * Return value: a newly allocated query signed or NULL if an error occurs.
 **/
xmlChar*
lasso_query_sign(xmlChar *query, lassoSignatureMethod  sign_method, const char *private_key_file)
{
	BIO *bio = NULL;
	xmlChar *digest = NULL; /* 160 bit buffer */
	RSA *rsa = NULL;
	DSA *dsa = NULL;
	unsigned char *sigret = NULL;
	unsigned int siglen;
	xmlChar *b64_sigret = NULL, *e_b64_sigret = NULL;
	xmlChar *new_query = NULL, *s_new_query = NULL;
	int status = 0;
	char *t;

	g_return_val_if_fail(query != NULL, NULL);
	g_return_val_if_fail(sign_method == LASSO_SIGNATURE_METHOD_RSA_SHA1 ||
			sign_method == LASSO_SIGNATURE_METHOD_DSA_SHA1, NULL);
	g_return_val_if_fail(private_key_file != NULL, NULL);

	bio = BIO_new_file(private_key_file, "rb");
	if (bio == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Failed to open %s private key file",
				private_key_file);
		return NULL;
	}

	/* add SigAlg */
	switch (sign_method) {
		case LASSO_SIGNATURE_METHOD_RSA_SHA1:
			t = xmlURIEscapeStr(xmlSecHrefRsaSha1, NULL);
			new_query = g_strdup_printf("%s&SigAlg=%s", query, t);
			xmlFree(t);
			break;
		case LASSO_SIGNATURE_METHOD_DSA_SHA1:
			t = xmlURIEscapeStr(xmlSecHrefDsaSha1, NULL);
			new_query = g_strdup_printf("%s&SigAlg=%s", query, t);
			xmlFree(t);
			break;
	}

	/* build buffer digest */
	digest = lasso_sha1(new_query);
	if (digest == NULL) {
		message(G_LOG_LEVEL_CRITICAL, "Failed to build the buffer digest");
		goto done;
	}

	/* calculate signature value */
	if (sign_method == LASSO_SIGNATURE_METHOD_RSA_SHA1) {
		/* load private key */
		rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
		if (rsa == NULL) {
			goto done;
		}
		/* alloc memory for sigret */
		sigret = (unsigned char *)g_malloc (RSA_size(rsa));
		/* sign digest message */
		status = RSA_sign(NID_sha1, digest, 20, sigret, &siglen, rsa);
		RSA_free(rsa);
	}
	else if (sign_method == LASSO_SIGNATURE_METHOD_DSA_SHA1) {
		dsa = PEM_read_bio_DSAPrivateKey(bio, NULL, NULL, NULL);
		if (dsa == NULL) {
			goto done;
		}
		sigret = (unsigned char *)g_malloc (DSA_size(dsa));
		status = DSA_sign(NID_sha1, digest, 20, sigret, &siglen, dsa);
		DSA_free(dsa);
	}
	if (status == 0) {
		goto done;
	}

	/* Base64 encode the signature value */
	b64_sigret = xmlSecBase64Encode(sigret, siglen, 0);
	/* escape b64_sigret */
	e_b64_sigret = xmlURIEscapeStr(b64_sigret, NULL);

	/* add signature */
	switch (sign_method) {
		case LASSO_SIGNATURE_METHOD_RSA_SHA1:
			s_new_query = g_strdup_printf("%s&Signature=%s", new_query, e_b64_sigret);
			break;
		case LASSO_SIGNATURE_METHOD_DSA_SHA1:
			s_new_query = g_strdup_printf("%s&Signature=%s", new_query, e_b64_sigret);
			break;
	}

done:
	g_free(new_query);
	xmlFree(digest);
	BIO_free(bio);
	free(sigret);
	xmlFree(b64_sigret);
	free(e_b64_sigret);

	return s_new_query;
}

/**
 * lasso_query_verify_signature:
 * @query: a query (an url-encoded message)
 * @sender_public_key_file: the query sender public key
 * 
 * Verifies the query signature.
 * 
 * Return value: 0 if signature is valid
 * a positive value if signature was not found or is invalid
 * a negative value if an error occurs during verification
 **/
int
lasso_query_verify_signature(const char *query, const char *sender_public_key_file)
{
	BIO *bio = NULL;
	RSA *rsa = NULL;
	DSA *dsa = NULL;
	gchar **str_split = NULL;
	lassoSignatureMethod  sign_method;
	xmlChar *digest = NULL, *b64_signature = NULL;
	xmlChar *e_rsa_alg = NULL, *e_dsa_alg = NULL;
	xmlSecByte *signature = NULL;
	int key_size, status = 0, ret = 0;

	g_return_val_if_fail(query != NULL, LASSO_PARAM_ERROR_INVALID_VALUE);
	g_return_val_if_fail(sender_public_key_file != NULL, LASSO_PARAM_ERROR_INVALID_VALUE);

	/* split query, the signature MUST be the last param of the query */
	str_split = g_strsplit(query, "&Signature=", 0);
	if (str_split[1] == NULL) {
		ret = LASSO_DS_ERROR_SIGNATURE_NOT_FOUND;
		goto done;
	}

	/* create bio to read public key */
	bio = BIO_new_file(sender_public_key_file, "rb");
	if (bio == NULL) {
		message(G_LOG_LEVEL_CRITICAL, 
				lasso_strerror(LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED),
				sender_public_key_file);
		ret = LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED;
		goto done;
	}  

	/* get signature method (algorithm) and read public key */
	e_rsa_alg = xmlURIEscapeStr(xmlSecHrefRsaSha1, NULL);
	e_dsa_alg = xmlURIEscapeStr(xmlSecHrefDsaSha1, NULL);
	if (g_strrstr(str_split[0], e_rsa_alg) != NULL) {
		sign_method = LASSO_SIGNATURE_METHOD_RSA_SHA1;
		rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
		/* rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL); */
		if (rsa == NULL) {
			ret = LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED;
			goto done;
		}
		key_size = RSA_size(rsa);
	}
	else if (g_strrstr(str_split[0], e_dsa_alg) != NULL) {
		sign_method = LASSO_SIGNATURE_METHOD_DSA_SHA1;
		dsa = PEM_read_bio_DSA_PUBKEY(bio, NULL, NULL, NULL);
		if (dsa == NULL) {
			ret = LASSO_DS_ERROR_PUBLIC_KEY_LOAD_FAILED;
			goto done;
		}
		key_size = DSA_size(dsa);
	}
	else {
		message(G_LOG_LEVEL_CRITICAL, lasso_strerror(LASSO_DS_ERROR_INVALID_SIGALG));
		ret = LASSO_DS_ERROR_INVALID_SIGALG;
		goto done;
	}

	/* get signature (unescape + base64 decode) */
	signature = (xmlSecByte *)xmlMalloc(key_size+1);
	b64_signature = xmlURIUnescapeString(str_split[1], 0, NULL);
	xmlSecBase64Decode(b64_signature, signature, key_size+1);

	/* calculate signature digest */
	digest = lasso_sha1(str_split[0]);
	if (digest == NULL) {
		message(G_LOG_LEVEL_CRITICAL, 
				lasso_strerror(LASSO_DS_ERROR_DIGEST_COMPUTE_FAILED));
		ret = LASSO_DS_ERROR_DIGEST_COMPUTE_FAILED;
		goto done;
	}

	if (sign_method == LASSO_SIGNATURE_METHOD_RSA_SHA1) {
		status = RSA_verify(NID_sha1, digest, 20, signature, RSA_size(rsa), rsa);
		/* printf("OpenSSL %s\n", ERR_error_string(ERR_get_error(), NULL)); */
		/* printf("OpenSSL %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); */
	}
	else if (sign_method == LASSO_SIGNATURE_METHOD_DSA_SHA1) {
		status = DSA_verify(NID_sha1, digest, 20, signature, DSA_size(dsa), dsa);
	}
	if (status == 0) {
		ret = LASSO_DS_ERROR_INVALID_SIGNATURE;
	}

done:
	xmlFree(b64_signature);
	xmlFree(signature);
	xmlFree(digest);
	xmlFree(e_rsa_alg);
	xmlFree(e_dsa_alg);
	g_strfreev(str_split);
	BIO_free(bio);
	RSA_free(rsa);
	DSA_free(dsa);

	return ret;
}

/**
 * lasso_sha1:
 * @str: a string
 * 
 * Builds the SHA-1 message digest (cryptographic hash) of @str
 * 
 * Return value: 20-bytes buffer allocated with xmlMalloc
 **/
char*
lasso_sha1(const char *str)
{
	xmlChar *md;

	if (str == NULL)
		return NULL;

	md = xmlMalloc(20);
	return SHA1(str, strlen(str), md);
}

char** urlencoded_to_strings(const char *str)
{
	int i, n=1;
	char *st, *st2;
	char **result;

	st = (char*)str;
	while (strchr(st, '&')) {
		st = strchr(st, '&')+1;
		n++;
	}

	result = malloc(sizeof(char*)*n+2);
	result[n] = NULL;

	st = (char*)str;
	for (i=0; i<n; i++) {
		st2 = strchr(st, '&');
		st2 = st2 ? st2 : st+strlen(st);
		result[i] = xmlURIUnescapeString(st, st2-st, NULL);
		st = st2 + 1;
	}
	return result;
}

void
_debug(GLogLevelFlags level, const char *filename, int line,
		const char *function, const char *format, ...) 
{
	char debug_string[1024];
	time_t ts;
	char date[20];
	va_list args;

	va_start(args, format);
	vsnprintf(debug_string, 1024, format, args);
	va_end(args);

	time(&ts);
	strftime(date, 20, "%Y-%m-%d %H:%M:%S", localtime(&ts));

	if (level == G_LOG_LEVEL_DEBUG || level == G_LOG_LEVEL_CRITICAL) {
		g_log("Lasso", level, "%s (%s/%s:%d)\n======> %s",
				date, filename, function, line, debug_string);
	} else {
		g_log("Lasso", level, "%s\t%s", date, debug_string);
	}
}

int
error_code(GLogLevelFlags level, int error, ...)
{
	const char *format;
	char message[1024];
	va_list args;

	format = lasso_strerror(error);

	va_start(args, error);
	g_vsnprintf(message, 1024, format, args);
	va_end(args);

	return error;
}