source: libabac/abac_xml.c @ 831da18

abac0-leakabac0-mei
Last change on this file since 831da18 was 831da18, checked in by Mei <mei@…>, 11 years ago

1) getting ready to for 0.1.6

  • Property mode set to 100644
File size: 50.7 KB
Line 
1/* abac_xml.c, specifically for GENI */
2
3/* in xml, rc in general is, 1 is good, 0 or -1 is bad */
4
5#define _GNU_SOURCE
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9#include <time.h>
10
11#include <libxml/tree.h>
12#include <libxml/xmlmemory.h>
13#include <libxml/parser.h>
14
15#ifndef XMLSEC_NO_XSLT
16#include <libxslt/xslt.h>
17#include <libxslt/security.h>
18#endif /* XMLSEC_NO_XSLT */
19
20#include <xmlsec/xmlsec.h>
21#include <xmlsec/xmltree.h>
22#include <xmlsec/xmldsig.h>
23#include <xmlsec/base64.h>
24#include <xmlsec/templates.h>
25#include <xmlsec/crypto.h>
26#include <xmlsec/list.h>
27
28#include <openssl/sha.h>
29
30#include "abac.h"
31#include "abac_util.h"
32#include "abac_list.h"
33
34extern int abac_verifier_load_id_chars(abac_list_t*, char*, abac_keyid_map_t *); 
35extern void abac_get_sha_from_nake_pem(char *npem, char **sha1);
36extern void abac_split(char *string, char *delim, char **ret, int *num);
37static int debug=0;
38
39/* from Ted's reader */
40
41/* for accessing GENI privilege credentials */
42#define GENI_signed_credential "signed-credential"
43#define GENI_credential "credential"
44#define GENI_type "type"
45#define GENI_serial "serial"
46#define GENI_owner_gid "owner_gid"
47#define GENI_owner_urn "owner_urn"
48#define GENI_target_gid "target_gid"
49#define GENI_target_urn "target_urn"
50#define GENI_uuid "uuid"
51#define GENI_expires "expires"
52#define GENI_privileges "privileges"
53#define GENI_privilege "privilege"
54#define GENI_name "name"
55#define GENI_can_delegate "can_delegate"
56#define GENI_x509_certificate "X509Certificate"
57
58/* for accessing GENI abac credentials. signed-credential, credential, type and
59 * expires are present as well.  */
60#define GENI_abac "abac"
61#define GENI_rt0 "rt0"
62#define GENI_version "version"
63
64/* maximum credential stringlen */
65#define CREDLEN 1024
66/* Maximum version len */
67#define VERSIONLEN 256
68
69/* These templates are given in defines so that they can initialize the
70 * specialization structures. */
71
72/* XML template for a new RT0 v1.0 credential.  Fill in the RT0 to store (XML
73 * escaped) and the expiration time (formated using strftime_format and
74 * strftime). */
75#define template_v10 "<signed-credential>\n"\
76"    <credential xml:id=\"ref0\">\n"\
77"       <type>abac</type>\n"\
78"       <version>1.0</version>\n"\
79"       <expires>%s</expires>\n"\
80"       <rt0>%s</rt0>\n"\
81"    </credential>\n"\
82"    <signatures>\n"\
83"       <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n"\
84"           <SignedInfo>\n"\
85"               <CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\n"\
86"               <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n"\
87"               <Reference URI=\"#ref0\">\n"\
88"                   <Transforms>\n"\
89"                       <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n"\
90"                   </Transforms>\n"\
91"                   <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n"\
92"                   <DigestValue/>\n"\
93"               </Reference>\n"\
94"           </SignedInfo>\n"\
95"           <SignatureValue/>\n"\
96"           <KeyInfo>\n"\
97"             <KeyValue/>\n"\
98"               <X509Data>\n"\
99"                   <X509Certificate/>\n"\
100"                   <X509SubjectName/>\n"\
101"                   <X509IssuerSerial/>\n"\
102"               </X509Data>\n"\
103"           </KeyInfo>\n"\
104"       </Signature>\n"\
105"    </signatures>\n"\
106"</signed-credential>"
107
108/* XML template for a new RT0 v1.1 credential.  Fill in the RT0 to store (XML
109 * escaped) and the expiration time (formated using strftime_format and
110 * strftime). */
111#define template_v11 "<signed-credential>\n"\
112"    <credential xml:id=\"ref0\">\n"\
113"       <type>abac</type>\n"\
114"       <serial/>\n"\
115"       <owner_gid/>\n"\
116"       <target_gid/>\n"\
117"       <uuid/>\n"\
118"       <expires>%s</expires>\n"\
119"       <abac>\n"\
120"           <rt0>\n"\
121"               <version>1.1</version>\n"\
122"               %s\n"\
123"           </rt0>\n"\
124"       </abac>\n"\
125"    </credential>\n"\
126"    <signatures>\n"\
127"       <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n"\
128"           <SignedInfo>\n"\
129"               <CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\n"\
130"               <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n"\
131"               <Reference URI=\"#ref0\">\n"\
132"                   <Transforms>\n"\
133"                       <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n"\
134"                   </Transforms>\n"\
135"                   <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n"\
136"                   <DigestValue/>\n"\
137"               </Reference>\n"\
138"           </SignedInfo>\n"\
139"           <SignatureValue/>\n"\
140"           <KeyInfo>\n"\
141"             <KeyValue/>\n"\
142"               <X509Data>\n"\
143"                   <X509Certificate/>\n"\
144"                   <X509SubjectName/>\n"\
145"                   <X509IssuerSerial/>\n"\
146"               </X509Data>\n"\
147"           </KeyInfo>\n"\
148"       </Signature>\n"\
149"    </signatures>\n"\
150"</signed-credential>"
151
152/* Forward declarations of functions to parse and generate rt0 elements in
153 * various formats */
154xmlChar *encode_rt0_xml_v10(abac_attribute_t *);
155xmlChar *encode_rt0_xml_v11(abac_attribute_t *);
156xmlChar **parse_rt0_xml_v10(xmlNodePtr, abac_keyid_map_t *);
157xmlChar **parse_rt0_xml_v11(xmlNodePtr, abac_keyid_map_t *);
158
159/* Structure that specializes XML parsing */
160typedef struct {
161    /* Version to use these functions for */
162    char *version; 
163    /* Convert an ABAC attribute into an rt0 element */
164    xmlChar *(*rt0_to_xml)(abac_attribute_t *);
165    /* Convert an rt0 element into a list of RT0 strings */
166    xmlChar **(*xml_to_rt0)(xmlNodePtr, abac_keyid_map_t *);
167    /* The overall template to generate this version of credential */
168    char *out_template;
169} GENI_xml_processing_t;
170
171/* The processing specializations */
172GENI_xml_processing_t xml_proc[] = {
173    { "GENIv1.0", encode_rt0_xml_v10, parse_rt0_xml_v10, template_v10},
174    { "1.0", encode_rt0_xml_v10, parse_rt0_xml_v10, template_v10},
175    { "GENIv1.1", encode_rt0_xml_v11, parse_rt0_xml_v11, template_v11},
176    { "1.1", encode_rt0_xml_v11, parse_rt0_xml_v11, template_v11},
177    { NULL, NULL, NULL},
178};
179
180/* Query funtion to convert a processing version into the functions above */
181GENI_xml_processing_t *get_xml_processing(char *ver) {
182    int i ;
183
184    for (i = 0; xml_proc[i].version; i++) {
185        if (!strcmp(xml_proc[i].version, ver))
186            return &xml_proc[i];
187    }
188    return NULL;
189}
190
191
192/* Hex dump the contents of buf (length len) to stderr.  For debugging */
193static void dump_it(xmlChar *buf, int len) {
194    int i;
195
196    for (i=0; i < len; i++ ) 
197        fprintf(stderr, "%02x ", buf[i] & 0xff);
198    fprintf(stderr, "\n");
199}
200
201/* Convert a SHA1 hash to text for printing or use in strings.  keyid is the
202 * hash (SHA_DIGEST_LENGTH bytes long) and text is the output string (at least
203 * 2 * SHA_DIGEST_LENGTH +1 bytes long).  The caller is responsible for
204 * allocating and deallocating each of them. */
205static void sha1_to_text(xmlChar *keyid, xmlChar *text) {
206    int i = 0;
207
208    for (i=0; i < SHA_DIGEST_LENGTH; i++) 
209        snprintf((char *) text+2*i, 3, "%02x", keyid[i] & 0xff);
210}
211
212/*
213 * Returns the content pointer of the XML_TEXT node that is the child of the
214 * node passed in.  Node must point to an XML_ELEMENT node.  the return value
215 * is still part of node's XML document, so treat it as read only. */
216static xmlChar *get_element_content(xmlNodePtr node) {
217    xmlNodePtr text = NULL;
218
219    if ( node->type != XML_ELEMENT_NODE ) return NULL;
220    if ( !( text = node->children) ) return NULL;
221    if ( text->type != XML_TEXT_NODE ) return NULL;
222    return text->content;
223}
224
225/*Find the XML element named field that is a at or below node in the XML
226 * document and return a copy of the base64 decoded content of its content.
227 * For example, find key day in a signature and return it base64decoded.  buf
228 * is allocated and its length is returned in len.  Any values for buf and len
229 * are ignored and overwritten. */
230static int get_base64_field(xmlNodePtr node, xmlChar *field, 
231        xmlChar **buf, int *len) {
232    xmlChar *txt = NULL;
233
234    *buf = NULL;
235
236    if ( !(node = xmlSecFindNode(node, field, xmlSecDSigNs)))
237        goto fail;
238
239    if ( !(txt = get_element_content(node))) 
240            goto fail;
241   
242    *len = strlen((char *) txt);
243    if ( !(*buf = malloc(*len))) 
244        goto fail;
245
246    if ( (*len = xmlSecBase64Decode(txt, *buf, *len)) < 0 ) 
247        goto fail;
248
249    return 1;
250fail:
251    if ( *buf) free(*buf);
252    *len = 0;
253    return 0;
254}
255/* Construct an ASN.1 header for a field of type h that is len bytes long.
256 * Mosttly this creates the proper length encoding under ASN.1's length
257 * encoding rules. buf will contain the new header (and the caller is
258 * responsible for making sure it is at least 6 bytes long, though fewer are
259 * usually used.  The length of the constructed header is returned. This is
260 * used in creating a key hash from key data.*/
261static int make_asn1_header(char h, size_t len, xmlChar *buf) {
262    if ( len > 0x00ffffff) {
263        buf[0] = h;
264        buf[1] = 0x84;
265        buf[2] = (len >> 24) & 0xff;
266        buf[3] = (len >> 16) & 0xff;
267        buf[4] = (len >> 8) & 0xff;
268        buf[5] = (len) & 0xff;
269        return 6;
270    } else if ( len > 0x0000ffff ) {
271        buf[0] = h;
272        buf[1] = 0x83;
273        buf[2] = (len >> 16) & 0xff;
274        buf[3] = (len >> 8) & 0xff;
275        buf[4] = (len) & 0xff;
276        return 5;
277    } else if ( len > 0x000000ff ) {
278        buf[0] = h;
279        buf[1] = 0x82;
280        buf[2] = (len >> 8) & 0xff;
281        buf[3] = (len) & 0xff;
282        return 4;
283    } else if ( len > 0x80 ) {
284        buf[0] = h;
285        buf[1] = 0x81;
286        buf[2] = (len) & 0xff;
287        return 3;
288    } else {
289        buf[0] = h;
290        buf[1] = (len) & 0xff;
291        return 2;
292    }
293}
294
295/* Find the RSA key parameters in the KeyInfo section of the XML document
296 * pointed to by doc, construct the ASN.1 encoding of that key and SHA1 hash
297 * it.    This gives the standard keyid of that key.  keyid will be the binary
298 * encoding of that (the bits of the hash)  sha1_to_text will turn it to text.
299 * keyid must be at least SHA_DIGEST_LENGTH bytes long, and the caller is
300 * responsible for it. This routine returns 1 on success and 0 on failure. */
301static int get_keyid_from_keyinfo(xmlDocPtr doc, xmlChar *keyid) {
302    xmlNodePtr root = NULL; /* XML document root */
303    xmlNodePtr node = NULL; /* Scratch XML node */
304
305    xmlChar b0[20];         /* Header for the sequence */
306    xmlChar b1[20];         /* Header for the modulus */
307    xmlChar b2[20];         /* Header for the exponent */
308    int l0 = 0;             /* Header length for the sequence */
309    int l1 = 0;             /* Header length for the modulus */
310    int l2 = 0;             /* Header length for the exponent */
311
312    xmlChar *modBuf = NULL; /* Bytes of the modulus */
313    xmlChar *expBuf = NULL; /* Bytes of the exponent */
314    int modLen = 0;         /* Length of the modulus */
315    int expLen = 0;         /* Length of the exponent */
316
317    SHA_CTX sha;            /* SHA1 hash context */
318
319    int rv = 0;             /* return value */
320
321    if ( !SHA1_Init(&sha)) goto fail;
322
323    if ( !doc || !(root = xmlDocGetRootElement(doc)) ) 
324        goto fail;
325
326    /* Find the KeyInfo section to be the root of later searches */
327    if ( !(node = xmlSecFindNode(root, 
328                    xmlSecNodeKeyInfo, xmlSecDSigNs)))
329        goto fail;
330
331    /* Get the binary for the modulus and exponent */
332    if ( !get_base64_field(node, (xmlChar *) "Modulus", &modBuf, &modLen)) 
333        goto fail;
334    if ( !get_base64_field(node, (xmlChar *) "Exponent", &expBuf, &expLen)) 
335        goto fail;
336
337    /* Construct the headers for modulus and exponent.  Another weird fact
338     * about ASN.1 is that all the integers are signed, so if either the
339     * modulus or exponent has the high order bit of its first byte set, the
340     * ASN.1 encoding has a 0 byte prepended.  This code appends the 0 byte to
341     * the header, which results in the same hash. */
342    if ( modBuf[0] & 0x80 ) {
343        l1 = make_asn1_header(0x02, modLen +1, b1);
344        b1[l1++] = '\0';
345    } else {
346        l1 = make_asn1_header(0x02, modLen, b1);
347    }
348
349    if ( expBuf[0] & 0x80 ) {
350        l2 = make_asn1_header(0x02, expLen +1, b2);
351        b2[l2++] = '\0';
352    } else {
353        l2 = make_asn1_header(0x02, expLen, b2);
354    }
355
356    /* Sequence header: have to do it after we know the lengths of the inner
357     * headers. */
358    l0 = make_asn1_header(0x30, modLen + expLen + l1 + l2, b0);
359    /* Hash it all up in parts */
360    SHA1_Update(&sha, b0, l0);
361    SHA1_Update(&sha, b1, l1);
362    SHA1_Update(&sha, modBuf, modLen);
363    SHA1_Update(&sha, b2, l2);
364    SHA1_Update(&sha, expBuf, expLen);
365    SHA1_Final(keyid, &sha);
366    rv = 1;
367fail:
368
369    if (modBuf) free(modBuf);
370    if (expBuf) free(expBuf);
371    return rv;
372}
373
374/* Check the signature of either kind of credential - it'll work for basically
375 * any signed XML. Returns true if the signature checks and false otherwise.
376 * Takes a pointer to the XML document to check.  Similar to the examples at
377 * http://www.aleksey.com/xmlsec/api/xmlsec-examples.html */
378static int check_signature(xmlDocPtr doc) {
379    xmlNodePtr root = NULL;         /* Root XML node */
380    xmlNodePtr node = NULL;         /* Scratch XML node */
381    xmlSecKeyInfoCtxPtr keyCtx = NULL;/* Key info context.  Used to parse
382                                         KeyInfo */
383    xmlSecKeysMngrPtr keyMan = NULL;/* Key manager - used because we have
384                                       certificated. */
385    xmlSecKeyPtr key = NULL;        /* The key extracted */
386    xmlSecDSigCtxPtr dsigCtx = NULL;/* Signature context */
387    int rv = 0;                     /* Return value */
388
389    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
390        goto fail;
391
392    /* Find the KeyInfo section to pull the keys out. */
393    if ( !(node = xmlSecFindNode(root, 
394                    xmlSecNodeKeyInfo, xmlSecDSigNs)))
395        goto fail;
396
397    /* Create and initialize key, key manager, and context */
398    if ( !(key = xmlSecKeyCreate() ) )
399            goto fail;
400    if ( !(keyMan = xmlSecKeysMngrCreate()) ) 
401        goto fail;
402
403    if ( xmlSecCryptoAppDefaultKeysMngrInit(keyMan) < 0)
404        goto fail;
405
406    if ( !(keyCtx = xmlSecKeyInfoCtxCreate(keyMan)) ) 
407        goto fail;
408
409    /* Do not check certificate signatures */
410    keyCtx->flags |= XMLSEC_KEYINFO_FLAGS_X509DATA_DONT_VERIFY_CERTS;
411
412    /* Gather up the key data */
413    if ( xmlSecKeyInfoNodeRead(node, key, keyCtx) < 0 ) 
414        goto fail;
415
416    /* Set up the signature context and attack the keys */
417    if ( !(dsigCtx = xmlSecDSigCtxCreate(NULL)))
418        goto fail;
419
420    dsigCtx->signKey = key;
421
422    /* find the Signature section */
423    if ( !(node = xmlSecFindNode(root, 
424                    xmlSecNodeSignature, xmlSecDSigNs)))
425        goto fail;
426
427    /* Check it */
428    if ( (rv = xmlSecDSigCtxVerify(dsigCtx, node)) < 0 ) 
429        goto fail;
430
431    /* Strangely xmlSecDSigCtxVerify can return success even if the status is
432     * bad.  Check the status in the context explicitly and override the result
433     * above if necessary.*/
434    if ( dsigCtx->status != xmlSecDSigStatusSucceeded) 
435        goto fail;
436
437    return 1;
438fail:
439    if ( key ) xmlSecKeyDestroy(key);
440    if ( keyCtx ) xmlSecKeyInfoCtxDestroy(keyCtx);
441    if ( dsigCtx) xmlSecDSigCtxDestroy(dsigCtx);
442    return 0;
443}
444
445/* Extract a sha from PEM blob */
446static void extract_owner_sha1(xmlChar *pem, xmlChar **sha1) {
447    abac_get_sha_from_nake_pem((char *) pem, (char **)sha1); 
448    if(debug) fprintf(stderr,"owner sha1 is (%s)..\n", *sha1);
449}
450static void extract_target_sha1(xmlChar *pem, xmlChar **sha1) {
451    abac_get_sha_from_nake_pem((char *) pem,(char **)sha1); 
452    if(debug) fprintf(stderr,"group sha1 is (%s)..\n", *sha1);
453}
454
455/* Parse the content of the expires field and compare it to the time passed in
456 * n.  If expires is earlier, return false, else true.  If n is null, compare
457 * it to the current time. */
458static int check_GENI_expires(xmlChar *expires, struct tm *n) {
459    struct tm tv;   /* Parsed expires field */
460    time_t now;     /* Now in seconds since the epoch */
461    time_t exp;     /* expires in seconds since the epoch */
462
463    if (n) now = mktime(n);
464    else time(&now);
465
466    strptime((char *) expires, "%FT%TZ", &tv);
467    exp = timegm(&tv);
468
469    return difftime(exp, now) > 0.0;
470}
471
472/* Convert a parsed privilege in a GENI privilege string into one or more ABAC
473 * creds.  Rules are as in http://groups.geni.net/geni/wiki/TIEDCredentials .
474 * keyid is  the issuer's keyid, text_owner is the owners keyid (XXX:a
475 * placeholder) text_target is the target's keyid (XXX: a placeholder), priv is
476 * the privilege being assigned, and delegate is true if it can be delegated.
477 * carray is the output array of character strings that currently has *nc
478 * entries in it.  If nc has nothing in it, insert the "speaks_for" delegation
479 * rules.  Then add the privilege specific rules. On failure ***carray and its
480 * contents are freed and *nc is set to zero.*/
481static void add_privilege_credential_string(xmlChar *text_keyid, xmlChar *text_owner, 
482        xmlChar *text_target, xmlChar *priv, int delegate, xmlChar ***carray,
483        int *nc) {
484    xmlChar **rv = *carray;     /* Local pointer to the array of strings */
485    xmlChar **newrv = NULL;     /* Used to realloc the array of strings */
486    int ncred = *nc;            /* Local copy of the number of creds in rv */
487    int newc = (delegate) ? 3 : 1;  /* Number of new creds to add */
488    int base = ncred;           /* First new credential index.  This advances
489                                   as we add creds to rv. */
490    int i = 0;                  /* Scratch */
491
492    /* If rv is empty, add the speaks_for rules */
493    if (base == 0 ) newc += 2;
494
495    /* Resize rv */
496    if (!(newrv = realloc(rv, (base + newc) * sizeof(xmlChar *))))
497        goto fail;
498
499    for ( i = base; i < base +newc; i ++) { 
500        newrv[i] = NULL;
501    }
502
503    /* So fail works */
504    rv = newrv;
505    ncred = base + newc;
506
507    /* Add speaks_for rules  if needed */
508    if ( base == 0 ) {
509        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
510        snprintf((char *) rv[base], CREDLEN, 
511                "%s.speaks_for_%s <- %s.speaks_for_%s",
512                text_keyid, text_owner, text_owner, text_owner);
513        base++;
514        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
515        snprintf((char *) rv[base], CREDLEN, 
516                "%s.speaks_for_%s <- %s",
517                text_keyid, text_owner, text_owner);
518        base++;
519    }
520
521    /* The assignemnt of priv.  Always happens */
522    if ( !(rv[base] = malloc(CREDLEN))) goto fail;
523    snprintf((char *) rv[base], CREDLEN, 
524            "%s.%s_%s <- %s.speaks_for_%s",
525            text_keyid, priv, text_target, text_keyid, text_owner);
526    base++;
527    /* Add delegation rules */
528    if ( delegate ) {
529        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
530        snprintf((char *) rv[base], CREDLEN, 
531                "%s.%s_%s <- %s.can_delegate_%s_%s.%s_%s",
532                text_keyid, priv, text_target, text_keyid, priv, 
533                text_target, priv, text_target);
534        base++;
535        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
536        snprintf((char *) rv[base], CREDLEN, 
537                "%s.can_delegate_%s_%s <- %s",
538                text_keyid, priv, text_target, text_owner);
539        base++;
540    }
541    /* And return new values */
542    *carray = rv;
543    *nc = ncred;
544    return;
545fail:
546    if ( rv ) {
547        /* Delete all the allocations, ours or not, and clear the caller's
548         * variables */
549        for (i = 0; i < ncred; i++) 
550            if (rv[i]) free(rv[i]);
551        free(rv);
552    }
553    *carray = NULL;
554    *nc = 0;
555}
556
557
558/* Grab the issuer x509 blob */
559static xmlChar *get_issuer(xmlDocPtr doc) {
560    xmlNodePtr root = NULL;         /* Root XML node */
561    xmlNodePtr node = NULL;         /* Scratch XML node */
562    xmlNodePtr x509ptr = NULL;      /* XML X509Certificate node */
563    int rv = 0;                     /* Return value */
564    xmlChar *pem=NULL;
565
566    if (!(root = xmlDocGetRootElement(doc)) )
567        goto fail;
568
569    /* Find the KeyInfo section to be the root of later searches */
570    if ( !(node = xmlSecFindNode(root,
571                    xmlSecNodeKeyInfo, xmlSecDSigNs)))
572        goto fail;
573
574    if ( !(node = xmlSecFindNode(node,
575                    xmlSecNodeX509Data, xmlSecDSigNs)))
576        goto fail;
577
578    /* Find the X509Certificate from KeyInfo section */
579    if ( x509ptr = xmlSecFindNode(node, xmlSecNodeX509Certificate, xmlSecDSigNs)) {
580        pem=get_element_content(x509ptr);
581        } else {
582            goto fail;
583    }
584    return pem;
585fail:
586    return NULL;
587}
588
589/* Parse a GENI privilege credential (that has already had its signature
590 * checked) and return the RT0 strings that the credential is encoded as.  The
591 * return value is an array of strings, zero-terminated (like argv) that holds
592 * the RT0 strings.  It is NULL on failure. */
593static xmlChar **parse_privilege(xmlDocPtr doc, abac_list_t* ctxt_id_certs, 
594        abac_keyid_map_t *km) {
595    xmlNodePtr root = NULL;     /* XML root node */
596    xmlNodePtr node = NULL;     /* XML scratch node */
597    xmlNodePtr owner = NULL;    /* XML owner_gid node */
598    xmlNodePtr expires = NULL;  /* XML expires node */
599    xmlNodePtr target = NULL;   /* XML target_gid node */
600    xmlNodePtr privs = NULL;    /* XML privileges node */
601    xmlNodePtr priv = NULL;     /* XML privilege node - used to iterate */
602    xmlChar keyid[SHA_DIGEST_LENGTH];   /* Issuer key SHA1 */
603    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid as text */
604    xmlChar *owner_sha1 = NULL;         /* owner gid as text */
605    xmlChar *target_sha1 = NULL;        /* target gid as text */
606    xmlChar **newrv = NULL;     /* Used to realloc rv to add the NULL
607                                   terminator*/
608    xmlChar **rv = NULL;        /* return value */
609    int ncred = 0;              /* number of creds in rv, incase we need to
610                                   deallocate it */
611    int i = 0;                  /* scratch */
612
613    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
614        goto fail;
615
616    /* Get the issuer keyid */
617    if ( !get_keyid_from_keyinfo(doc, keyid)) 
618        goto fail;
619    sha1_to_text(keyid, text_keyid);
620
621    /* Find the various fields of interest */
622    if ( !(node = xmlSecFindNode(root, (xmlChar *) GENI_credential, NULL)))
623        goto fail;
624
625    /* Make sure this is not expired */
626    if ( !(expires = xmlSecFindNode(node, (xmlChar *) GENI_expires, NULL)))
627        goto fail;
628
629    if ( !check_GENI_expires(get_element_content(expires), NULL))
630        goto fail;
631
632    /* owner and target will be X.509 pem files from which we need to
633     * extract keyids for add_privilege_credential_string.  */
634    if ( !(owner = xmlSecFindNode(node, (xmlChar *) GENI_owner_gid, NULL)))
635        goto fail;
636    extract_owner_sha1(get_element_content(owner),&owner_sha1);
637
638    if ( !(target = xmlSecFindNode(node, (xmlChar *) GENI_target_gid, NULL)))
639        goto fail;
640    extract_target_sha1(get_element_content(target),&target_sha1);
641
642    /* extract issuer pem */
643    xmlChar *issuer_ptr=get_issuer(doc);
644
645    if ( !(privs = xmlSecFindNode(node, (xmlChar *) GENI_privileges, NULL)))
646        goto fail;
647
648    /* Iterate through the privileges, parsing out names and can_delegate and
649     * generating the strings from it. */
650    for (priv = privs->children; priv; priv = priv->next) {
651        /* reinitialized every time around */
652        xmlNodePtr n = NULL;
653        xmlChar *name = NULL;
654        int delegate = -1;
655
656        /* Ignore wayward text and other gook */
657        if ( priv->type != XML_ELEMENT_NODE) 
658            continue;
659
660        /* Ignore things that are not privilege nodes */
661        if ( strcmp((char *) priv->name, (char *) GENI_privilege) ) 
662            continue;
663
664        /* looking for name and can_delegate */
665        for (n = priv->children; n; n = n->next) {
666            if ( n->type != XML_ELEMENT_NODE ) 
667                continue;
668            if ( !strcmp((char *) n->name, (char *) GENI_name)) {
669                name = get_element_content(n);
670                continue;
671            }
672            if ( !strcmp((char *) n->name, (char *) GENI_can_delegate)) {
673                xmlChar *boolean = get_element_content(n);
674
675                if ( !strcmp((char *) boolean, "true") ||
676                        !strcmp((char *) boolean, "1") ) {
677                    delegate = 1;
678                } else if ( !strcmp((char *) boolean, "false") ||
679                        !strcmp((char *) boolean, "0") ) {
680                    delegate = 0;
681                } else {
682                    fprintf(stderr, "Unknown delegation value %s", boolean);
683                }
684            }
685        }
686        /* Found both name and can_delegate, add the RT0 to rv and ncred */
687        if ( name && delegate != -1 ) {
688            add_privilege_credential_string(text_keyid, 
689                    (xmlChar *) owner_sha1, (xmlChar *) target_sha1, name,
690                    delegate, &rv, &ncred);
691            if ( !rv ) goto fail;
692        }
693    }
694
695    /* Add the terminating NULL */
696    if (!(newrv = realloc(rv, sizeof(xmlChar*)*(ncred+1))))
697        goto fail;
698
699    newrv[ncred] = NULL;
700    /* able to extract some RT0s, load issuer credential as side-effect */
701    if(ncred !=1) {
702        /* load  issuer_ptr */ 
703        if(issuer_ptr && abac_verifier_load_id_chars(ctxt_id_certs, issuer_ptr, NULL) != 0 /*ABAC_CERT_SUCCESS*/)
704            goto fail;
705    }
706    return newrv;
707
708fail:
709    /* Throw away all of rv if there's an error */
710    if ( rv ) {
711        for (i = 0; i < ncred; i++) 
712            if (rv[i]) free(rv[i]);
713        free(rv);
714    }
715    return NULL;
716}
717
718/*
719 * If n has a child that is an element named name, return a pointer to it,
720 * other wise return NULL.
721 */
722static xmlNodePtr get_direct_child(xmlNodePtr n, xmlChar *name) {
723    xmlNodePtr c = NULL;
724
725    if ( !n ) return NULL;
726
727    for (c = n->children; c; c = c->next) {
728        if ( c->type != XML_ELEMENT_NODE ) 
729            continue;
730        if ( !strcmp((char *) c->name, (char *) name)) 
731            return c;
732    }
733    return NULL;
734}
735
736/*
737 * Convert a version 1.0 rt0 section to an RT0 string, returned in an array of
738 * strings.  This is just allocating the array and copying the string.  RT0 1.0
739 * has no structure.
740 */
741xmlChar **parse_rt0_xml_v10(xmlNodePtr n, abac_keyid_map_t *km) {
742    xmlChar *txt;
743    xmlChar **rv = NULL;
744
745    /* read the RT0 and return it */
746    if ( !(txt = get_element_content(n)) ) return NULL;
747
748    if ( !(rv = malloc(2 * sizeof(xmlChar *)))) return NULL;
749    if (!(rv[0] = malloc(strlen((char *) txt)+1))) {
750        free(rv);
751        return NULL;
752    }
753    strcpy((char *) rv[0], (char *) txt);
754    rv[1] = NULL;
755    return rv;
756}
757
758/* Return the length of the string pointed to by rn, ignoring whitespace */
759static int role_len(xmlChar *rn) {
760    xmlChar *p;
761    int len = 0;
762
763    for (p = rn; *p; p++) 
764        if ( !isspace(*p) ) len++;
765    return len;
766}
767
768/* Return the length of the RT0 string represented bt the RT0 1.1 term.  That
769 * term looks like:
770 * <head>
771 *  <ABACprincipal><keyid>...</keyid><mnemonic>...</menmonic></ABACprincipal>
772 *  <role>...</role>
773 *  <linking_role>...</linking_role>
774 * </head>
775 * The container can be either a head or a tail, and the role and linking_role
776 * are optional.  The result is the number of non whitespace characters in the
777 * keyid, role, and linking_role fields (if present) plus a dot to separate
778 * each field.
779 */
780static int term_len(xmlNodePtr n) {
781    int len = 0;
782    xmlNodePtr c = NULL;/* Scratch */
783
784    for (c = n->children; c; c = c->next) {
785        if ( c->type != XML_ELEMENT_NODE ) 
786            continue;
787        if ( !strcmp((char *) c->name, "ABACprincipal")) {
788            xmlNodePtr k = get_direct_child(c, "keyid");
789            if ( !k ) return -1;
790            len += role_len(get_element_content(k));
791        } else if (!strcmp((char *) c->name, "role")) {
792            len += role_len(get_element_content(c)) +1;
793        } else if (!strcmp((char *) c->name, "linking_role")) {
794            len += role_len(get_element_content(c)) +1;
795        }
796    }
797    return len;
798}
799
800/* Copy non-whitespace characters from rn to dest.  Return the final vaue of
801 * dest, but no guarantees are made about it.  The caller must make sure there
802 * is enough space in dest.
803 */
804static xmlChar *role_copy(xmlChar *rn, xmlChar *dest) {
805    while (*rn) {
806        if (!isspace(*rn)) *dest++ = *rn;
807        rn++;
808    }
809    return dest;
810}
811
812/* Turn the contents of the node pointer into a dotted string representation of
813 * the RT0 term.  For example
814 * <tail>
815 *  <ABACprincipal><keyid>P</keyid><mnemonic>...</menmonic></ABACprincipal>
816 *  <role>r2</role>
817 *  <linking_role>r1</linking_role>
818 * </tail>
819 * becomes P.r1.r2.
820 * In addition, if there is a mnemonic in the ABACPrincipal field, add it to
821 * the keyid_map (if there is a map).
822 */
823static xmlChar *term_copy(xmlNodePtr n, xmlChar *dest, abac_keyid_map_t *km) {
824    xmlNodePtr p = get_direct_child(n, "ABACprincipal");
825    xmlNodePtr k = NULL;
826    xmlNodePtr m = NULL;
827    char *ks = NULL;
828    char *ms = NULL;
829
830    if ( !p ) return NULL;
831    if ( !(k = get_direct_child(p, "keyid"))) return NULL;
832    if ( !(ks = get_element_content(k))) return NULL;
833    if ( !(dest = role_copy(ks, dest))) return NULL;
834    /* If there's a mnemonic string, add the mapping from keyid to mnemonic to
835     * the keymap */
836    if ( (m = get_direct_child(p, "mnemonic"))) {
837        if ( (ms = get_element_content(m))) {
838            abac_keyid_map_remove_keyid(km, ks);
839            abac_keyid_map_add_nickname(km, ks, ms);
840        }
841    }
842    if ( (p = get_direct_child(n, "linking_role"))) {
843        *dest++ = '.';
844        if ( !(dest = role_copy(get_element_content(p), dest))) return NULL;
845    }
846    if ( (p = get_direct_child(n, "role"))) {
847        *dest++ = '.';
848        if ( !(dest = role_copy(get_element_content(p), dest))) return NULL;
849    }
850    return dest;
851}
852
853/*
854 * Append at most sz characters from a to d and advance d by sz characters.  No
855 * checking is done.
856 */
857static xmlChar *append_and_move(xmlChar *d, xmlChar *a, int sz) {
858    int i = 0; 
859    for ( i = 0; i < sz && a[i] != '\0'; i++) 
860        *d++ = a[i];
861    return d;
862}
863
864static void partial_string_dump(char *s, char *e) {
865    for (; s!= e; s++) 
866        fprintf(stderr, "%c", *s);
867    fprintf(stderr, "\n");
868}
869
870
871/*
872 * Parse a structured RT0 v 1.1 xml into an RT0 string.  For example
873 * <head>
874 *  <ABACprincipal><keyid>A</keyid><mnemonic>...</menmonic></ABACprincipal>
875 *  <role>r</role>
876 * </head>
877 * <tail>
878 *  <ABACprincipal><keyid>B</keyid><mnemonic>...</menmonic></ABACprincipal>
879 *  <role>r2</role>
880 *  <linking_role>r1</linking_role>
881 * </tail>
882 * <tail>
883 *  <ABACprincipal><keyid>C</keyid><mnemonic>...</menmonic></ABACprincipal>
884 *  <role>r2</role>
885 * </tail>
886 *
887 * Converts to A.r<-B.r1.r2 & C.r2
888 */
889xmlChar **parse_rt0_xml_v11(xmlNodePtr n, abac_keyid_map_t *km) {
890    int len = 3;    /* Length of the RT0 string we're building. Initially 3 for
891                       the <- and end-of-string */
892    int heads = 0;  /* number of tails so far */
893    int tails = 0;  /* number of tails so far */
894    xmlNodePtr c = NULL;/* Scratch */
895    xmlChar **rv = NULL;
896    xmlChar *d = NULL;
897
898    /* Compute the length of the new string and make sure we have a head and at
899     * least one tail.
900     */
901    if ( !n ) return NULL;
902
903    for (c = n->children; c; c = c->next) {
904        if ( c->type != XML_ELEMENT_NODE ) 
905            continue;
906        if ( !strcmp((char *) c->name, "head") ) {
907            len += term_len(c);
908            heads ++;
909        } else if (!strcmp((char *) c->name, "tail")) {
910            len += term_len(c);
911            /* if more than one tail, add space for " & " */
912            if ( tails++) len += 3; 
913        }
914    }
915    if ( heads != 1 || tails < 1) return NULL;
916
917    /* Allocate the return value */
918    if ( !(rv = malloc(2 * sizeof(xmlChar *)))) return NULL;
919    if (!(rv[0] = malloc(len)) ) {
920        free(rv);
921        return NULL;
922    }
923    rv[1] = NULL;
924
925    /* Translate term by term */
926    d = rv[0];
927    if ( !( c = get_direct_child(n, "head"))) goto fail;
928    if ( !(d = term_copy(c, d, km))) goto fail;
929    d = append_and_move(d, "<-", 2);
930    tails = 0;
931    for (c = n->children; c; c = c->next) {
932        if ( c->type != XML_ELEMENT_NODE ) 
933            continue;
934        if ( !strcmp((char *) c->name, "tail") ) {
935            /* if more than one tail, add " & " */
936            if ( tails++) 
937                d = append_and_move(d, " & ", 3);
938            if ( !(d = term_copy(c, d, km))) goto fail;
939        }
940    }
941    *d++ = '\0';
942    return rv;
943
944fail:
945    free(rv[0]);
946    free(rv);
947    return NULL;
948} 
949/*
950 * Parse an ABAC credential (that has had its signature checked.  Make sure it
951 * has not expired and that its version is one we know.  Return the RT0 it
952 * encodes as the only entry in an NULL-terminated array of strings (just like
953 * parse_privilege). On failure return NULL.  In addition to parsing the
954 * certificate, we add the issuer's identity from the signature to the
955 * controlling context, if any.  ctxt_id_certs is the list of certificates to
956 * which the new certificate is added.
957 */
958xmlChar **parse_abac(xmlDocPtr doc, abac_list_t*ctxt_id_certs, abac_keyid_map_t *km) {
959    xmlNodePtr root = NULL;     /* XML root node */
960    xmlNodePtr node = NULL;     /* XML credential node */
961    xmlNodePtr rt0 = NULL;      /* XML rt0 node */
962    xmlNodePtr expires = NULL;  /* XML expires node */
963    xmlNodePtr version = NULL;  /* XML version node */
964    xmlChar keyid[SHA_DIGEST_LENGTH];/* issuer SHA1 hash */
965    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid in text */
966    xmlChar *txt;               /* rt0 content */
967    xmlChar **rv = NULL;        /* return value */
968    xmlChar *issuer_ptr=NULL;   /* Issuer certificate to add to ctxt_id_certs */
969    GENI_xml_processing_t *proc = NULL; /* Specialization for version number */
970    int ncred = 0;              /* number of creds in rv */
971    int i = 0;                  /* Scratch (used only in fail:)  */
972
973    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
974        goto fail;
975
976    /* Get the issuer keyid */
977    if ( !get_keyid_from_keyinfo(doc, keyid)) 
978        goto fail;
979    sha1_to_text(keyid, text_keyid);
980    /* get the various nodes of interest */
981    if ( !(node = xmlSecFindNode(root, (xmlChar *) GENI_credential, NULL)))
982        goto fail;
983    if ( !(expires = get_direct_child(node, (xmlChar *) GENI_expires)))
984        goto fail;
985    if ( !check_GENI_expires(get_element_content(expires), NULL))
986        goto fail;
987
988    if ( !(rt0 = get_direct_child(node, (xmlChar *) GENI_rt0))) {
989        if ( !(rt0 = get_direct_child(node, (xmlChar *) GENI_abac))) 
990            goto fail;
991        if ( !(rt0 = get_direct_child(rt0, (xmlChar *) GENI_rt0))) 
992            goto fail;
993    }
994
995    /* There are two places to look for a version.  The credential node and the
996     * rt0 node that is a child of the credential node.  The version element is
997     * only under the credential in the misdefined GENI abac v1.0. */
998    if ( !(version = get_direct_child(node, (xmlChar *) GENI_version))) {
999        if ( !(version = get_direct_child(rt0, (xmlChar *) GENI_version))) 
1000            goto fail;
1001    }
1002
1003
1004    /* Pick parsing specialization based on the version.  If we can't resolve a
1005     * processor, this is an unknown version. */
1006    if ( !(proc = get_xml_processing(get_element_content(version))))
1007        goto fail;
1008
1009    /* read the RT0 and return it */
1010    if ( !(rv = proc->xml_to_rt0(rt0, km)) ) goto fail;
1011    ncred=1;
1012
1013    /* extract issuer pem and insert */
1014    issuer_ptr=get_issuer(doc);
1015    if( issuer_ptr && 
1016            abac_verifier_load_id_chars(ctxt_id_certs,issuer_ptr, NULL) != 
1017            ABAC_CERT_SUCCESS) {
1018        goto fail;
1019    }
1020
1021    return rv;
1022fail:
1023    if ( rv ) {
1024        for (i = 0; i < ncred; i++) 
1025            if (rv[i]) free(rv[i]);
1026        free(rv);
1027    }
1028    return NULL;
1029}
1030
1031/* Check and parse a GENI credential.  Return the new RT0 rules in a
1032 * NULL-terminated array of strings.  If the signature or parsing fails, return
1033 * NULL. Demultiplexed to parse_privilege or parse_abac to do the parsing and
1034 * uses check_signature to confirm the sig. If ctxt_id_certs is a list of
1035 * identities known to a context.  If it is not NULL and identity certs appear
1036 * (as they do in GENI credentials) add them to that list, which adds them to
1037 * the ABAC context. */
1038char **read_credential(abac_list_t *ctxt_id_certs, char *infile, 
1039        char **in_xml, abac_keyid_map_t *km) {
1040    xmlChar **xml = (xmlChar **) in_xml;    /* Cast */
1041    xmlDocPtr doc = xmlParseFile(infile);   /* Parse the document */
1042    xmlNodePtr node = NULL;                 /* XML scratch node */
1043    xmlChar *text = NULL;                   /* Text of the type field */
1044    xmlChar **rv = NULL;                    /* return value from parse_* */
1045
1046    if ( !check_signature(doc) ) 
1047        goto fail;
1048    /* Parse out the type field */
1049    if ( !(node = xmlDocGetRootElement(doc)) ) 
1050        goto fail;
1051    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1052        goto fail;
1053    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1054        goto fail;
1055
1056    if ( !(text = get_element_content(node)) ) 
1057        goto fail;
1058
1059    /* Demux on type */
1060    if ( !strcmp((char *) text, "privilege")) {
1061        rv = parse_privilege(doc, ctxt_id_certs, km);
1062    } else if ( !strcmp((char *) text, "abac")) {
1063        rv = parse_abac(doc, ctxt_id_certs, km);
1064    } else { 
1065        goto fail;
1066    }
1067    int len=0;
1068    xmlDocDumpMemoryEnc(doc, xml, &len, "UTF-8");
1069    if(len == 0)
1070       goto fail;
1071
1072fail:
1073    xmlFreeDoc(doc);
1074    return (char **) rv;
1075}
1076
1077
1078/* format for dates in <expires> */
1079char *strftime_fmt = "%FT%TZ";
1080#define EXPIRESLEN 20
1081
1082/* Return a copy of str with > < and & replaced by &gt; &lt; and &amp; for
1083 * embedding in XML.  Caller is responsible for deallocating the return value
1084 * using xmlFree().
1085 */
1086static xmlChar *minimal_xml_escaping(xmlChar *str) {
1087    /* A quickie translation table with the character to escape, the output
1088     * string and the length of the output in it. The table is initialized with
1089     * the three translations we want. */
1090    static struct esc {
1091        xmlChar c;
1092        xmlChar *esc;
1093        int l;
1094    } escapes[] = {
1095        { (xmlChar) '<', (xmlChar *) "&lt;", 4 }, 
1096        { (xmlChar) '>', (xmlChar *) "&gt;", 4},
1097        { (xmlChar) '&', (xmlChar *) "&amp;", 5},
1098        { (xmlChar) '\0', NULL, 0 },
1099    };
1100
1101    xmlChar *rv = NULL;     /* Return value */
1102    xmlChar *p = NULL;      /* Scratch (walking str) */
1103    xmlChar *q = NULL;      /* Scratch (walking rv) */
1104    struct esc *e = NULL;   /* Scratch for walking escapes */
1105    int len = 0;            /* Length of rv */
1106
1107    /* Walk str and calculate how long the escaped version is */
1108    for ( p = str; *p ; p++) {
1109        int foundit = 0;
1110        for ( e = escapes; !foundit && e->c ; e++ ) {
1111            if ( *p == e->c ) {
1112                len += e->l;
1113                foundit = 1;
1114            }
1115        }
1116        if ( !foundit ) len++;
1117    }
1118    /* Allocate the new string */
1119    q = rv = (xmlChar *) xmlMalloc(len+1);
1120    /* copy str to rv, escaping when necessary */
1121    for ( p = str; *p ; p++) {
1122        int foundit = 0;
1123        for ( e = escapes; !foundit && e->c ; e++ ) {
1124            if ( *p == e->c ) {
1125                strncpy((char *) q, (char *) e->esc, e->l);
1126                q += e->l;
1127                foundit = 1;
1128            }
1129        }
1130        if ( !foundit ) *q++ = *p;
1131    }
1132    /* terminate rv */
1133    *q = '\0';
1134    return rv;
1135}
1136
1137xmlChar *encode_rt0_xml_v10(abac_attribute_t *a) {
1138    return minimal_xml_escaping(abac_attribute_role_string(a));
1139}
1140
1141/* Template to create a head element in structured XML for RT0 (v1.1).  All
1142 * heads are a single role element. There aer versions with and without
1143 * mnemonics. */
1144static char *head_template = 
1145"<head>\n"
1146"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1147"   <role>%s</role>\n"
1148"</head>\n";
1149
1150static char *head_template_w_mnemonic = 
1151"<head>\n"
1152"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1153"   <role>%s</role>\n"
1154"</head>\n";
1155
1156/* Templates to create a tail in structured XML  based on how many of
1157 * principal, role, and linking role are present. There are variants with
1158 * and without mnomonics. */
1159static char *tail_template[] = {
1160"<tail>\n"
1161"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1162"</tail>\n",
1163"<tail>\n"
1164"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1165"   <role>%s</role>\n"
1166"</tail>\n",
1167"<tail>\n"
1168"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1169"   <role>%s</role>\n"
1170"   <linking_role>%s</linking_role>\n"
1171"</tail>\n",
1172};
1173static char *tail_template_w_mnemonic[] = {
1174"<tail>\n"
1175"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1176"</tail>\n",
1177"<tail>\n"
1178"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1179"   <role>%s</role>\n"
1180"</tail>\n",
1181"<tail>\n"
1182"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1183"   <role>%s</role>\n"
1184"   <linking_role>%s</linking_role>\n"
1185"</tail>\n",
1186};
1187
1188/* These three functions are variations on the theme of printing out the XML
1189 * representation of tail roles in the XML credential.  They're separated out
1190 * to make reading encode_rt0_xml_v11 a little easier.  Each prints the role
1191 * (r) into the string tmp, adding mnemonic annotations from km if present.  Sz
1192 * is the number of bytes remaining in the overall string, and is always
1193 * smaller than the size of tmp.  The only differences are which templates are
1194 * used and how many strings are inserted.  The length of the generated string
1195 * is returned.
1196 */
1197static int encode_principal_role(abac_role_t *r, char *tmp,  int sz,
1198        abac_keyid_map_t *km) {
1199    char *p = minimal_xml_escaping(abac_role_principal(r));
1200    char *nick = NULL;
1201    int ts = 0;
1202
1203    if ( km ) 
1204        nick = abac_keyid_map_key_to_nickname(km, p);
1205
1206    if (nick) {
1207        ts = snprintf(tmp, sz, tail_template_w_mnemonic[0], p, nick);
1208        free(nick);
1209        nick = NULL;
1210    }
1211    else {
1212        ts = snprintf(tmp, sz, tail_template[0], p);
1213    }
1214    free(p);
1215    return ts;
1216}
1217
1218static int encode_single_role(abac_role_t *r, char *tmp,  int sz,
1219        abac_keyid_map_t *km) {
1220    char *p = minimal_xml_escaping(abac_role_principal(r));
1221    char *ro = minimal_xml_escaping(abac_role_role_name(r));
1222    char *nick = NULL;
1223    int ts = 0;
1224
1225    if ( km ) 
1226        nick = abac_keyid_map_key_to_nickname(km, p);
1227
1228    if (nick) {
1229        ts = snprintf(tmp, sz, tail_template_w_mnemonic[0], 
1230                p, nick, ro);
1231        free(nick);
1232        nick = NULL;
1233    }
1234    else {
1235        ts = snprintf(tmp, sz, tail_template[1], p, ro);
1236    }
1237    free(p);
1238    free(ro);
1239    return ts;
1240}
1241
1242static int encode_linking_role(abac_role_t *r, char *tmp,  int sz,
1243        abac_keyid_map_t *km) {
1244    char *p = minimal_xml_escaping(abac_role_principal(r));
1245    char *ro = minimal_xml_escaping(abac_role_role_name(r));
1246    char *li = minimal_xml_escaping(abac_role_linking_role(r));
1247    char *nick = NULL;     
1248    int ts = 0;
1249
1250    if ( km ) 
1251        nick = abac_keyid_map_key_to_nickname(km, p);
1252
1253    if (nick) {
1254        ts = snprintf(tmp, sz, tail_template_w_mnemonic[2], 
1255                p, nick, ro, li);
1256        free(nick);
1257        nick = NULL;
1258    }
1259    else {
1260        ts = snprintf(tmp, sz, tail_template[2], p, ro, li);
1261    }
1262    free(p);
1263    free(ro);
1264    free(li);
1265    return ts;
1266}
1267
1268/* Convert the given attribute to the RT0 structured XML representation used by
1269 * version 1.1 credentials.
1270 */
1271xmlChar *encode_rt0_xml_v11(abac_attribute_t *a) {
1272    int htlen = strlen(head_template_w_mnemonic);    /* head template length */
1273    int ttlen = strlen(tail_template_w_mnemonic[2]); /* length of the longest
1274                                                        tail template */
1275    /* Size of the string we'll need - start with a head template and string */
1276    int sz = strlen(abac_attribute_get_head(a)) + htlen;
1277    /* Number of tails in the sttribute */
1278    int ntails = abac_attribute_get_ntails(a);
1279    char *princ_role[2];    /* Used to split the head role */
1280    char *copy = abac_xstrdup(abac_attribute_get_head(a)); /* splitting */
1281    int npr = 2;            /* Number of parts in the head role */
1282    abac_keyid_map_t *km = (a) ? abac_attribute_get_keyid_map(a) : NULL;
1283    char *nick = NULL;      /* Mnemonic name */
1284    char *tmp = NULL;       /* A temporary to build each tail element */
1285    char *rv = NULL;        /* The return value */
1286    int i;                  /* Scratch */
1287
1288    /* Add the tail lengths to the total length (assume all tails will need the
1289     * largest template for slop). */
1290    for ( i = 0 ; i < ntails; i++)
1291        sz += strlen(abac_attribute_get_tail_n(a, i)) + ttlen;
1292
1293    /* Get the rv and scratch string.  Since tmp is as long as the whole
1294     * string, it's big enough for any substring */
1295    if ( !(rv = (char *) xmlMalloc(sz)) ) goto fail;
1296    if ( !(tmp = (char *) xmlMalloc(sz)) ) goto fail;
1297
1298    abac_split(copy, ".", princ_role, &npr);
1299    if ( npr != 2) 
1300        goto fail;
1301
1302    if ( km ) 
1303        nick = abac_keyid_map_key_to_nickname(km, princ_role[0]);
1304    /* Put the head in */
1305    if ( nick ) {
1306        sz -= snprintf(rv, sz, head_template_w_mnemonic, princ_role[0], 
1307                nick, princ_role[1]);
1308        free(nick);
1309        nick = NULL;
1310    } else {
1311        sz -= snprintf(rv, sz, head_template, princ_role[0], princ_role[1]);
1312    }
1313
1314    for ( i = 0 ; i < ntails; i++) {
1315        /* Make a role for each tail and use those functions to write out the
1316         * structures for the different kinds of role. */
1317        abac_role_t *r = abac_role_from_string(abac_attribute_get_tail_n(a,i));
1318        int ts;
1319
1320        if ( !r )
1321            goto fail;
1322
1323        if ( abac_role_is_principal(r))
1324            ts = encode_principal_role(r, tmp, sz, km);
1325        else if (abac_role_is_role(r))
1326            ts = encode_single_role(r, tmp, sz, km);
1327        else if (abac_role_is_linking(r))
1328            ts = encode_linking_role(r, tmp, sz, km);
1329
1330        free(r);
1331        if ( ts < 0 ) 
1332            goto fail;
1333
1334        strncat(rv, tmp, sz);
1335        sz -= ts;
1336    }
1337    free(tmp);
1338    return (xmlChar *) rv;
1339
1340fail:
1341    if (rv ) free(rv);
1342    if (tmp) free(tmp);
1343    return NULL;
1344}
1345
1346/* Make an new GENI abac credential with the rt0 rule that expires secs from
1347 * now.  cert is the PEM encoded X.509 of the issuer's certificate as a string.
1348 * certlen is the length of cert.  Returns the XML. Caller is responsible for
1349 * freeing it. */
1350char *make_credential(abac_attribute_t *attr, int secs, char *in_cert, 
1351        int in_certlen) {
1352    xmlSecByte *cert = (xmlSecByte *) in_cert; /* Cast of certificate */
1353    xmlSecSize certlen = (xmlSecSize) in_certlen; /* Cast of len */
1354    xmlDocPtr doc = NULL;       /* parsed XML document */
1355    xmlNodePtr root = NULL;     /* Root of the document */
1356    xmlNodePtr signNode = NULL; /* <Signature> element */
1357    xmlSecDSigCtxPtr dsigCtx = NULL;  /* Signing context */
1358    xmlChar *rt0_xml = NULL;    /* attr's RT0 as xml */
1359    xmlChar *rv = NULL;         /* return value */
1360    time_t exp;                 /* expriation time (seconds since epoch) */
1361    struct tm exp_tm;           /* expiration for formatting */
1362    char estr[EXPIRESLEN+1];    /* String with formatted expiration */
1363    char *temp = NULL;          /* populated XML template */
1364    int len = 0;                /* length of the populated template (temp) */
1365
1366    GENI_xml_processing_t *proc = get_xml_processing(
1367            abac_attribute_get_output_format(attr));
1368
1369    if ( !proc ) goto fail;
1370    if ( !(rt0_xml = proc->rt0_to_xml(attr))) goto fail;
1371
1372    /* Calculate the length of the populated template and allocate it */
1373    len = strlen((char *) proc->out_template)+EXPIRESLEN+
1374        strlen((char *) rt0_xml)+1;
1375
1376    if ( !(temp = malloc(len)) )
1377        goto fail;
1378
1379    /* format expiration */
1380    time(&exp);
1381    exp += secs;
1382    gmtime_r(&exp, &exp_tm);
1383
1384    if (strftime(estr, EXPIRESLEN+1, strftime_fmt, &exp_tm) == 0 ) 
1385        goto fail;
1386
1387    /* Populate template with  expiration and escaped rt0 */
1388    snprintf(temp, len, proc->out_template, estr, (char *) rt0_xml);
1389
1390    /* parse the populated template */
1391    if ( !(doc = xmlParseMemory(temp, len))) 
1392        goto fail;
1393
1394    if (!(root = xmlDocGetRootElement(doc)) )
1395        goto fail;
1396
1397    /* Find the signature element for the Signing call */
1398    signNode = xmlSecFindNode(root, xmlSecNodeSignature, xmlSecDSigNs);
1399
1400    /* Create the context */
1401    if ( !(dsigCtx = xmlSecDSigCtxCreate(NULL))) 
1402        goto fail;
1403
1404    /* Assign the key (a PEM key) */
1405    if (!(dsigCtx->signKey = xmlSecCryptoAppKeyLoadMemory(cert, certlen,
1406                    xmlSecKeyDataFormatPem, NULL, NULL, NULL)) )
1407        goto fail;
1408
1409    /* Load the certificate */
1410    if ( xmlSecCryptoAppKeyCertLoadMemory(dsigCtx->signKey, cert, certlen,
1411                xmlSecKeyDataFormatPem) < 0)
1412        goto fail;
1413
1414    /* Sign it */
1415    if ( xmlSecDSigCtxSign(dsigCtx, signNode) < 0)
1416        goto fail;
1417
1418    /* Store the signed credential to rv */
1419    xmlDocDumpMemoryEnc(doc, &rv, &len, "UTF-8");
1420fail:
1421    /* clean up */
1422    if (dsigCtx) 
1423        xmlSecDSigCtxDestroy(dsigCtx);
1424    if ( doc) xmlFreeDoc(doc);
1425    if (rt0_xml) xmlFree(rt0_xml);
1426    if ( temp) free(temp);
1427    return (char *) rv;
1428}
1429
1430#define CERTSIZE 4096
1431/* Read a file into a the dynamically allocated array buf.  Whatever was in buf
1432 * is discarded w/o freeing so it should initially be NULL and len 0. On return
1433 * buf contains as much of the contents of filename as possible and len is the
1434 * length of it.  The caller must free() buf. buf is zero terminated.*/
1435static void read_cert(char *filename, char **buf, int *len) {
1436    FILE *cert = NULL;
1437    char *nbuf = NULL;
1438    int cap = CERTSIZE;
1439    int r = 0;
1440
1441    *len = 0; 
1442    if (!(*buf = malloc(CERTSIZE))) return;
1443
1444    if ( !(cert = fopen(filename, "r"))) 
1445        goto fail;
1446
1447    /* Read cert, expanding buf as necessary */
1448    while ( (r = fread(*buf + *len, 1, cap - *len, cert)) != 0) {
1449        *len += r;
1450        if ( *len == cap ) {
1451            if ( !(nbuf = realloc(*buf, cap + CERTSIZE)) ) 
1452                goto fail;
1453            memcpy(nbuf, *buf, cap);
1454            cap += CERTSIZE;
1455            *buf = nbuf;
1456        }
1457    }
1458    /* Extend if we read exactly cap bytes so we can terminate the string */
1459    if ( *len == cap ) {
1460        if ( !(nbuf = realloc(*buf, cap + CERTSIZE)) ) 
1461            goto fail;
1462        memcpy(nbuf, *buf, cap);
1463        cap += CERTSIZE;
1464        *buf = nbuf;
1465    }
1466    (*buf)[*len] = '\0';
1467    return;
1468fail:
1469    if ( *buf) free(*buf);
1470    *buf = NULL;
1471    *len = 0;
1472    return;
1473}
1474
1475
1476/******** helper functions used by libabac **********************/
1477
1478/* Function to disable libXML2's debugging */
1479static void _nullGenericErrorFunc(void* ctxt, const char* msg, ...) { return; }
1480
1481/* Straight off http://www.aleksey.com/xmlsec/api/xmlsec-examples.html .
1482 * Voodoo.  But call it. */
1483int init_xmlsec() {
1484    /* Init xmlsec library */
1485    if(xmlSecInit() < 0) {
1486        fprintf(stderr, "Error: xmlsec initialization failed.\n");
1487        return(-1);
1488    }
1489
1490    /* Check loaded library version */
1491    if(xmlSecCheckVersion() != 1) {
1492        fprintf(stderr,
1493                "Error: loaded xmlsec library version is not compatible.\n");
1494        return(-1);
1495    }
1496
1497    /* Load default crypto engine if we are supporting dynamic
1498     * loading for xmlsec-crypto libraries. Use the crypto library
1499     * name ("openssl", "nss", etc.) to load corresponding
1500     * xmlsec-crypto library.
1501     */
1502#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
1503    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
1504        fprintf(stderr, "Error: unable to load default xmlsec-crypto library. "
1505                "Make sure\n" 
1506                "that you have it installed and check shared libraries path\n"
1507                "(LD_LIBRARY_PATH) envornment variable.\n");
1508        return(-1);     
1509    }
1510#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
1511
1512    /* Init crypto library */
1513    if(xmlSecCryptoAppInit(NULL) < 0) {
1514        fprintf(stderr, "Error: crypto initialization failed.\n");
1515        return(-1);
1516    }
1517
1518    /* Init xmlsec-crypto library */
1519    if(xmlSecCryptoInit() < 0) {
1520        fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
1521        return(-1);
1522    }
1523    /* Turn off the built in debugging */
1524    xmlThrDefSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1525    xmlSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1526
1527    return 0;
1528}
1529
1530int deinit_xmlsec() {
1531  /* no op for now */
1532    return 0;
1533}
1534
1535
1536/* parse the xml blob and extract keyid */ 
1537char *get_keyid_from_xml(char *xml) {
1538    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1539    xmlChar keyid[SHA_DIGEST_LENGTH];   /* Issuer key SHA1 */
1540    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid as text */
1541    char *ret=NULL;
1542
1543    /* Get the issuer keyid */
1544    if ( !get_keyid_from_keyinfo(doc, keyid))
1545        goto fail;
1546    sha1_to_text(keyid, text_keyid);
1547    ret=strdup((char *)text_keyid);
1548fail:
1549    xmlFreeDoc(doc);
1550    return ret;
1551}
1552
1553/* parse xml and get the expected expiration time and returns
1554 * (expiration time-current time)
1555 */
1556long get_validity_from_xml(char *xml) {
1557    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1558    xmlNodePtr node = NULL;                 /* XML scratch node */
1559    xmlNodePtr expires = NULL;  /* XML expires node */
1560    struct tm tv;   /* Parsed expires field */
1561    time_t now;     /* Now in seconds since the epoch */
1562    time_t exp;     /* expires in seconds since the epoch */
1563    long dtime=0;
1564
1565    if ( !(node = xmlDocGetRootElement(doc)) )
1566        goto fail;
1567
1568    if ( !(expires = xmlSecFindNode(node, (xmlChar *) GENI_expires, NULL)))
1569        goto fail;
1570
1571    xmlChar *etime=get_element_content(expires);
1572    time(&now);
1573
1574    strptime((char *) etime, "%FT%TZ", &tv);
1575    exp = timegm(&tv);
1576    dtime=difftime(exp, now);
1577
1578fail:
1579    xmlFreeDoc(doc);
1580    return dtime;
1581}
1582
1583/* parse xml structure and extract the attribute rules */
1584char **get_rt0_from_xml(abac_list_t *ctxt_id_certs,char *xml, abac_keyid_map_t *km) {
1585    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1586    xmlNodePtr node = NULL;                 /* XML scratch node */
1587    xmlChar *text = NULL;                   /* Text of the type field */
1588    xmlChar **rv = NULL;                    /* return value from parse_* */
1589   
1590    if ( !check_signature(doc) )
1591        goto fail;
1592    /* Parse out the type field */
1593    if ( !(node = xmlDocGetRootElement(doc)) )
1594        goto fail;
1595    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1596        goto fail;
1597    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1598        goto fail;
1599
1600    if ( !(text = get_element_content(node)) )
1601        goto fail;
1602
1603    /* Demux on type */
1604    if ( !strcmp((char *) text, "privilege")) {
1605        rv = parse_privilege(doc, ctxt_id_certs, km);
1606    } else if ( !strcmp((char *) text, "abac")) {
1607        rv = parse_abac(doc, ctxt_id_certs, km);
1608    } else {
1609        goto fail;
1610    }
1611fail:
1612    xmlFreeDoc(doc);
1613    return (char **)rv;
1614}
1615
1616
Note: See TracBrowser for help on using the repository browser.