source: libabac/abac_xml.c @ 09aa249

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

That's not how strcat works.

  • Property mode set to 100644
File size: 46.8 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    int i = 0; 
837    for ( i = 0; i < sz && a[i] != '\0'; i++) 
838        *d++ = a[i];
839    return d;
840}
841
842static void partial_string_dump(char *s, char *e) {
843    for (; s!= e; s++) 
844        fprintf(stderr, "%c", *s);
845    fprintf(stderr, "\n");
846}
847
848
849/*
850 * Parse a structured RT0 v 1.1 xml into an RT0 string.  For example
851 * <head>
852 *  <ABACprincipal><keyid>A</keyid><mnemonic>...</menmonic></ABACprincipal>
853 *  <role>r</role>
854 * </head>
855 * <tail>
856 *  <ABACprincipal><keyid>B</keyid><mnemonic>...</menmonic></ABACprincipal>
857 *  <role>r2</role>
858 *  <linking_role>r1</linking_role>
859 * </tail>
860 * <tail>
861 *  <ABACprincipal><keyid>C</keyid><mnemonic>...</menmonic></ABACprincipal>
862 *  <role>r2</role>
863 * </tail>
864 *
865 * Converts to A.r<-B.r1.r2 & C.r2
866 */
867xmlChar **parse_rt0_xml_v11(xmlNodePtr n) {
868    int len = 3;    /* Length of the RT0 string we're building. Initially 3 for
869                       the <- and end-of-string */
870    int heads = 0;  /* number of tails so far */
871    int tails = 0;  /* number of tails so far */
872    xmlNodePtr c = NULL;/* Scratch */
873    xmlChar **rv = NULL;
874    xmlChar *d = NULL;
875
876    /* Compute the length of the new string and make sure we have a head and at
877     * least one tail.
878     */
879    if ( !n ) return NULL;
880
881    for (c = n->children; c; c = c->next) {
882        if ( c->type != XML_ELEMENT_NODE ) 
883            continue;
884        if ( !strcmp((char *) c->name, "head") ) {
885            len += term_len(c);
886            heads ++;
887        } else if (!strcmp((char *) c->name, "tail")) {
888            len += term_len(c);
889            /* if more than one tail, add space for " & " */
890            if ( tails++) len += 3; 
891        }
892    }
893    if ( heads != 1 || tails < 1) return NULL;
894
895    /* Allocate the return value */
896    if ( !(rv = malloc(2 * sizeof(xmlChar *)))) return NULL;
897    if (!(rv[0] = malloc(len)) ) {
898        free(rv);
899        return NULL;
900    }
901
902    /* Translate term by term */
903    d = rv[0];
904    if ( !( c = get_direct_child(n, "head"))) goto fail;
905    if ( !(d = term_copy(c, d))) goto fail;
906    d = append_and_move(d, "<-", 2);
907    tails = 0;
908    for (c = n->children; c; c = c->next) {
909        if ( c->type != XML_ELEMENT_NODE ) 
910            continue;
911        if ( !strcmp((char *) c->name, "tail") ) {
912            /* if more than one tail, add " & " */
913            if ( tails++) 
914                d = append_and_move(d, " & ", 3);
915            if ( !(d = term_copy(c, d))) goto fail;
916        }
917    }
918    *d++ = '\0';
919    return rv;
920
921fail:
922    free(rv[0]);
923    free(rv);
924    return NULL;
925} 
926/*
927 * Parse an ABAC credential (that has had its signature checked.  Make sure it
928 * has not expired and that its version is one we know.  Return the RT0 it
929 * encodes as the only entry in an NULL-terminated array of strings (just like
930 * parse_privilege). On failure return NULL.  In addition to parsing the
931 * certificate, we add the issuer's identity from the signature to the
932 * controlling context, if any.  ctxt_id_certs is the list of certificates to
933 * which the new certificate is added.
934 */
935xmlChar **parse_abac(xmlDocPtr doc, void *ctxt_id_certs) {
936    xmlNodePtr root = NULL;     /* XML root node */
937    xmlNodePtr node = NULL;     /* XML credential node */
938    xmlNodePtr rt0 = NULL;      /* XML rt0 node */
939    xmlNodePtr expires = NULL;  /* XML expires node */
940    xmlNodePtr version = NULL;  /* XML version node */
941    xmlChar keyid[SHA_DIGEST_LENGTH];/* issuer SHA1 hash */
942    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid in text */
943    xmlChar *txt;               /* rt0 content */
944    xmlChar **rv = NULL;        /* return value */
945    xmlChar *issuer_ptr=NULL;   /* Issuer certificate to add to ctxt_id_certs */
946    GENI_xml_processing_t *proc = NULL; /* Specialization for version number */
947    int ncred = 0;              /* number of creds in rv */
948    int i = 0;                  /* Scratch (used only in fail:)  */
949
950    if ( doc && !(root = xmlDocGetRootElement(doc)) ) 
951        goto fail;
952
953    /* Get the issuer keyid */
954    if ( !get_keyid_from_keyinfo(doc, keyid)) 
955        goto fail;
956    sha1_to_text(keyid, text_keyid);
957    /* get the various nodes of interest */
958    if ( !(node = xmlSecFindNode(root, (xmlChar *) GENI_credential, NULL)))
959        goto fail;
960    if ( !(expires = get_direct_child(node, (xmlChar *) GENI_expires)))
961        goto fail;
962    if ( !check_GENI_expires(get_element_content(expires), NULL))
963        goto fail;
964
965    if ( !(rt0 = get_direct_child(node, (xmlChar *) GENI_rt0))) 
966        goto fail;
967    /* There are two places to look for a version.  The credential node and the
968     * rt0 node that is a child of the credential node.  The version element is
969     * only under the credential in the misdefined GENI abac v1.0. */
970    if ( !(version = get_direct_child(node, (xmlChar *) GENI_version))) {
971        if ( !(version = get_direct_child(rt0, (xmlChar *) GENI_version))) 
972            goto fail;
973    }
974
975    /* Pick parsing specialization based on the version.  If we can't resolve a
976     * processor, this is an unknown version. */
977    if ( !(proc = get_xml_processing(get_element_content(version))))
978        goto fail;
979
980    /* read the RT0 and return it */
981    if ( !(rv = proc->xml_to_rt0(rt0)) ) goto fail;
982    ncred=1;
983
984    /* extract issuer pem and insert */
985    issuer_ptr=get_issuer(doc);
986    if( issuer_ptr && 
987            abac_verifier_load_id_chars(ctxt_id_certs,issuer_ptr) != 
988            ABAC_CERT_SUCCESS) {
989        goto fail;
990    }
991
992    return rv;
993fail:
994    if ( rv ) {
995        for (i = 0; i < ncred; i++) 
996            if (rv[i]) free(rv[i]);
997        free(rv);
998    }
999    return NULL;
1000}
1001
1002/* Check and parse a GENI credential.  Return the new RT0 rules in a
1003 * NULL-terminated array of strings.  If the signature or parsing fails, return
1004 * NULL. Demultiplexed to parse_privilege or parse_abac to do the parsing and
1005 * uses check_signature to confirm the sig. If ctxt_id_certs is a list of
1006 * identities known to a context.  If it is not NULL and identity certs appear
1007 * (as they do in GENI credentials) add them to that list, which adds them to
1008 * the ABAC context. */
1009char **read_credential(void *ctxt_id_certs, char *infile, 
1010        char **in_xml) {
1011    xmlChar **xml = in_xml;                 /* Cast */
1012    xmlDocPtr doc = xmlParseFile(infile);   /* Parse the document */
1013    xmlNodePtr node = NULL;                 /* XML scratch node */
1014    xmlChar *text = NULL;                   /* Text of the type field */
1015    xmlChar **rv = NULL;                    /* return value from parse_* */
1016
1017    if ( !check_signature(doc) ) 
1018        goto fail;
1019    /* Parse out the type field */
1020    if ( !(node = xmlDocGetRootElement(doc)) ) 
1021        goto fail;
1022    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1023        goto fail;
1024    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1025        goto fail;
1026
1027    if ( !(text = get_element_content(node)) ) 
1028        goto fail;
1029
1030    /* Demux on type */
1031    if ( !strcmp((char *) text, "privilege")) {
1032        rv = parse_privilege(doc, ctxt_id_certs);
1033    } else if ( !strcmp((char *) text, "abac")) {
1034        rv = parse_abac(doc, ctxt_id_certs);
1035    } else { 
1036        goto fail;
1037    }
1038    int len=0;
1039    xmlDocDumpMemoryEnc(doc, xml, &len, "UTF-8");
1040    if(len == 0)
1041       goto fail;
1042
1043fail:
1044    xmlFreeDoc(doc);
1045    return (char **) rv;
1046}
1047
1048
1049/* format for dates in <expires> */
1050char *strftime_fmt = "%FT%TZ";
1051#define EXPIRESLEN 20
1052
1053/* Return a copy of str with > < and & replaced by &gt; &lt; and &amp; for
1054 * embedding in XML.  Caller is responsible for deallocating the return value
1055 * using xmlFree().
1056 */
1057static xmlChar *minimal_xml_escaping(xmlChar *str) {
1058    /* A quickie translation table with the character to escape, the output
1059     * string and the length of the output in it. The table is initialized with
1060     * the three translations we want. */
1061    static struct esc {
1062        xmlChar c;
1063        xmlChar *esc;
1064        int l;
1065    } escapes[] = {
1066        { (xmlChar) '<', (xmlChar *) "&lt;", 4 }, 
1067        { (xmlChar) '>', (xmlChar *) "&gt;", 4},
1068        { (xmlChar) '&', (xmlChar *) "&amp;", 5},
1069        { (xmlChar) '\0', NULL, 0 },
1070    };
1071
1072    xmlChar *rv = NULL;     /* Return value */
1073    xmlChar *p = NULL;      /* Scratch (walking str) */
1074    xmlChar *q = NULL;      /* Scratch (walking rv) */
1075    struct esc *e = NULL;   /* Scratch for walking escapes */
1076    int len = 0;            /* Length of rv */
1077
1078    /* Walk str and calculate how long the escaped version is */
1079    for ( p = str; *p ; p++) {
1080        int foundit = 0;
1081        for ( e = escapes; !foundit && e->c ; e++ ) {
1082            if ( *p == e->c ) {
1083                len += e->l;
1084                foundit = 1;
1085            }
1086        }
1087        if ( !foundit ) len++;
1088    }
1089    /* Allocate the new string */
1090    q = rv = (xmlChar *) xmlMalloc(len+1);
1091    /* copy str to rv, escaping when necessary */
1092    for ( p = str; *p ; p++) {
1093        int foundit = 0;
1094        for ( e = escapes; !foundit && e->c ; e++ ) {
1095            if ( *p == e->c ) {
1096                strncpy((char *) q, (char *) e->esc, e->l);
1097                q += e->l;
1098                foundit = 1;
1099            }
1100        }
1101        if ( !foundit ) *q++ = *p;
1102    }
1103    /* terminate rv */
1104    *q = '\0';
1105    return rv;
1106}
1107
1108xmlChar *encode_rt0_xml_v10(abac_attribute_t *a) {
1109    return minimal_xml_escaping(abac_attribute_role_string(a));
1110}
1111
1112/* Template to create a head element in structured XML for RT0 (v1.1).  All
1113 * heads are a single role element */
1114static char *head_template = 
1115"<head>\n"
1116"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1117"   <role>%s</role>\n"
1118"</head>\n";
1119
1120/* Templates to create a tail in structured XML  based on how many of
1121 * principal, role, and linking role are present. */
1122static char *tail_template[] = {
1123"<tail>\n"
1124"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1125"</tail>\n",
1126"<tail>\n"
1127"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1128"   <role>%s</role>\n"
1129"</tail>\n",
1130"<tail>\n"
1131"   <ABACprincipal><keyid>%s</keyid></ABACprincipal>\n"
1132"   <role>%s</role>\n"
1133"   <linking_role>%s</linking_role>\n"
1134"</tail>\n",
1135};
1136
1137/* Convert the given attribute to the RT0 structured XML representation used by
1138 * version 1.1 credentials.
1139 */
1140xmlChar *encode_rt0_xml_v11(abac_attribute_t *a) {
1141    int htlen = strlen(head_template);      /* head template length */
1142    int ttlen = strlen(tail_template[2]);   /* length of the longest tail
1143                                               template */
1144    /* Size of the string we'll need - start with a head template and string */
1145    int sz = strlen(abac_attribute_get_head(a)) + htlen;
1146    /* Number of tails in the sttribute */
1147    int ntails = abac_attribute_get_ntails(a);
1148    char *princ_role[2];    /* Used to split the head role */
1149    char *copy = abac_xstrdup(abac_attribute_get_head(a)); /* splitting */
1150    int npr = 2;            /* Number of parts in the head role */
1151    char *tmp = NULL;       /* A temporary to build each tail element */
1152    char *rv = NULL;        /* The return value */
1153    int i;                  /* Scratch */
1154
1155    /* Add the tail lengths to the total length (assume all tails will need the
1156     * largest template for slop). */
1157    for ( i = 0 ; i < ntails; i++)
1158        sz += strlen(abac_attribute_get_tail_n(a, i)) + ttlen;
1159
1160    /* Get the rv and scratch string.  Since tmp is as long as the whole
1161     * string, it's big enough for any substring */
1162    if ( !(rv = (char *) xmlMalloc(sz)) ) goto fail;
1163    if ( !(tmp = (char *) xmlMalloc(sz)) ) goto fail;
1164
1165    abac_split(copy, ".", princ_role, &npr);
1166    if ( npr != 2) 
1167        goto fail;
1168
1169    /* Put the head in */
1170    sz -= snprintf(rv, sz, head_template, princ_role[0], princ_role[1]);
1171
1172    for ( i = 0 ; i < ntails; i++) {
1173        /* Make a role for each tail and use those functions to write out the
1174         * structures for the different kinds of role. */
1175        abac_role_t *r = abac_role_from_string(abac_attribute_get_tail_n(a,i));
1176        int ts;
1177
1178        if ( !r )
1179            goto fail;
1180
1181        if ( abac_role_is_principal(r)) {
1182            char *p = minimal_xml_escaping(abac_role_principal(r));
1183
1184            ts = snprintf(tmp, sz, tail_template[0], p);
1185            free(p);
1186        } else if (abac_role_is_role(r)) {
1187            char *p = minimal_xml_escaping(abac_role_principal(r));
1188            char *ro = minimal_xml_escaping(abac_role_role_name(r));
1189
1190            ts = snprintf(tmp, sz, tail_template[1], p, ro);
1191            free(p);
1192            free(ro);
1193        } else if (abac_role_is_linking(r)) {
1194            char *p = minimal_xml_escaping(abac_role_principal(r));
1195            char *ro = minimal_xml_escaping(abac_role_role_name(r));
1196            char *li = minimal_xml_escaping(abac_role_linking_role(r));
1197
1198            ts = snprintf(tmp, sz, tail_template[2], p, ro, li);
1199            free(p);
1200            free(ro);
1201            free(li);
1202        }
1203
1204        free(r);
1205
1206        if ( ts < 0 ) 
1207            goto fail;
1208
1209        strncat(rv, tmp, sz);
1210        sz -= ts;
1211    }
1212    free(tmp);
1213    return (xmlChar *) rv;
1214
1215fail:
1216    if (rv ) free(rv);
1217    if (tmp) free(tmp);
1218    return NULL;
1219}
1220
1221/* Make an new GENI abac credential with the rt0 rule that expires secs from
1222 * now.  cert is the PEM encoded X.509 of the issuer's certificate as a string.
1223 * certlen is the length of cert.  Returns the XML. Caller is responsible for
1224 * freeing it. */
1225char *make_credential(abac_attribute_t *attr, int secs, char *in_cert, 
1226        int in_certlen) {
1227    xmlSecByte *cert = (xmlSecByte *) in_cert; /* Cast of certificate */
1228    xmlSecSize certlen = (xmlSecSize) in_certlen; /* Cast of len */
1229    xmlDocPtr doc = NULL;       /* parsed XML document */
1230    xmlNodePtr root = NULL;     /* Root of the document */
1231    xmlNodePtr signNode = NULL; /* <Signature> element */
1232    xmlSecDSigCtxPtr dsigCtx = NULL;  /* Signing context */
1233    /*xmlChar *rt0_escaped = minimal_xml_escaping(rt0); /* RT0, escaped */
1234    xmlChar *rt0_xml = NULL;    /* attr's RT0 as xml */
1235    xmlChar *rv = NULL;         /* return value */
1236    time_t exp;                 /* expriation time (seconds since epoch) */
1237    struct tm exp_tm;           /* expiration for formatting */
1238    char estr[EXPIRESLEN+1];    /* String with formatted expiration */
1239    char *temp = NULL;          /* populated XML template */
1240    int len = 0;                /* length of the populated template (temp) */
1241
1242    GENI_xml_processing_t *proc = get_xml_processing("1.1");
1243
1244    if ( !proc ) goto fail;
1245    if ( !(rt0_xml = proc->rt0_to_xml(attr))) goto fail;
1246
1247    /* Calculate the length of the populated template and allocate it */
1248    len = strlen((char *) proc->out_template)+EXPIRESLEN+
1249        strlen((char *) rt0_xml)+1;
1250
1251    if ( !(temp = malloc(len)) )
1252        goto fail;
1253
1254    /* format expiration */
1255    time(&exp);
1256    exp += secs;
1257    gmtime_r(&exp, &exp_tm);
1258
1259    if (strftime(estr, EXPIRESLEN+1, strftime_fmt, &exp_tm) == 0 ) 
1260        goto fail;
1261
1262    /* Populate template with  expiration and escaped rt0 */
1263    snprintf(temp, len, proc->out_template, estr, (char *) rt0_xml);
1264
1265    /* parse the populated template */
1266    if ( !(doc = xmlParseMemory(temp, len))) 
1267        goto fail;
1268
1269    if (!(root = xmlDocGetRootElement(doc)) )
1270        goto fail;
1271
1272    /* Find the signature element for the Signing call */
1273    signNode = xmlSecFindNode(root, xmlSecNodeSignature, xmlSecDSigNs);
1274
1275    /* Create the context */
1276    if ( !(dsigCtx = xmlSecDSigCtxCreate(NULL))) 
1277        goto fail;
1278
1279    /* Assign the key (a PEM key) */
1280    if (!(dsigCtx->signKey = xmlSecCryptoAppKeyLoadMemory(cert, certlen,
1281                    xmlSecKeyDataFormatPem, NULL, NULL, NULL)) )
1282        goto fail;
1283
1284    /* Load the certificate */
1285    if ( xmlSecCryptoAppKeyCertLoadMemory(dsigCtx->signKey, cert, certlen,
1286                xmlSecKeyDataFormatPem) < 0)
1287        goto fail;
1288
1289    /* Sign it */
1290    if ( xmlSecDSigCtxSign(dsigCtx, signNode) < 0)
1291        goto fail;
1292
1293    /* Store the signed credential to rv */
1294    xmlDocDumpMemoryEnc(doc, &rv, &len, "UTF-8");
1295fail:
1296    /* clean up */
1297    if (dsigCtx) 
1298        xmlSecDSigCtxDestroy(dsigCtx);
1299    if ( doc) xmlFreeDoc(doc);
1300    if (rt0_xml) xmlFree(rt0_xml);
1301    if ( temp) free(temp);
1302    return (char *) rv;
1303}
1304
1305#define CERTSIZE 4096
1306/* Read a file into a the dynamically allocated array buf.  Whatever was in buf
1307 * is discarded w/o freeing so it should initially be NULL and len 0. On return
1308 * buf contains as much of the contents of filename as possible and len is the
1309 * length of it.  The caller must free() buf. buf is zero terminated.*/
1310static void read_cert(char *filename, char **buf, int *len) {
1311    FILE *cert = NULL;
1312    char *nbuf = NULL;
1313    int cap = CERTSIZE;
1314    int r = 0;
1315
1316    *len = 0; 
1317    if (!(*buf = malloc(CERTSIZE))) return;
1318
1319    if ( !(cert = fopen(filename, "r"))) 
1320        goto fail;
1321
1322    /* Read cert, expanding buf as necessary */
1323    while ( (r = fread(*buf + *len, 1, cap - *len, cert)) != 0) {
1324        *len += r;
1325        if ( *len == cap ) {
1326            if ( !(nbuf = realloc(*buf, cap + CERTSIZE)) ) 
1327                goto fail;
1328            memcpy(nbuf, *buf, cap);
1329            cap += CERTSIZE;
1330            *buf = nbuf;
1331        }
1332    }
1333    /* Extend if we read exactly cap bytes so we can terminate the string */
1334    if ( *len == cap ) {
1335        if ( !(nbuf = realloc(*buf, cap + CERTSIZE)) ) 
1336            goto fail;
1337        memcpy(nbuf, *buf, cap);
1338        cap += CERTSIZE;
1339        *buf = nbuf;
1340    }
1341    (*buf)[*len] = '\0';
1342    return;
1343fail:
1344    if ( *buf) free(*buf);
1345    *buf = NULL;
1346    *len = 0;
1347    return;
1348}
1349
1350
1351/******** helper functions used by libabac **********************/
1352
1353/* Function to disable libXML2's debugging */
1354static void _nullGenericErrorFunc(void* ctxt, const char* msg, ...) { return; }
1355
1356/* Straight off http://www.aleksey.com/xmlsec/api/xmlsec-examples.html .
1357 * Voodoo.  But call it. */
1358int init_xmlsec() {
1359    /* Init xmlsec library */
1360    if(xmlSecInit() < 0) {
1361        fprintf(stderr, "Error: xmlsec initialization failed.\n");
1362        return(-1);
1363    }
1364
1365    /* Check loaded library version */
1366    if(xmlSecCheckVersion() != 1) {
1367        fprintf(stderr,
1368                "Error: loaded xmlsec library version is not compatible.\n");
1369        return(-1);
1370    }
1371
1372    /* Load default crypto engine if we are supporting dynamic
1373     * loading for xmlsec-crypto libraries. Use the crypto library
1374     * name ("openssl", "nss", etc.) to load corresponding
1375     * xmlsec-crypto library.
1376     */
1377#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
1378    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
1379        fprintf(stderr, "Error: unable to load default xmlsec-crypto library. "
1380                "Make sure\n" 
1381                "that you have it installed and check shared libraries path\n"
1382                "(LD_LIBRARY_PATH) envornment variable.\n");
1383        return(-1);     
1384    }
1385#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
1386
1387    /* Init crypto library */
1388    if(xmlSecCryptoAppInit(NULL) < 0) {
1389        fprintf(stderr, "Error: crypto initialization failed.\n");
1390        return(-1);
1391    }
1392
1393    /* Init xmlsec-crypto library */
1394    if(xmlSecCryptoInit() < 0) {
1395        fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
1396        return(-1);
1397    }
1398    /* Turn off the built in debugging */
1399    xmlThrDefSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1400    xmlSetGenericErrorFunc(NULL, _nullGenericErrorFunc);
1401
1402    return 0;
1403}
1404
1405int deinit_xmlsec() {
1406  /* no op for now */
1407    return 0;
1408}
1409
1410
1411/* parse the xml blob and extract keyid */ 
1412char *get_keyid_from_xml(char *xml) {
1413    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1414    xmlChar keyid[SHA_DIGEST_LENGTH];   /* Issuer key SHA1 */
1415    xmlChar text_keyid[2*SHA_DIGEST_LENGTH+1];/* Issuer keyid as text */
1416    char *ret=NULL;
1417
1418    /* Get the issuer keyid */
1419    if ( !get_keyid_from_keyinfo(doc, keyid))
1420        goto fail;
1421    sha1_to_text(keyid, text_keyid);
1422    ret=strdup((char *)text_keyid);
1423fail:
1424    xmlFreeDoc(doc);
1425    return ret;
1426}
1427
1428/* parse xml and get the expected expiration time and returns
1429 * (expiration time-current time)
1430 */
1431long get_validity_from_xml(char *xml) {
1432    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1433    xmlNodePtr node = NULL;                 /* XML scratch node */
1434    xmlNodePtr expires = NULL;  /* XML expires node */
1435    struct tm tv;   /* Parsed expires field */
1436    time_t now;     /* Now in seconds since the epoch */
1437    time_t exp;     /* expires in seconds since the epoch */
1438    long dtime=0;
1439
1440    if ( !(node = xmlDocGetRootElement(doc)) )
1441        goto fail;
1442
1443    if ( !(expires = xmlSecFindNode(node, (xmlChar *) GENI_expires, NULL)))
1444        goto fail;
1445
1446    xmlChar *etime=get_element_content(expires);
1447    time(&now);
1448
1449    strptime((char *) etime, "%FT%TZ", &tv);
1450    exp = timegm(&tv);
1451    dtime=difftime(exp, now);
1452
1453fail:
1454    xmlFreeDoc(doc);
1455    return dtime;
1456}
1457
1458/* parse xml structure and extract the attribute rules */
1459char **get_rt0_from_xml(void *ctxt_id_certs,char *xml) {
1460    xmlDocPtr doc=xmlParseMemory(xml,strlen(xml));
1461    xmlNodePtr node = NULL;                 /* XML scratch node */
1462    xmlChar *text = NULL;                   /* Text of the type field */
1463    xmlChar **rv = NULL;                    /* return value from parse_* */
1464   
1465    if ( !check_signature(doc) )
1466        goto fail;
1467    /* Parse out the type field */
1468    if ( !(node = xmlDocGetRootElement(doc)) )
1469        goto fail;
1470    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_credential, NULL)))
1471        goto fail;
1472    if ( !(node = xmlSecFindNode(node, (xmlChar *) GENI_type, NULL)))
1473        goto fail;
1474
1475    if ( !(text = get_element_content(node)) )
1476        goto fail;
1477
1478    /* Demux on type */
1479    if ( !strcmp((char *) text, "privilege")) {
1480        rv = parse_privilege(doc,ctxt_id_certs);
1481    } else if ( !strcmp((char *) text, "abac")) {
1482        rv = parse_abac(doc, ctxt_id_certs);
1483    } else {
1484        goto fail;
1485    }
1486fail:
1487    xmlFreeDoc(doc);
1488    return (char **)rv;
1489}
1490
1491
Note: See TracBrowser for help on using the repository browser.