source: libabac/abac_xml.c @ 373169a

Last change on this file since 373169a was 373169a, checked in by Ted Faber <faber@…>, 10 years ago

First attempt at IOS 8061 parsing - too brittle

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