source: libabac/abac_xml.c @ 7cefdb4

Last change on this file since 7cefdb4 was 756011e, checked in by Ted Faber <faber@…>, 11 years ago

Now we pass -Wall with no warnings.

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