source: libabac/abac_xml.c @ 63dcd99

abac0-leak
Last change on this file since 63dcd99 was f43e42c, checked in by Mei <mei@…>, 11 years ago

Merge branch 'abac0-mei' of git://abac.deterlab.net/abac

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