source: libabac/abac_xml.c @ a2b9fd2

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

Add more comments

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