source: libabac/abac_xml.c @ 7f25e109

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

Much imporved ISO 8061 parsing (not perfect)

  • Property mode set to 100644
File size: 52.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 is_time_separator(char *c) {
451    return (*c == '\0' || *c == 'T');
452}
453
454static int is_tz_separator(char *c) {
455    return (*c == '\0' || *c == 'Z' || *c == '-' || *c=='+' );
456}
457
458static int parse_ISO_time(xmlChar *expires, struct tm *out) {
459    /* Parse an ISO 8601 formatted datetime.  Strptime isn't nearly smart
460     * enough to handle this without help.  ISO 8061 has a demented range of
461     * valid formats.  We parse this into "basic" format dates and times,
462     * separated by the T that splits a timestamp.  A "basic" format date only
463     * has the digits necessary for that representation.  Once the whole thing
464     * is cannonicalized, we call strptime on it.
465     *
466     * Return 0 on error.
467     */
468
469#define DATELEN 8
470#define TIMELEN 6
471#define ZONELEN 5
472/* 1 for the terminal \0 */
473#define PARSABLELEN DATELEN + TIMELEN + ZONELEN + 1
474
475    char *timeSep = NULL;
476    char *tzSep = NULL;
477    char *c = NULL;
478    int tot = 0;
479    char parsable[PARSABLELEN];
480
481    for (timeSep = (char *) expires; !is_time_separator(timeSep); timeSep++)
482        ;
483    if (*timeSep == '\0') return 0;
484    for (tzSep = timeSep+1; !is_tz_separator(tzSep); tzSep++)
485        ;
486
487    /* Found our markers, parse it into the parsable array */
488    /* Copy exactly DATELEN digits into parsable (%Y%m%d). */
489    tot = 0;
490    for ( c = (char *) expires; c != timeSep; c++ ) {
491        if (isdigit(*c)) {
492            if ( tot >= DATELEN) return 0;
493            parsable[tot++] = *c;
494        }
495    }
496    if ( tot != DATELEN ) return 0;
497
498    /* Copy exactly TIMELEN digits into parsable (%H%M%S) after the date. */
499    tot = 0;
500    for ( c = (char *) timeSep+1; c != tzSep; c++ ) {
501        if (isdigit(*c)) {
502            /* Only copy the first TIMELEN.  If the stamp includes fractions of
503             * a second, ignore 'em. */
504            if ( tot >= TIMELEN) break;
505            parsable[DATELEN + tot++] = *c;
506        }
507    }
508    if ( tot != TIMELEN ) return 0;
509    /* null-terminate parsable */
510    parsable[DATELEN+TIMELEN] = '\0';
511
512    /* If no timezone is given or Z is given, copy a GMT offset into parsable,
513     * otherwise parse ZONELEN digits or +/- into parsable after the DATE and
514     * TIME. */
515    if ( *tzSep == 'Z' || *tzSep == '\0' ) {
516        strncat(parsable, "+0000", ZONELEN);
517    }
518    else {
519        tot = 0;
520        for ( c = (char *) tzSep; *c != '\0'; c++ ) {
521            if (isdigit(*c) || *c == '+' || *c == '-') {
522                if ( tot >= ZONELEN) return 0;
523                parsable[DATELEN + TIMELEN + tot++] = *c;
524            }
525        }
526        if ( tot != ZONELEN ) return 0;
527    }
528    /* null-terminate parsable */
529    parsable[DATELEN+TIMELEN+ZONELEN] = '\0';
530    return ( strptime(parsable, "%Y%m%d%H%M%S%z", out) != NULL );
531}
532
533/* Parse the content of the expires field and compare it to the time passed in
534 * n.  If expires is earlier, return false, else true.  If n is null, compare
535 * it to the current time. */
536static int check_GENI_expires(xmlChar *expires, struct tm *n) {
537    struct tm tv;   /* Parsed expires field */
538    time_t now;     /* Now in seconds since the epoch */
539    time_t exp;     /* expires in seconds since the epoch */
540
541    if (n) now = mktime(n);
542    else time(&now);
543
544    if ( !parse_ISO_time(expires, &tv)) return 0;
545    exp = timegm(&tv);
546
547    return difftime(exp, now) > 0.0;
548}
549
550/* Convert a parsed privilege in a GENI privilege string into one or more ABAC
551 * creds.  Rules are as in http://groups.geni.net/geni/wiki/TIEDCredentials .
552 * keyid is  the issuer's keyid, text_owner is the owners keyid (XXX:a
553 * placeholder) text_target is the target's keyid (XXX: a placeholder), priv is
554 * the privilege being assigned, and delegate is true if it can be delegated.
555 * carray is the output array of character strings that currently has *nc
556 * entries in it.  If nc has nothing in it, insert the "speaks_for" delegation
557 * rules.  Then add the privilege specific rules. On failure ***carray and its
558 * contents are freed and *nc is set to zero.*/
559static void add_privilege_credential_string(xmlChar *text_keyid, xmlChar *text_owner, 
560        xmlChar *text_target, xmlChar *priv, int delegate, xmlChar ***carray,
561        int *nc) {
562    xmlChar **rv = *carray;     /* Local pointer to the array of strings */
563    xmlChar **newrv = NULL;     /* Used to realloc the array of strings */
564    int ncred = *nc;            /* Local copy of the number of creds in rv */
565    int newc = (delegate) ? 3 : 1;  /* Number of new creds to add */
566    int base = ncred;           /* First new credential index.  This advances
567                                   as we add creds to rv. */
568    int i = 0;                  /* Scratch */
569
570    /* If rv is empty, add the speaks_for rules */
571    if (base == 0 ) newc += 2;
572
573    /* Resize rv */
574    if (!(newrv = realloc(rv, (base + newc) * sizeof(xmlChar *))))
575        goto fail;
576
577    for ( i = base; i < base +newc; i ++) { 
578        newrv[i] = NULL;
579    }
580
581    /* So fail works */
582    rv = newrv;
583    ncred = base + newc;
584
585    /* Add speaks_for rules  if needed */
586    if ( base == 0 ) {
587        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
588        snprintf((char *) rv[base], CREDLEN, 
589                "%s.speaks_for_%s <- %s.speaks_for_%s",
590                text_keyid, text_owner, text_owner, text_owner);
591        base++;
592        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
593        snprintf((char *) rv[base], CREDLEN, 
594                "%s.speaks_for_%s <- %s",
595                text_keyid, text_owner, text_owner);
596        base++;
597    }
598
599    /* The assignemnt of priv.  Always happens */
600    if ( !(rv[base] = malloc(CREDLEN))) goto fail;
601    snprintf((char *) rv[base], CREDLEN, 
602            "%s.%s_%s <- %s.speaks_for_%s",
603            text_keyid, priv, text_target, text_keyid, text_owner);
604    base++;
605    /* Add delegation rules */
606    if ( delegate ) {
607        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
608        snprintf((char *) rv[base], CREDLEN, 
609                "%s.%s_%s <- %s.can_delegate_%s_%s.%s_%s",
610                text_keyid, priv, text_target, text_keyid, priv, 
611                text_target, priv, text_target);
612        base++;
613        if ( !(rv[base] = malloc(CREDLEN))) goto fail;
614        snprintf((char *) rv[base], CREDLEN, 
615                "%s.can_delegate_%s_%s <- %s",
616                text_keyid, priv, text_target, text_owner);
617        base++;
618    }
619    /* And return new values */
620    *carray = rv;
621    *nc = ncred;
622    return;
623fail:
624    if ( rv ) {
625        /* Delete all the allocations, ours or not, and clear the caller's
626         * variables */
627        for (i = 0; i < ncred; i++) 
628            if (rv[i]) free(rv[i]);
629        free(rv);
630    }
631    *carray = NULL;
632    *nc = 0;
633}
634
635
636/* Grab the issuer x509 blob */
637static xmlChar *get_issuer(xmlDocPtr doc) {
638    xmlNodePtr root = NULL;         /* Root XML node */
639    xmlNodePtr node = NULL;         /* Scratch XML node */
640    xmlNodePtr x509ptr = NULL;      /* XML X509Certificate node */
641    xmlChar *pem=NULL;
642
643    if (!(root = xmlDocGetRootElement(doc)) )
644        goto fail;
645
646    /* Find the KeyInfo section to be the root of later searches */
647    if ( !(node = xmlSecFindNode(root,
648                    xmlSecNodeKeyInfo, xmlSecDSigNs)))
649        goto fail;
650
651    if ( !(node = xmlSecFindNode(node,
652                    xmlSecNodeX509Data, xmlSecDSigNs)))
653        goto fail;
654
655    /* Find the X509Certificate from KeyInfo section */
656    if ( (x509ptr = xmlSecFindNode(node, xmlSecNodeX509Certificate, 
657                    xmlSecDSigNs))) {
658        pem=get_element_content(x509ptr);
659        } else {
660            goto fail;
661    }
662    return pem;
663fail:
664    return NULL;
665}
666
667/* Parse a GENI privilege credential (that has already had its signature
668 * checked) and return the RT0 strings that the credential is encoded as.  The
669 * return value is an array of strings, zero-terminated (like argv) that holds
670 * the RT0 strings.  It is NULL on failure. */
671static xmlChar **parse_privilege(xmlDocPtr doc, abac_list_t* ctxt_id_certs, 
672        abac_keyid_map_t *km) {
673    xmlNodePtr root = NULL;     /* XML root node */
674    xmlNodePtr node = NULL;     /* XML scratch node */
675    xmlNodePtr owner = NULL;    /* XML owner_gid node */
676    xmlNodePtr expires = NULL;  /* XML expires node */
677    xmlNodePtr target = NULL;   /* XML target_gid node */
678    xmlNodePtr privs = NULL;    /* XML privileges node */
679    xmlNodePtr priv = NULL;     /* XML privilege node - used to iterate */
680    xmlChar keyid[SHA_DIGEST_LENGTH];   /* Issuer key SHA1 */
681    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid as text */
682    xmlChar *owner_sha1 = NULL;         /* owner gid as text */
683    xmlChar *target_sha1 = NULL;        /* target gid as text */
684    xmlChar **newrv = NULL;     /* Used to realloc rv to add the NULL
685                                   terminator*/
686    xmlChar **rv = NULL;        /* return value */
687    int ncred = 0;              /* number of creds in rv, incase we need to
688                                   deallocate it */
689    int i = 0;                  /* scratch */
690
691    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
692        goto fail;
693
694    /* Get the issuer keyid */
695    if ( !get_keyid_from_keyinfo(doc, keyid)) 
696        goto fail;
697    sha1_to_text(keyid, text_keyid);
698
699    /* Find the various fields of interest */
700    if ( !(node = xmlSecFindNode(root, (xmlChar *) GENI_credential, NULL)))
701        goto fail;
702
703    /* Make sure this is not expired */
704    if ( !(expires = xmlSecFindNode(node, (xmlChar *) GENI_expires, NULL)))
705        goto fail;
706
707    if ( !check_GENI_expires(get_element_content(expires), NULL))
708        goto fail;
709
710    /* owner and target will be X.509 pem files from which we need to
711     * extract keyids for add_privilege_credential_string.  */
712    if ( !(owner = xmlSecFindNode(node, (xmlChar *) GENI_owner_gid, NULL)))
713        goto fail;
714    extract_owner_sha1(get_element_content(owner),&owner_sha1);
715
716    if ( !(target = xmlSecFindNode(node, (xmlChar *) GENI_target_gid, NULL)))
717        goto fail;
718    extract_target_sha1(get_element_content(target),&target_sha1);
719
720    /* extract issuer pem */
721    xmlChar *issuer_ptr=get_issuer(doc);
722
723    if ( !(privs = xmlSecFindNode(node, (xmlChar *) GENI_privileges, NULL)))
724        goto fail;
725
726    /* Iterate through the privileges, parsing out names and can_delegate and
727     * generating the strings from it. */
728    for (priv = privs->children; priv; priv = priv->next) {
729        /* reinitialized every time around */
730        xmlNodePtr n = NULL;
731        xmlChar *name = NULL;
732        int delegate = -1;
733
734        /* Ignore wayward text and other gook */
735        if ( priv->type != XML_ELEMENT_NODE) 
736            continue;
737
738        /* Ignore things that are not privilege nodes */
739        if ( strcmp((char *) priv->name, (char *) GENI_privilege) ) 
740            continue;
741
742        /* looking for name and can_delegate */
743        for (n = priv->children; n; n = n->next) {
744            if ( n->type != XML_ELEMENT_NODE ) 
745                continue;
746            if ( !strcmp((char *) n->name, (char *) GENI_name)) {
747                name = get_element_content(n);
748                continue;
749            }
750            if ( !strcmp((char *) n->name, (char *) GENI_can_delegate)) {
751                xmlChar *boolean = get_element_content(n);
752
753                if ( !strcmp((char *) boolean, "true") ||
754                        !strcmp((char *) boolean, "1") ) {
755                    delegate = 1;
756                } else if ( !strcmp((char *) boolean, "false") ||
757                        !strcmp((char *) boolean, "0") ) {
758                    delegate = 0;
759                } else {
760                    fprintf(stderr, "Unknown delegation value %s", boolean);
761                }
762            }
763        }
764        /* Found both name and can_delegate, add the RT0 to rv and ncred */
765        if ( name && delegate != -1 ) {
766            add_privilege_credential_string(text_keyid, 
767                    (xmlChar *) owner_sha1, (xmlChar *) target_sha1, name,
768                    delegate, &rv, &ncred);
769            if ( !rv ) goto fail;
770        }
771    }
772
773    /* Add the terminating NULL */
774    if (!(newrv = realloc(rv, sizeof(xmlChar*)*(ncred+1))))
775        goto fail;
776
777    newrv[ncred] = NULL;
778    /* able to extract some RT0s, load issuer credential as side-effect */
779    if(ncred !=1) {
780        /* load  issuer_ptr */ 
781        if(issuer_ptr && abac_verifier_load_id_chars(ctxt_id_certs, 
782                    (char *) issuer_ptr, NULL) != 0 /*ABAC_CERT_SUCCESS*/)
783            goto fail;
784    }
785    return newrv;
786
787fail:
788    /* Throw away all of rv if there's an error */
789    if ( rv ) {
790        for (i = 0; i < ncred; i++) 
791            if (rv[i]) free(rv[i]);
792        free(rv);
793    }
794    return NULL;
795}
796
797/*
798 * If n has a child that is an element named name, return a pointer to it,
799 * other wise return NULL.
800 */
801static xmlNodePtr get_direct_child(xmlNodePtr n, xmlChar *name) {
802    xmlNodePtr c = NULL;
803
804    if ( !n ) return NULL;
805
806    for (c = n->children; c; c = c->next) {
807        if ( c->type != XML_ELEMENT_NODE ) 
808            continue;
809        if ( !strcmp((char *) c->name, (char *) name)) 
810            return c;
811    }
812    return NULL;
813}
814
815/*
816 * Convert a version 1.0 rt0 section to an RT0 string, returned in an array of
817 * strings.  This is just allocating the array and copying the string.  RT0 1.0
818 * has no structure.
819 */
820xmlChar **parse_rt0_xml_v10(xmlNodePtr n, abac_keyid_map_t *km) {
821    xmlChar *txt;
822    xmlChar **rv = NULL;
823
824    /* read the RT0 and return it */
825    if ( !(txt = get_element_content(n)) ) return NULL;
826
827    if ( !(rv = malloc(2 * sizeof(xmlChar *)))) return NULL;
828    if (!(rv[0] = malloc(strlen((char *) txt)+1))) {
829        free(rv);
830        return NULL;
831    }
832    strcpy((char *) rv[0], (char *) txt);
833    rv[1] = NULL;
834    return rv;
835}
836
837/* Return the length of the string pointed to by rn, ignoring whitespace */
838static int role_len(xmlChar *rn) {
839    xmlChar *p;
840    int len = 0;
841
842    for (p = rn; *p; p++) 
843        if ( !isspace(*p) ) len++;
844    return len;
845}
846
847/* Return the length of the RT0 string represented bt the RT0 1.1 term.  That
848 * term looks like:
849 * <head>
850 *  <ABACprincipal><keyid>...</keyid><mnemonic>...</menmonic></ABACprincipal>
851 *  <role>...</role>
852 *  <linking_role>...</linking_role>
853 * </head>
854 * The container can be either a head or a tail, and the role and linking_role
855 * are optional.  The result is the number of non whitespace characters in the
856 * keyid, role, and linking_role fields (if present) plus a dot to separate
857 * each field.
858 */
859static int term_len(xmlNodePtr n) {
860    int len = 0;
861    xmlNodePtr c = NULL;/* Scratch */
862
863    for (c = n->children; c; c = c->next) {
864        if ( c->type != XML_ELEMENT_NODE ) 
865            continue;
866        if ( !strcmp((char *) c->name, "ABACprincipal")) {
867            xmlNodePtr k = get_direct_child(c, (xmlChar *)"keyid");
868            if ( !k ) return -1;
869            len += role_len(get_element_content(k));
870        } else if (!strcmp((char *) c->name, "role")) {
871            len += role_len(get_element_content(c)) +1;
872        } else if (!strcmp((char *) c->name, "linking_role")) {
873            len += role_len(get_element_content(c)) +1;
874        }
875    }
876    return len;
877}
878
879/* Copy non-whitespace characters from rn to dest.  Return the final vaue of
880 * dest, but no guarantees are made about it.  The caller must make sure there
881 * is enough space in dest.
882 */
883static xmlChar *role_copy(xmlChar *rn, xmlChar *dest) {
884    while (*rn) {
885        if (!isspace(*rn)) *dest++ = *rn;
886        rn++;
887    }
888    return dest;
889}
890
891/* Turn the contents of the node pointer into a dotted string representation of
892 * the RT0 term.  For example
893 * <tail>
894 *  <ABACprincipal><keyid>P</keyid><mnemonic>...</menmonic></ABACprincipal>
895 *  <role>r2</role>
896 *  <linking_role>r1</linking_role>
897 * </tail>
898 * becomes P.r1.r2.
899 * In addition, if there is a mnemonic in the ABACPrincipal field, add it to
900 * the keyid_map (if there is a map).
901 */
902static xmlChar *term_copy(xmlNodePtr n, xmlChar *dest, abac_keyid_map_t *km) {
903    xmlNodePtr p = get_direct_child(n, (xmlChar *)"ABACprincipal");
904    xmlNodePtr k = NULL;
905    xmlNodePtr m = NULL;
906    xmlChar *ks = NULL;
907    xmlChar *ms = NULL;
908
909    if ( !p ) return NULL;
910    if ( !(k = get_direct_child(p, (xmlChar *)"keyid"))) return NULL;
911    if ( !(ks = get_element_content(k))) return NULL;
912    if ( !(dest = role_copy(ks, dest))) return NULL;
913    /* If there's a mnemonic string, add the mapping from keyid to mnemonic to
914     * the keymap */
915    if ( (m = get_direct_child(p, (xmlChar *)"mnemonic"))) {
916        if ( (ms = get_element_content(m))) {
917            abac_keyid_map_remove_keyid(km, (char *) ks);
918            abac_keyid_map_add_nickname(km, (char *) ks, (char *) ms);
919        }
920    }
921    if ( (p = get_direct_child(n, (xmlChar *)"linking_role"))) {
922        *dest++ = '.';
923        if ( !(dest = role_copy(get_element_content(p), dest))) return NULL;
924    }
925    if ( (p = get_direct_child(n, (xmlChar *)"role"))) {
926        *dest++ = '.';
927        if ( !(dest = role_copy(get_element_content(p), dest))) return NULL;
928    }
929    return dest;
930}
931
932/*
933 * Append at most sz characters from a to d and advance d by sz characters.  No
934 * checking is done.
935 */
936static xmlChar *append_and_move(xmlChar *d, xmlChar *a, int sz) {
937    int i = 0; 
938    for ( i = 0; i < sz && a[i] != '\0'; i++) 
939        *d++ = a[i];
940    return d;
941}
942
943/*
944 * Parse a structured RT0 v 1.1 xml into an RT0 string.  For example
945 * <head>
946 *  <ABACprincipal><keyid>A</keyid><mnemonic>...</menmonic></ABACprincipal>
947 *  <role>r</role>
948 * </head>
949 * <tail>
950 *  <ABACprincipal><keyid>B</keyid><mnemonic>...</menmonic></ABACprincipal>
951 *  <role>r2</role>
952 *  <linking_role>r1</linking_role>
953 * </tail>
954 * <tail>
955 *  <ABACprincipal><keyid>C</keyid><mnemonic>...</menmonic></ABACprincipal>
956 *  <role>r2</role>
957 * </tail>
958 *
959 * Converts to A.r<-B.r1.r2 & C.r2
960 */
961xmlChar **parse_rt0_xml_v11(xmlNodePtr n, abac_keyid_map_t *km) {
962    int len = 3;    /* Length of the RT0 string we're building. Initially 3 for
963                       the <- and end-of-string */
964    int heads = 0;  /* number of tails so far */
965    int tails = 0;  /* number of tails so far */
966    xmlNodePtr c = NULL;/* Scratch */
967    xmlChar **rv = NULL;
968    xmlChar *d = NULL;
969
970    /* Compute the length of the new string and make sure we have a head and at
971     * least one tail.
972     */
973    if ( !n ) return NULL;
974
975    for (c = n->children; c; c = c->next) {
976        if ( c->type != XML_ELEMENT_NODE ) 
977            continue;
978        if ( !strcmp((char *) c->name, "head") ) {
979            len += term_len(c);
980            heads ++;
981        } else if (!strcmp((char *) c->name, "tail")) {
982            len += term_len(c);
983            /* if more than one tail, add space for " & " */
984            if ( tails++) len += 3; 
985        }
986    }
987    if ( heads != 1 || tails < 1) return NULL;
988
989    /* Allocate the return value */
990    if ( !(rv = malloc(2 * sizeof(xmlChar *)))) return NULL;
991    if (!(rv[0] = malloc(len)) ) {
992        free(rv);
993        return NULL;
994    }
995    rv[1] = NULL;
996
997    /* Translate term by term */
998    d = rv[0];
999    if ( !( c = get_direct_child(n, (xmlChar *)"head"))) goto fail;
1000    if ( !(d = term_copy(c, d, km))) goto fail;
1001    d = append_and_move(d, (xmlChar *)"<-", 2);
1002    tails = 0;
1003    for (c = n->children; c; c = c->next) {
1004        if ( c->type != XML_ELEMENT_NODE ) 
1005            continue;
1006        if ( !strcmp((char *) c->name, "tail") ) {
1007            /* if more than one tail, add " & " */
1008            if ( tails++) 
1009                d = append_and_move(d, (xmlChar *)" & ", 3);
1010            if ( !(d = term_copy(c, d, km))) goto fail;
1011        }
1012    }
1013    *d++ = '\0';
1014    return rv;
1015
1016fail:
1017    free(rv[0]);
1018    free(rv);
1019    return NULL;
1020} 
1021/*
1022 * Parse an ABAC credential (that has had its signature checked.  Make sure it
1023 * has not expired and that its version is one we know.  Return the RT0 it
1024 * encodes as the only entry in an NULL-terminated array of strings (just like
1025 * parse_privilege). On failure return NULL.  In addition to parsing the
1026 * certificate, we add the issuer's identity from the signature to the
1027 * controlling context, if any.  ctxt_id_certs is the list of certificates to
1028 * which the new certificate is added.
1029 */
1030xmlChar **parse_abac(xmlDocPtr doc, abac_list_t *ctxt_id_certs, abac_keyid_map_t *km) {
1031    xmlNodePtr root = NULL;     /* XML root node */
1032    xmlNodePtr node = NULL;     /* XML credential node */
1033    xmlNodePtr rt0 = NULL;      /* XML rt0 node */
1034    xmlNodePtr expires = NULL;  /* XML expires node */
1035    xmlNodePtr version = NULL;  /* XML version node */
1036    xmlChar keyid[SHA_DIGEST_LENGTH];/* issuer SHA1 hash */
1037    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid in text */
1038    xmlChar **rv = NULL;        /* return value */
1039    xmlChar *issuer_ptr=NULL;   /* Issuer certificate to add to ctxt_id_certs */
1040    GENI_xml_processing_t *proc = NULL; /* Specialization for version number */
1041    int ncred = 0;              /* number of creds in rv */
1042    int i = 0;                  /* Scratch (used only in fail:)  */
1043
1044    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
1045        goto fail;
1046
1047    /* Get the issuer keyid */
1048    if ( !get_keyid_from_keyinfo(doc, keyid)) 
1049        goto fail;
1050    sha1_to_text(keyid, text_keyid);
1051    /* get the various nodes of interest */
1052    if ( !(node = xmlSecFindNode(root, (xmlChar *) GENI_credential, NULL)))
1053        goto fail;
1054    if ( !(expires = get_direct_child(node, (xmlChar *) GENI_expires)))
1055        goto fail;
1056    if ( !check_GENI_expires(get_element_content(expires), NULL))
1057        goto fail;
1058
1059    if ( !(rt0 = get_direct_child(node, (xmlChar *) GENI_rt0))) {
1060        if ( !(rt0 = get_direct_child(node, (xmlChar *) GENI_abac))) 
1061            goto fail;
1062        if ( !(rt0 = get_direct_child(rt0, (xmlChar *) GENI_rt0))) 
1063            goto fail;
1064    }
1065
1066    /* There are two places to look for a version.  The credential node and the
1067     * rt0 node that is a child of the credential node.  The version element is
1068     * only under the credential in the misdefined GENI abac v1.0. */
1069    if ( !(version = get_direct_child(node, (xmlChar *) GENI_version))) {
1070        if ( !(version = get_direct_child(rt0, (xmlChar *) GENI_version))) 
1071            goto fail;
1072    }
1073
1074
1075    /* Pick parsing specialization based on the version.  If we can't resolve a
1076     * processor, this is an unknown version. */
1077    if ( !(proc = get_xml_processing((char *) get_element_content(version))))
1078        goto fail;
1079
1080    /* read the RT0 and return it */
1081    if ( !(rv = proc->xml_to_rt0(rt0, km)) ) goto fail;
1082    ncred=1;
1083
1084    /* extract issuer pem and insert */
1085    issuer_ptr=get_issuer(doc);
1086    if( issuer_ptr && 
1087            abac_verifier_load_id_chars(ctxt_id_certs, (char *)issuer_ptr, 
1088                NULL) != ABAC_CERT_SUCCESS) {
1089        goto fail;
1090    }
1091
1092    return rv;
1093fail:
1094    if ( rv ) {
1095        for (i = 0; i < ncred; i++) 
1096            if (rv[i]) free(rv[i]);
1097        free(rv);
1098    }
1099    return NULL;
1100}
1101
1102/* Check and parse a GENI credential.  Return the new RT0 rules in a
1103 * NULL-terminated array of strings.  If the signature or parsing fails, return
1104 * NULL. Demultiplexed to parse_privilege or parse_abac to do the parsing and
1105 * uses check_signature to confirm the sig. If ctxt_id_certs is a list of
1106 * identities known to a context.  If it is not NULL and identity certs appear
1107 * (as they do in GENI credentials) add them to that list, which adds them to
1108 * the ABAC context. */
1109char **read_credential(abac_list_t *ctxt_id_certs, char *infile, 
1110        char **in_xml, abac_keyid_map_t *km) {
1111    xmlChar **xml = (xmlChar **) in_xml;    /* Cast */
1112    xmlDocPtr doc = xmlParseFile(infile);   /* Parse the document */
1113    xmlNodePtr node = NULL;                 /* XML scratch node */
1114    xmlChar *text = NULL;                   /* Text of the type field */
1115    xmlChar **rv = NULL;                    /* return value from parse_* */
1116
1117    if ( !check_signature(doc) ) 
1118        goto fail;
1119    /* Parse out the type field */
1120    if ( !(node = xmlDocGetRootElement(doc)) ) 
1121        goto fail;
1122    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1123        goto fail;
1124    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1125        goto fail;
1126
1127    if ( !(text = get_element_content(node)) ) 
1128        goto fail;
1129
1130    /* Demux on type */
1131    if ( !strcmp((char *) text, "privilege")) {
1132        rv = parse_privilege(doc, ctxt_id_certs, km);
1133    } else if ( !strcmp((char *) text, "abac")) {
1134        rv = parse_abac(doc, ctxt_id_certs, km);
1135    } else { 
1136        goto fail;
1137    }
1138    int len=0;
1139    xmlDocDumpMemoryEnc(doc, xml, &len, "UTF-8");
1140    if(len == 0)
1141       goto fail;
1142
1143fail:
1144    xmlFreeDoc(doc);
1145    return (char **) rv;
1146}
1147
1148
1149/* format for dates in <expires> */
1150char *strftime_fmt = "%FT%TZ";
1151#define EXPIRESLEN 20
1152
1153/* Return a copy of str with > < and & replaced by &gt; &lt; and &amp; for
1154 * embedding in XML.  Caller is responsible for deallocating the return value
1155 * using xmlFree().
1156 */
1157static xmlChar *minimal_xml_escaping(xmlChar *str) {
1158    /* A quickie translation table with the character to escape, the output
1159     * string and the length of the output in it. The table is initialized with
1160     * the three translations we want. */
1161    static struct esc {
1162        xmlChar c;
1163        xmlChar *esc;
1164        int l;
1165    } escapes[] = {
1166        { (xmlChar) '<', (xmlChar *) "&lt;", 4 }, 
1167        { (xmlChar) '>', (xmlChar *) "&gt;", 4},
1168        { (xmlChar) '&', (xmlChar *) "&amp;", 5},
1169        { (xmlChar) '\0', NULL, 0 },
1170    };
1171
1172    xmlChar *rv = NULL;     /* Return value */
1173    xmlChar *p = NULL;      /* Scratch (walking str) */
1174    xmlChar *q = NULL;      /* Scratch (walking rv) */
1175    struct esc *e = NULL;   /* Scratch for walking escapes */
1176    int len = 0;            /* Length of rv */
1177
1178    /* Walk str and calculate how long the escaped version is */
1179    for ( p = str; *p ; p++) {
1180        int foundit = 0;
1181        for ( e = escapes; !foundit && e->c ; e++ ) {
1182            if ( *p == e->c ) {
1183                len += e->l;
1184                foundit = 1;
1185            }
1186        }
1187        if ( !foundit ) len++;
1188    }
1189    /* Allocate the new string */
1190    q = rv = (xmlChar *) xmlMalloc(len+1);
1191    /* copy str to rv, escaping when necessary */
1192    for ( p = str; *p ; p++) {
1193        int foundit = 0;
1194        for ( e = escapes; !foundit && e->c ; e++ ) {
1195            if ( *p == e->c ) {
1196                strncpy((char *) q, (char *) e->esc, e->l);
1197                q += e->l;
1198                foundit = 1;
1199            }
1200        }
1201        if ( !foundit ) *q++ = *p;
1202    }
1203    /* terminate rv */
1204    *q = '\0';
1205    return rv;
1206}
1207
1208xmlChar *encode_rt0_xml_v10(abac_attribute_t *a) {
1209    return minimal_xml_escaping((xmlChar *)abac_attribute_role_string(a));
1210}
1211
1212/* Template to create a head element in structured XML for RT0 (v1.1).  All
1213 * heads are a single role element. There aer versions with and without
1214 * mnemonics. */
1215static char *head_template = 
1216"<head>\n"
1217"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1218"   <role>%s</role>\n"
1219"</head>\n";
1220
1221static char *head_template_w_mnemonic = 
1222"<head>\n"
1223"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1224"   <role>%s</role>\n"
1225"</head>\n";
1226
1227/* Templates to create a tail in structured XML  based on how many of
1228 * principal, role, and linking role are present. There are variants with
1229 * and without mnomonics. */
1230static char *tail_template[] = {
1231"<tail>\n"
1232"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1233"</tail>\n",
1234"<tail>\n"
1235"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1236"   <role>%s</role>\n"
1237"</tail>\n",
1238"<tail>\n"
1239"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1240"   <role>%s</role>\n"
1241"   <linking_role>%s</linking_role>\n"
1242"</tail>\n",
1243};
1244static char *tail_template_w_mnemonic[] = {
1245"<tail>\n"
1246"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1247"</tail>\n",
1248"<tail>\n"
1249"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1250"   <role>%s</role>\n"
1251"</tail>\n",
1252"<tail>\n"
1253"   <ABACprincipal><keyid>%s</keyid><mnemonic>%s</mnemonic></ABACprincipal>\n"
1254"   <role>%s</role>\n"
1255"   <linking_role>%s</linking_role>\n"
1256"</tail>\n",
1257};
1258
1259/* These three functions are variations on the theme of printing out the XML
1260 * representation of tail roles in the XML credential.  They're separated out
1261 * to make reading encode_rt0_xml_v11 a little easier.  Each prints the role
1262 * (r) into the string tmp, adding mnemonic annotations from km if present.  Sz
1263 * is the number of bytes remaining in the overall string, and is always
1264 * smaller than the size of tmp.  The only differences are which templates are
1265 * used and how many strings are inserted.  The length of the generated string
1266 * is returned.
1267 */
1268static int encode_principal_role(abac_role_t *r, char *tmp,  int sz,
1269        abac_keyid_map_t *km) {
1270    xmlChar *p = minimal_xml_escaping((xmlChar *) abac_role_principal(r));
1271    char *nick = NULL;
1272    int ts = 0;
1273
1274    if ( km ) 
1275        nick = abac_keyid_map_key_to_nickname(km, (char *)p);
1276
1277    if (nick) {
1278        ts = snprintf(tmp, sz, tail_template_w_mnemonic[0], p, nick);
1279        free(nick);
1280        nick = NULL;
1281    }
1282    else {
1283        ts = snprintf(tmp, sz, tail_template[0], p);
1284    }
1285    free(p);
1286    return ts;
1287}
1288
1289static int encode_single_role(abac_role_t *r, char *tmp,  int sz,
1290        abac_keyid_map_t *km) {
1291    xmlChar *p = minimal_xml_escaping((xmlChar*)abac_role_principal(r));
1292    xmlChar *ro = minimal_xml_escaping((xmlChar *)abac_role_role_name(r));
1293    char *nick = NULL;
1294    int ts = 0;
1295
1296    if ( km ) 
1297        nick = abac_keyid_map_key_to_nickname(km, (char *)p);
1298
1299    if (nick) {
1300        ts = snprintf(tmp, sz, tail_template_w_mnemonic[0], 
1301                p, nick, ro);
1302        free(nick);
1303        nick = NULL;
1304    }
1305    else {
1306        ts = snprintf(tmp, sz, tail_template[1], p, ro);
1307    }
1308    free(p);
1309    free(ro);
1310    return ts;
1311}
1312
1313static int encode_linking_role(abac_role_t *r, char *tmp,  int sz,
1314        abac_keyid_map_t *km) {
1315    xmlChar *p = minimal_xml_escaping((xmlChar *)abac_role_principal(r));
1316    xmlChar *ro = minimal_xml_escaping((xmlChar*)abac_role_role_name(r));
1317    xmlChar *li = minimal_xml_escaping((xmlChar*)abac_role_linking_role(r));
1318    char *nick = NULL;     
1319    int ts = 0;
1320
1321    if ( km ) 
1322        nick = abac_keyid_map_key_to_nickname(km, (char *) p);
1323
1324    if (nick) {
1325        ts = snprintf(tmp, sz, tail_template_w_mnemonic[2], 
1326                p, nick, ro, li);
1327        free(nick);
1328        nick = NULL;
1329    }
1330    else {
1331        ts = snprintf(tmp, sz, tail_template[2], p, ro, li);
1332    }
1333    free(p);
1334    free(ro);
1335    free(li);
1336    return ts;
1337}
1338
1339/* Convert the given attribute to the RT0 structured XML representation used by
1340 * version 1.1 credentials.
1341 */
1342xmlChar *encode_rt0_xml_v11(abac_attribute_t *a) {
1343    int htlen = strlen(head_template_w_mnemonic);    /* head template length */
1344    int ttlen = strlen(tail_template_w_mnemonic[2]); /* length of the longest
1345                                                        tail template */
1346    /* Size of the string we'll need - start with a head template and string */
1347    int sz = strlen(abac_attribute_get_head(a)) + htlen;
1348    /* Number of tails in the sttribute */
1349    int ntails = abac_attribute_get_ntails(a);
1350    char *princ_role[2];    /* Used to split the head role */
1351    char *copy = abac_xstrdup(abac_attribute_get_head(a)); /* splitting */
1352    int npr = 2;            /* Number of parts in the head role */
1353    abac_keyid_map_t *km = (a) ? abac_attribute_get_keyid_map(a) : NULL;
1354    char *nick = NULL;      /* Mnemonic name */
1355    char *tmp = NULL;       /* A temporary to build each tail element */
1356    char *rv = NULL;        /* The return value */
1357    int i;                  /* Scratch */
1358
1359    /* Add the tail lengths to the total length (assume all tails will need the
1360     * largest template for slop). */
1361    for ( i = 0 ; i < ntails; i++)
1362        sz += strlen(abac_attribute_get_tail_n(a, i)) + ttlen;
1363
1364    /* Get the rv and scratch string.  Since tmp is as long as the whole
1365     * string, it's big enough for any substring */
1366    if ( !(rv = (char *) xmlMalloc(sz)) ) goto fail;
1367    if ( !(tmp = (char *) xmlMalloc(sz)) ) goto fail;
1368
1369    abac_split(copy, ".", princ_role, &npr);
1370    if ( npr != 2) 
1371        goto fail;
1372
1373    if ( km ) 
1374        nick = abac_keyid_map_key_to_nickname(km, princ_role[0]);
1375    /* Put the head in */
1376    if ( nick ) {
1377        sz -= snprintf(rv, sz, head_template_w_mnemonic, princ_role[0], 
1378                nick, princ_role[1]);
1379        free(nick);
1380        nick = NULL;
1381    } else {
1382        sz -= snprintf(rv, sz, head_template, princ_role[0], princ_role[1]);
1383    }
1384
1385    /* done with the copy */
1386    free(copy);
1387
1388    char *tail;
1389    for ( i = 0 ; i < ntails; i++) {
1390        /* Make a role for each tail and use those functions to write out the
1391         * structures for the different kinds of role. */
1392        tail=abac_attribute_get_tail_n(a,i);
1393        abac_role_t *r = abac_role_from_string(tail);
1394        int ts = -1;
1395
1396        if ( !r )
1397            goto fail;
1398
1399        if ( abac_role_is_principal(r))
1400            ts = encode_principal_role(r, tmp, sz, km);
1401        else if (abac_role_is_role(r))
1402            ts = encode_single_role(r, tmp, sz, km);
1403        else if (abac_role_is_linking(r))
1404            ts = encode_linking_role(r, tmp, sz, km);
1405
1406        abac_role_free(r);
1407        if ( ts < 0 ) 
1408            goto fail;
1409
1410        strncat(rv, tmp, sz);
1411        sz -= ts;
1412    }
1413    free(tmp);
1414    return (xmlChar *) rv;
1415
1416fail:
1417    if (rv ) free(rv);
1418    if (tmp) free(tmp);
1419    return NULL;
1420}
1421
1422/* Make an new GENI abac credential with the rt0 rule that expires secs from
1423 * now.  cert is the PEM encoded X.509 of the issuer's certificate as a string.
1424 * certlen is the length of cert.  Returns the XML. Caller is responsible for
1425 * freeing it. */
1426char *make_credential(abac_attribute_t *attr, int secs, char *in_cert, 
1427        int in_certlen) {
1428    xmlSecByte *cert = (xmlSecByte *) in_cert; /* Cast of certificate */
1429    xmlSecSize certlen = (xmlSecSize) in_certlen; /* Cast of len */
1430    xmlDocPtr doc = NULL;       /* parsed XML document */
1431    xmlNodePtr root = NULL;     /* Root of the document */
1432    xmlNodePtr signNode = NULL; /* <Signature> element */
1433    xmlSecDSigCtxPtr dsigCtx = NULL;  /* Signing context */
1434    xmlChar *rt0_xml = NULL;    /* attr's RT0 as xml */
1435    xmlChar *rv = NULL;         /* return value */
1436    time_t exp;                 /* expriation time (seconds since epoch) */
1437    struct tm exp_tm;           /* expiration for formatting */
1438    char estr[EXPIRESLEN+1];    /* String with formatted expiration */
1439    char *temp = NULL;          /* populated XML template */
1440    int len = 0;                /* length of the populated template (temp) */
1441
1442    GENI_xml_processing_t *proc = get_xml_processing(
1443            abac_attribute_get_output_format(attr));
1444
1445    if ( !proc ) goto fail;
1446    if ( !(rt0_xml = proc->rt0_to_xml(attr))) goto fail;
1447
1448    /* Calculate the length of the populated template and allocate it */
1449    len = strlen((char *) proc->out_template)+EXPIRESLEN+
1450        strlen((char *) rt0_xml)+1;
1451
1452    if ( !(temp = malloc(len)) )
1453        goto fail;
1454
1455    /* format expiration */
1456    time(&exp);
1457    exp += secs;
1458    gmtime_r(&exp, &exp_tm);
1459
1460    if (strftime(estr, EXPIRESLEN+1, strftime_fmt, &exp_tm) == 0 ) 
1461        goto fail;
1462
1463    /* Populate template with  expiration and escaped rt0 */
1464    snprintf(temp, len, proc->out_template, estr, (char *) rt0_xml);
1465
1466    /* parse the populated template */
1467    if ( !(doc = xmlParseMemory(temp, len))) 
1468        goto fail;
1469
1470    if (!(root = xmlDocGetRootElement(doc)) )
1471        goto fail;
1472
1473    /* Find the signature element for the Signing call */
1474    signNode = xmlSecFindNode(root, xmlSecNodeSignature, xmlSecDSigNs);
1475
1476    /* Create the context */
1477    if ( !(dsigCtx = xmlSecDSigCtxCreate(NULL))) 
1478        goto fail;
1479
1480    /* Assign the key (a PEM key) */
1481    if (!(dsigCtx->signKey = xmlSecCryptoAppKeyLoadMemory(cert, certlen,
1482                    xmlSecKeyDataFormatPem, NULL, NULL, NULL)) )
1483        goto fail;
1484
1485    /* Load the certificate */
1486    if ( xmlSecCryptoAppKeyCertLoadMemory(dsigCtx->signKey, cert, certlen,
1487                xmlSecKeyDataFormatPem) < 0)
1488        goto fail;
1489
1490    /* Sign it */
1491    if ( xmlSecDSigCtxSign(dsigCtx, signNode) < 0)
1492        goto fail;
1493
1494    /* Store the signed credential to rv */
1495    xmlDocDumpMemoryEnc(doc, &rv, &len, "UTF-8");
1496fail:
1497    /* clean up */
1498    if (dsigCtx) 
1499        xmlSecDSigCtxDestroy(dsigCtx);
1500    if ( doc) xmlFreeDoc(doc);
1501    if (rt0_xml) xmlFree(rt0_xml);
1502    if ( temp) free(temp);
1503    return (char *) rv;
1504}
1505
1506
1507/******** helper functions used by libabac **********************/
1508
1509/* Function to disable libXML2's debugging */
1510static void _nullGenericErrorFunc(void* ctxt, const char* msg, ...) { return; }
1511
1512/* Straight off http://www.aleksey.com/xmlsec/api/xmlsec-examples.html .
1513 * Voodoo.  But call it. */
1514int init_xmlsec() {
1515    /* Init xmlsec library */
1516    if(xmlSecInit() < 0) {
1517        fprintf(stderr, "Error: xmlsec initialization failed.\n");
1518        return(-1);
1519    }
1520
1521    /* Check loaded library version */
1522    if(xmlSecCheckVersion() != 1) {
1523        fprintf(stderr,
1524                "Error: loaded xmlsec library version is not compatible.\n");
1525        return(-1);
1526    }
1527
1528    /* Load default crypto engine if we are supporting dynamic
1529     * loading for xmlsec-crypto libraries. Use the crypto library
1530     * name ("openssl", "nss", etc.) to load corresponding
1531     * xmlsec-crypto library.
1532     */
1533#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
1534    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
1535        fprintf(stderr, "Error: unable to load default xmlsec-crypto library. "
1536                "Make sure\n" 
1537                "that you have it installed and check shared libraries path\n"
1538                "(LD_LIBRARY_PATH) envornment variable.\n");
1539        return(-1);     
1540    }
1541#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
1542
1543    /* Init crypto library */
1544    if(xmlSecCryptoAppInit(NULL) < 0) {
1545        fprintf(stderr, "Error: crypto initialization failed.\n");
1546        return(-1);
1547    }
1548
1549    /* Init xmlsec-crypto library */
1550    if(xmlSecCryptoInit() < 0) {
1551        fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
1552        return(-1);
1553    }
1554    /* Turn off the built in debugging */
1555    xmlThrDefSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1556    xmlSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1557
1558    return 0;
1559}
1560
1561int deinit_xmlsec() {
1562  /* no op for now */
1563    return 0;
1564}
1565
1566
1567/* parse the xml blob and extract keyid,
1568   caller should be freeing this if not
1569   needed anymore */ 
1570char *get_keyid_from_xml(char *xml) {
1571    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1572    xmlChar keyid[SHA_DIGEST_LENGTH];   /* Issuer key SHA1 */
1573    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid as text */
1574    char *ret=NULL;
1575
1576    /* Get the issuer keyid */
1577    if ( !get_keyid_from_keyinfo(doc, keyid))
1578        goto fail;
1579    sha1_to_text(keyid, text_keyid);
1580    ret=strdup((char *)text_keyid);
1581fail:
1582    xmlFreeDoc(doc);
1583    return ret;
1584}
1585
1586/* parse xml and get the expected expiration time and returns
1587 * (expiration time-current time)
1588 */
1589long get_validity_from_xml(char *xml) {
1590    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1591    xmlNodePtr node = NULL;                 /* XML scratch node */
1592    xmlNodePtr expires = NULL;  /* XML expires node */
1593    struct tm tv;   /* Parsed expires field */
1594    time_t now;     /* Now in seconds since the epoch */
1595    time_t exp;     /* expires in seconds since the epoch */
1596    long dtime=0;
1597
1598    if ( !(node = xmlDocGetRootElement(doc)) )
1599        goto fail;
1600
1601    if ( !(expires = xmlSecFindNode(node, (xmlChar *) GENI_expires, NULL)))
1602        goto fail;
1603
1604    xmlChar *etime=get_element_content(expires);
1605    time(&now);
1606
1607    if ( !parse_ISO_time(etime, &tv)) return 0;
1608    exp = timegm(&tv);
1609    dtime=difftime(exp, now);
1610
1611fail:
1612    xmlFreeDoc(doc);
1613    return dtime;
1614}
1615
1616/* parse xml structure and extract the attribute rules */
1617char **get_rt0_from_xml(abac_list_t *ctxt_id_certs,char *xml, abac_keyid_map_t *km) {
1618    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1619    xmlNodePtr node = NULL;                 /* XML scratch node */
1620    xmlChar *text = NULL;                   /* Text of the type field */
1621    xmlChar **rv = NULL;                    /* return value from parse_* */
1622   
1623    if ( !check_signature(doc) )
1624        goto fail;
1625    /* Parse out the type field */
1626    if ( !(node = xmlDocGetRootElement(doc)) )
1627        goto fail;
1628    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1629        goto fail;
1630    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1631        goto fail;
1632
1633    if ( !(text = get_element_content(node)) )
1634        goto fail;
1635
1636    /* Demux on type */
1637    if ( !strcmp((char *) text, "privilege")) {
1638        rv = parse_privilege(doc, ctxt_id_certs, km);
1639    } else if ( !strcmp((char *) text, "abac")) {
1640        rv = parse_abac(doc, ctxt_id_certs, km);
1641    } else {
1642        goto fail;
1643    }
1644fail:
1645    xmlFreeDoc(doc);
1646    return (char **)rv;
1647}
1648
1649
Note: See TracBrowser for help on using the repository browser.