source: libabac/abac_xml.c @ 34565bf

abac0-leakabac0-meitvf-new-xml
Last change on this file since 34565bf was afcafea, checked in by Ted Faber <faber@…>, 11 years ago

Outputs names with bake(Context)

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