source: libabac/abac_xml.c @ 547bac4

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

Prevent double free if key is attached to sig context

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