~ubuntu-branches/ubuntu/edgy/lasso/edgy

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
/* $Id: tools.c,v 1.34 2004/09/01 09:59:53 fpeters Exp $ 
 *
 * 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 <libxml/uri.h>

#include <openssl/sha.h>

#include <xmlsec/xmltree.h>
#include <xmlsec/base64.h>
#include <xmlsec/xmldsig.h>
#include <xmlsec/templates.h>
#include <xmlsec/crypto.h>

#include <lasso/xml/tools.h>

xmlChar *
lasso_build_random_sequence(guint8 size)
{
  int i, val;
  xmlChar *seq;

  g_return_val_if_fail(size > 0, NULL);

  seq = xmlMalloc(size+1);

  for (i=0; i<size; i++) {
    val = g_random_int_range(0, 16);
    if (val < 10)
      seq[i] = 48 + val;
    else
      seq[i] = 65 + val-10;
  }
  seq[size] = '\0';

  return seq;
}

/**
 * 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)
 **/
xmlChar *
lasso_build_unique_id(guint8 size)
{
  /*
    The probability of 2 randomly chosen identifiers being identical MUST be
    less than 2^-128 and SHOULD be less than 2^-160.
    so we must have 128 <= exp <= 160
    we could build a 128-bit binary number but hexa system is shorter
    32 <= hexa number size <= 40
  */
  int i, val;
  xmlChar *id; /* , *enc_id; */

  g_return_val_if_fail((size >= 32 && size <= 40) || size == 0, NULL);

  if (size == 0) size = 32;
  id = g_malloc(size+1+1); /* one for _ and one for \0 */

  /* build hex number (<= 2^exp-1) */
  id[0] = '_';
  for (i=1; i<size+1; i++) {
    val = g_random_int_range(0, 16);
    if (val < 10)
      id[i] = 48 + val;
    else
      id[i] = 65 + val-10;
  }
  id[size+1] = '\0';

  /* base64 encoding of build string */
  /* enc_id = xmlSecBase64Encode((const xmlChar *)id, size+1, 0); */

  /* g_free(id); */
  /* return (enc_id); */
  return id;
}

/**
 * lasso_doc_get_node_content:
 * @doc: a doc
 * @name: the name
 * 
 * Gets the value of the first node having given @name.
 * 
 * Return value: a node value or NULL if no node found or if no content is
 * available
 **/
xmlChar *
lasso_doc_get_node_content(xmlDocPtr doc, const xmlChar *name)
{
  xmlNodePtr node;

  /* FIXME: bad namespace used */
  node = xmlSecFindNode(xmlDocGetRootElement(doc), name, xmlSecDSigNs);
  if (node != NULL)
    /* val returned must be xmlFree() */
    return xmlNodeGetContent(node);
  else
    return NULL;
}

/**
 * lasso_g_ptr_array_index:
 * @a: a GPtrArray
 * @i: the index
 * 
 * Gets the pointer at the given index @i of the pointer array.
 * 
 * Return value: the pointer at the given index.
 **/
xmlChar*
lasso_g_ptr_array_index(GPtrArray *a, guint i)
{
  if (a != NULL) {
    return g_ptr_array_index(a, i);
  }
  else {
    return NULL;
  }
}

/**
 * lasso_get_current_time:
 * 
 * Returns the current time, format is "yyyy-mm-ddThh:mm:ssZ".
 * 
 * Return value: a string
 **/
gchar *
lasso_get_current_time()
{
  struct tm *tm;
  GTimeVal time_val;
  gchar *ret = g_new0(gchar, 21);

  g_get_current_time(&time_val);
  tm = localtime(&(time_val.tv_sec));
  strftime((char *)ret, 21, "%Y-%m-%dT%H:%M:%SZ", tm);

  return ret;
}

/**
 * lasso_query_get_value:
 * @query: a query (an url-encoded node)
 * @param: the parameter
 * 
 * Returns the value of the given @param
 * 
 * Return value: a string or NULL if no parameter found
 **/
GPtrArray *
lasso_query_get_value(const gchar   *query,
		      const xmlChar *param)
{
  guint i;
  GData *gd;
  GPtrArray *tmp_array, *array = NULL;

  gd = lasso_query_to_dict(query);
  tmp_array = (GPtrArray *)g_datalist_get_data(&gd, (gchar *)param);
  /* create a copy of tmp_array */
  if (tmp_array != NULL) {
    array = g_ptr_array_new();
    for(i=0; i<tmp_array->len; i++)
      g_ptr_array_add(array, g_strdup(g_ptr_array_index(tmp_array, i)));
  }
  g_datalist_clear(&gd);
  return array;
}

static void
gdata_query_to_dict_destroy_notify(gpointer data)
{
  guint i;
  GPtrArray *array = data;

  for (i=0; i<array->len; i++) {
    g_free(array->pdata[i]);
  }
  g_ptr_array_free(array, TRUE);
}

/**
 * lasso_query_to_dict:
 * @query: the query (an url-encoded node)
 * 
 * Explodes query to build a dictonary.
 * Dictionary values are stored in GPtrArray.
 * The caller is responsible for freeing returned object by calling
 * g_datalist_clear() function.
 *
 * Return value: a dictonary
 **/
GData *
lasso_query_to_dict(const gchar *query)
{
  GData *gd = NULL;
  gchar **sa1, **sa2, **sa3;
  xmlChar *str_unescaped;
  GPtrArray *gpa;
  guint i, j;
  
  g_datalist_init(&gd);
  
  i = 0;
  sa1 = g_strsplit(query, "&", 0);

  while (sa1[i++] != NULL) {
    /* split of key=value to get (key, value) sub-strings */
    sa2 = g_strsplit(sa1[i-1], "=", 0);
    /* if no key / value found, then continue */
    if (sa2 == NULL) {
      continue;
    }
    /* if only a key but no value, then continue */
    if (sa2[1] == NULL) {
      continue;
    }

    /* printf("%s => ", sa2[0]); */
    /* split of value to get mutli values sub-strings separated by SPACE char */
    str_unescaped = lasso_str_unescape(sa2[1]);
    sa3 = g_strsplit(str_unescaped, " ", 0);
    if (sa3 == NULL) {
      g_strfreev(sa2);
      continue;
    }

    xmlFree(str_unescaped);
    gpa = g_ptr_array_new();
    j = 0;
    while (sa3[j++] != NULL) {
      g_ptr_array_add(gpa, g_strdup(sa3[j-1]));
      /* printf("%s, ", sa3[j-1]); */
    }
    /* printf("\n"); */
    /* add key => values in dict */
    g_datalist_set_data_full(&gd, sa2[0], gpa,
			     gdata_query_to_dict_destroy_notify);
    g_strfreev(sa3);
    g_strfreev(sa2);
  }  
  g_strfreev(sa1);

  return gd;
}

/**
 * lasso_query_verify_signature:
 * @query: a query  (an url-encoded and signed node)
 * @sender_public_key_file: the sender public key
 * @recipient_private_key_file: the recipient private key
 * 
 * Verifys the query's signature.
 * 
 * Return value: 1 if signature is valid, 0 if invalid, 2 if no signature found
 * and -1 if an error occurs.
 **/
int
lasso_query_verify_signature(const gchar   *query,
			     const xmlChar *sender_public_key_file,
			     const xmlChar *recipient_private_key_file)
{
  xmlDocPtr doc;
  xmlNodePtr sigNode, sigValNode;
  xmlSecDSigCtxPtr dsigCtx;
  xmlChar *str_unescaped;
  gchar **str_split;
  /*
     0: signature invalid
     1: signature ok
     2: signature not found
    -1: error during verification
  */
  gint ret = -1;

  /* split query, signature (must be last param) */
  str_split = g_strsplit(query, "&Signature=", 0);
  if (str_split[1] == NULL)
    return 2;
  /* re-create doc to verify (signed + enrypted) */
  doc = lasso_str_sign(str_split[0],
		       lassoSignatureMethodRsaSha1,
		       recipient_private_key_file);
  sigValNode = xmlSecFindNode(xmlDocGetRootElement(doc),
				          xmlSecNodeSignatureValue,
					  xmlSecDSigNs);
  /* set SignatureValue content */
  str_unescaped = lasso_str_unescape(str_split[1]);
  xmlNodeSetContent(sigValNode, str_unescaped);
  g_free(str_unescaped);

  g_strfreev(str_split);
  /*xmlDocDump(stdout, doc);*/

  /* find start node */
  sigNode = xmlSecFindNode(xmlDocGetRootElement(doc),
			   xmlSecNodeSignature, xmlSecDSigNs);
  
  /* create signature context */
  dsigCtx = xmlSecDSigCtxCreate(NULL);
  if(dsigCtx == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to create signature context\n");
    goto done;
  }
  
  /* load public key */
  dsigCtx->signKey = xmlSecCryptoAppKeyLoad(sender_public_key_file,
					    xmlSecKeyDataFormatPem,
					    NULL, NULL, NULL);
  if(dsigCtx->signKey == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to load public pem key from \"%s\"\n",
	    sender_public_key_file);
    goto done;
  }
  
  /* Verify signature */
  if(xmlSecDSigCtxVerify(dsigCtx, sigNode) < 0) {
    message(G_LOG_LEVEL_CRITICAL, "Signature verify failed\n");
    ret = 0;
    goto done;
  }
  
  /* print verification result to stdout and return */
  if(dsigCtx->status == xmlSecDSigStatusSucceeded) {
    ret = 1;
  }
  else {
    ret = 0;
  }
  
 done:
  /* cleanup */
  if(dsigCtx != NULL) {
    xmlSecDSigCtxDestroy(dsigCtx);
  }
  
  if(doc != NULL) {
    xmlFreeDoc(doc);
  }
  return ret;
}

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

  if (str != NULL) {
    md = xmlMalloc(20);
    return SHA1(str, strlen(str), md);
  }
  
  return NULL;
}

/**
 * lasso_str_escape:
 * @str: a string
 * 
 * Escapes the given string @str.
 * 
 * Return value: a new escaped string or NULL in case of error.
 **/
xmlChar *
lasso_str_escape(xmlChar *str)
{
  /* value returned must be xmlFree() */
  return xmlURIEscapeStr((const xmlChar *)str, NULL);
}

xmlChar *
lasso_str_hash(xmlChar    *str,
	       const char *private_key_file)
{
  xmlDocPtr doc;
  xmlChar *b64_digest, *digest = g_new0(xmlChar, 21);
  gint i;

  doc = lasso_str_sign(str,
		       lassoSignatureMethodRsaSha1,
		       private_key_file);
  b64_digest = xmlNodeGetContent(xmlSecFindNode(
			  	 	xmlDocGetRootElement(doc),
					xmlSecNodeDigestValue,
					xmlSecDSigNs));
  i = xmlSecBase64Decode(b64_digest, digest, 21);
  /* printf("Decoded string %s length is %d\n", digest, i); */
  xmlFree(b64_digest);
  xmlFreeDoc(doc);
  /* value returned must be xmlFree() */
  return digest;
}

/**
 * lasso_str_sign:
 * @str: 
 * @sign_method: 
 * @private_key_file: 
 * 
 * 
 * 
 * Return value: 
 **/
xmlDocPtr
lasso_str_sign(xmlChar              *str,
	       lassoSignatureMethod  sign_method,
	       const char           *private_key_file)
{
  /* FIXME : renamed fct into lasso_query_add_signature
     SHOULD returned a query (xmlChar) instead of xmlDoc */
  xmlDocPtr  doc = xmlNewDoc("1.0");
  xmlNodePtr envelope = xmlNewNode(NULL, "Envelope");
  xmlNodePtr cdata, data = xmlNewNode(NULL, "Data");
  xmlNodePtr signNode = NULL;
  xmlNodePtr refNode = NULL;
  xmlNodePtr keyInfoNode = NULL;
  xmlSecDSigCtxPtr dsigCtx = NULL;

  /* create doc */
  xmlNewNs(envelope, "urn:envelope", NULL);
  cdata = xmlNewCDataBlock(doc, str, strlen(str));
  xmlAddChild(envelope, data);
  xmlAddChild(data, cdata);
  xmlAddChild((xmlNodePtr)doc, envelope);

  /* create signature template for enveloped signature */
  switch (sign_method) {
  case lassoSignatureMethodRsaSha1:
    signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
					 xmlSecTransformRsaSha1Id, NULL);
    break;
  case lassoSignatureMethodDsaSha1:
    signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
					 xmlSecTransformDsaSha1Id, NULL);
    break;
  }

  if (signNode == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to create signature template\n");
    goto done;		
  }
  
  /* add <dsig:Signature/> node to the doc */
  xmlAddChild(xmlDocGetRootElement(doc), signNode);
  
  /* add reference */
  refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
					    NULL, NULL, NULL);
  if (refNode == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to add reference to signature template\n");
    goto done;		
  }
  
  /* add enveloped transform */
  if (xmlSecTmplReferenceAddTransform(refNode,
				      xmlSecTransformEnvelopedId) == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to add enveloped transform to reference\n");
    goto done;		
  }
  
  /* add <dsig:KeyInfo/> and <dsig:KeyName/> nodes to put key name in the
     signed document */
  keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
  if (keyInfoNode == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to add key info\n");
    goto done;		
  }
  
  if (xmlSecTmplKeyInfoAddKeyName(keyInfoNode, NULL) == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to add key name\n");
    goto done;		
  }
  
  /* create signature context */
  dsigCtx = xmlSecDSigCtxCreate(NULL);
  if (dsigCtx == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to create signature context\n");
    goto done;
  }

  /* load private key */
  dsigCtx->signKey = xmlSecCryptoAppKeyLoad(private_key_file,
					    xmlSecKeyDataFormatPem,
					    NULL, NULL, NULL);
  if (dsigCtx->signKey == NULL) {
    message(G_LOG_LEVEL_CRITICAL, "Failed to load private pem key from \"%s\"\n",
	    private_key_file);
    goto done;
  }

  /* sign the template */
  if (xmlSecDSigCtxSign(dsigCtx, signNode) < 0) {
    message(G_LOG_LEVEL_CRITICAL, "Signature failed\n");
    goto done;
  }
  
  /* xmlDocDump(stdout, doc); */
  xmlSecDSigCtxDestroy(dsigCtx);
  /* doc must be freed be caller */
  return doc;

 done:    
  /* cleanup */
  if (dsigCtx != NULL) {
    xmlSecDSigCtxDestroy(dsigCtx);
  }
  
  if (doc != NULL) {
    xmlFreeDoc(doc); 
  }
  return NULL;
}

/**
 * lasso_str_unescape:
 * @str: an escaped string
 * 
 * Unescapes the given string @str.
 * 
 * Return value: a new unescaped string or NULL in case of error.
 **/
xmlChar *
lasso_str_unescape(xmlChar *str)
{
  xmlChar *ret;

  ret = g_malloc(strlen(str) * 2); /* XXX why *2?  strlen(str) should be enough */
  xmlURIUnescapeString((const char *)str, 0, ret);
  return ret;
}