More error reporting
[mech_eap.git] / util_radius.cpp
1 /*
2  * Copyright (c) 2010, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include "gssapiP_eap.h"
34
35 /* stuff that should be provided by libradsec/libfreeradius-radius */
36 #define VENDORATTR(vendor, attr)            (((vendor) << 16) | (attr))
37
38 #ifndef ATTRID
39 #define ATTRID(attr)                        ((attr) & 0xFFFF)
40 #endif
41
42 static gss_buffer_desc radiusUrnPrefix = {
43     sizeof("urn:x-radius:") - 1,
44     (void *)"urn:x-radius:"
45 };
46
47 static VALUE_PAIR *copyAvps(const VALUE_PAIR *src);
48
49 gss_eap_radius_attr_provider::gss_eap_radius_attr_provider(void)
50 {
51     m_vps = NULL;
52     m_authenticated = false;
53 }
54
55 gss_eap_radius_attr_provider::~gss_eap_radius_attr_provider(void)
56 {
57     if (m_vps != NULL)
58         pairfree(&m_vps);
59 }
60
61 bool
62 gss_eap_radius_attr_provider::initFromExistingContext(const gss_eap_attr_ctx *manager,
63                                                       const gss_eap_attr_provider *ctx)
64 {
65     const gss_eap_radius_attr_provider *radius;
66
67     if (!gss_eap_attr_provider::initFromExistingContext(manager, ctx))
68         return false;
69
70     radius = static_cast<const gss_eap_radius_attr_provider *>(ctx);
71
72     if (radius->m_vps != NULL)
73         m_vps = copyAvps(const_cast<VALUE_PAIR *>(radius->getAvps()));
74
75     m_authenticated = radius->m_authenticated;
76
77     return true;
78 }
79
80 bool
81 gss_eap_radius_attr_provider::initFromGssContext(const gss_eap_attr_ctx *manager,
82                                                  const gss_cred_id_t gssCred,
83                                                  const gss_ctx_id_t gssCtx)
84 {
85     if (!gss_eap_attr_provider::initFromGssContext(manager, gssCred, gssCtx))
86         return false;
87
88     if (gssCtx != GSS_C_NO_CONTEXT) {
89         if (gssCtx->acceptorCtx.vps != NULL) {
90             m_vps = copyAvps(gssCtx->acceptorCtx.vps);
91             if (m_vps == NULL)
92                 return false;
93
94             /* We assume libradsec validated this for us */
95             assert(pairfind(m_vps, PW_MESSAGE_AUTHENTICATOR) != NULL);
96             m_authenticated = true;
97         }
98     }
99
100     return true;
101 }
102
103 static bool
104 alreadyAddedAttributeP(std::vector <std::string> &attrs, VALUE_PAIR *vp)
105 {
106     for (std::vector<std::string>::const_iterator a = attrs.begin();
107          a != attrs.end();
108          ++a) {
109         if (strcmp(vp->name, (*a).c_str()) == 0)
110             return true;
111     }
112
113     return false;
114 }
115
116 static bool
117 isSecretAttributeP(uint16_t attrid, uint16_t vendor)
118 {
119     bool ret = false;
120
121     switch (vendor) {
122     case VENDORPEC_MS:
123         switch (attrid) {
124         case PW_MS_MPPE_SEND_KEY:
125         case PW_MS_MPPE_RECV_KEY:
126             ret = true;
127             break;
128         default:
129             break;
130         }
131     default:
132         break;
133     }
134
135     return ret;
136 }
137
138 static bool
139 isSecretAttributeP(uint32_t attribute)
140 {
141     return isSecretAttributeP(ATTRID(attribute), VENDOR(attribute));
142 }
143
144 static bool
145 isHiddenAttributeP(uint16_t attrid, uint16_t vendor)
146 {
147     bool ret = false;
148
149     /* should have been filtered */
150     assert(!isSecretAttributeP(attrid, vendor));
151
152     switch (vendor) {
153     case VENDORPEC_UKERNA:
154         ret = true;
155         break;
156     default:
157         break;
158     }
159
160     return ret;
161 }
162
163 static bool
164 isHiddenAttributeP(uint32_t attribute)
165 {
166     return isHiddenAttributeP(ATTRID(attribute), VENDOR(attribute));
167 }
168
169 /*
170  * Copy AVP list, same as paircopy except it filters out attributes
171  * containing keys.
172  */
173 static VALUE_PAIR *
174 copyAvps(const VALUE_PAIR *src)
175 {
176     const VALUE_PAIR *vp;
177     VALUE_PAIR *dst = NULL, **pDst = &dst;
178
179     for (vp = src; vp != NULL; vp = vp->next) {
180         VALUE_PAIR *vpcopy;
181
182         if (isSecretAttributeP(vp->attribute))
183             continue;
184
185         vpcopy = paircopyvp(vp);
186         if (vpcopy == NULL) {
187             pairfree(&dst);
188             throw new std::bad_alloc;
189             return NULL;
190         }
191         *pDst = vpcopy;
192         pDst = &vpcopy->next;
193      }
194
195     return dst;
196 }
197
198 bool
199 gss_eap_radius_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute, void *data) const
200 {
201     VALUE_PAIR *vp;
202     std::vector <std::string> seen;
203
204     for (vp = m_vps; vp != NULL; vp = vp->next) {
205         gss_buffer_desc attribute;
206         char attrid[64];
207
208         if (isHiddenAttributeP(vp->attribute))
209             continue;
210
211         if (alreadyAddedAttributeP(seen, vp))
212             continue;
213
214         snprintf(attrid, sizeof(attrid), "%s%d",
215             (char *)radiusUrnPrefix.value, vp->attribute);
216
217         attribute.value = attrid;
218         attribute.length = strlen(attrid);
219
220         if (!addAttribute(this, &attribute, data))
221             return false;
222
223         seen.push_back(std::string(vp->name));
224     }
225
226     return true;
227 }
228
229 uint32_t
230 getAttributeId(const gss_buffer_t attr)
231 {
232     OM_uint32 tmpMinor;
233     gss_buffer_desc strAttr = GSS_C_EMPTY_BUFFER;
234     DICT_ATTR *da;
235     char *s;
236     uint32_t attrid = 0;
237
238     if (attr->length < radiusUrnPrefix.length ||
239         memcmp(attr->value, radiusUrnPrefix.value, radiusUrnPrefix.length) != 0)
240         return 0;
241
242     /* need to duplicate because attr may not be NUL terminated */
243     duplicateBuffer(*attr, &strAttr);
244     s = (char *)strAttr.value + radiusUrnPrefix.length;
245
246     if (isdigit(*s)) {
247         attrid = strtoul(s, NULL, 10);
248     } else {
249         da = dict_attrbyname(s);
250         if (da != NULL)
251             attrid = da->attr;
252     }
253
254     gss_release_buffer(&tmpMinor, &strAttr);
255
256     return attrid;
257 }
258
259 bool
260 gss_eap_radius_attr_provider::setAttribute(int complete,
261                                            uint32_t attrid,
262                                            const gss_buffer_t value)
263 {
264     OM_uint32 major = GSS_S_UNAVAILABLE, minor;
265
266     if (!isSecretAttributeP(attrid) &&
267         !isHiddenAttributeP(attrid)) {
268         deleteAttribute(attrid);
269
270         major = gssEapRadiusAddAvp(&minor, &m_vps,
271                                    ATTRID(attrid), VENDOR(attrid), 
272                                    value);
273     }
274
275     return !GSS_ERROR(major);
276 }
277
278 bool
279 gss_eap_radius_attr_provider::setAttribute(int complete,
280                                            const gss_buffer_t attr,
281                                            const gss_buffer_t value)
282 {
283     uint32_t attrid = getAttributeId(attr);
284
285     if (!attrid)
286         return false;
287
288     return setAttribute(complete, attrid, value);
289 }
290
291 bool
292 gss_eap_radius_attr_provider::deleteAttribute(uint32_t attrid)
293 {
294     if (isSecretAttributeP(attrid) || isHiddenAttributeP(attrid) ||
295         pairfind(m_vps, attrid) == NULL)
296         return false;
297
298     pairdelete(&m_vps, attrid);
299
300     return true;
301 }
302
303 bool
304 gss_eap_radius_attr_provider::deleteAttribute(const gss_buffer_t attr)
305 {
306     uint32_t attrid = getAttributeId(attr);
307
308     if (!attrid)
309         return false;
310
311     return deleteAttribute(attrid);
312 }
313
314 bool
315 gss_eap_radius_attr_provider::getAttribute(const gss_buffer_t attr,
316                                            int *authenticated,
317                                            int *complete,
318                                            gss_buffer_t value,
319                                            gss_buffer_t display_value,
320                                            int *more) const
321 {
322     uint32_t attrid;
323
324     attrid = getAttributeId(attr);
325     if (!attrid)
326         return false;
327
328     return getAttribute(attrid, authenticated, complete,
329                         value, display_value, more);
330 }
331
332 bool
333 gss_eap_radius_attr_provider::getAttribute(uint32_t attrid,
334                                            int *authenticated,
335                                            int *complete,
336                                            gss_buffer_t value,
337                                            gss_buffer_t display_value,
338                                            int *more) const
339 {
340     VALUE_PAIR *vp;
341     int i = *more, count = 0;
342
343     *more = 0;
344
345     if (isHiddenAttributeP(attrid))
346         return false;
347
348     if (i == -1)
349         i = 0;
350
351     for (vp = pairfind(m_vps, attrid);
352          vp != NULL;
353          vp = pairfind(vp->next, attrid)) {
354         if (count++ == i) {
355             if (pairfind(vp->next, attrid) != NULL)
356                 *more = count;
357             break;
358         }
359     }
360
361     if (vp == NULL && *more == 0)
362         return false;
363
364     if (value != GSS_C_NO_BUFFER) {
365         gss_buffer_desc valueBuf;
366
367         valueBuf.value = (void *)vp->vp_octets;
368         valueBuf.length = vp->length;
369
370         duplicateBuffer(valueBuf, value);
371     }
372
373     if (display_value != GSS_C_NO_BUFFER) {
374         char displayString[MAX_STRING_LEN];
375         gss_buffer_desc displayBuf;
376
377         displayBuf.length = vp_prints_value(displayString,
378                                             sizeof(displayString), vp, 0);
379         displayBuf.value = (void *)displayString;
380
381         duplicateBuffer(displayBuf, display_value);
382     }
383
384     if (authenticated != NULL)
385         *authenticated = m_authenticated;
386     if (complete != NULL)
387         *complete = true;
388
389     return true;
390 }
391
392 bool
393 gss_eap_radius_attr_provider::getFragmentedAttribute(uint16_t attribute,
394                                                      uint16_t vendor,
395                                                      int *authenticated,
396                                                      int *complete,
397                                                      gss_buffer_t value) const
398 {
399     OM_uint32 major, minor;
400
401     major = gssEapRadiusGetAvp(&minor, m_vps, attribute, vendor, value, TRUE);
402
403     if (authenticated != NULL)
404         *authenticated = m_authenticated;
405     if (complete != NULL)
406         *complete = true;
407
408     return !GSS_ERROR(major);
409 }
410
411 bool
412 gss_eap_radius_attr_provider::getAttribute(uint16_t attribute,
413                                            uint16_t vendor,
414                                            int *authenticated,
415                                            int *complete,
416                                            gss_buffer_t value,
417                                            gss_buffer_t display_value,
418                                            int *more) const
419 {
420
421     return getAttribute(VENDORATTR(attribute, vendor),
422                         authenticated, complete,
423                         value, display_value, more);
424 }
425
426 gss_any_t
427 gss_eap_radius_attr_provider::mapToAny(int authenticated,
428                                        gss_buffer_t type_id) const
429 {
430     if (authenticated && !m_authenticated)
431         return (gss_any_t)NULL;
432
433     return (gss_any_t)copyAvps(m_vps);
434 }
435
436 void
437 gss_eap_radius_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id,
438                                                     gss_any_t input) const
439 {
440     pairfree((VALUE_PAIR **)&input);
441 }
442
443 bool
444 gss_eap_radius_attr_provider::init(void)
445 {
446     gss_eap_attr_ctx::registerProvider(ATTR_TYPE_RADIUS,
447                                        "urn:ietf:params:gss-eap:radius-avp",
448                                        gss_eap_radius_attr_provider::createAttrContext);
449     return true;
450 }
451
452 void
453 gss_eap_radius_attr_provider::finalize(void)
454 {
455     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_RADIUS);
456 }
457
458 gss_eap_attr_provider *
459 gss_eap_radius_attr_provider::createAttrContext(void)
460 {
461     return new gss_eap_radius_attr_provider;
462 }
463
464 OM_uint32
465 gssEapRadiusAddAvp(OM_uint32 *minor,
466                    VALUE_PAIR **vps,
467                    uint16_t attribute,
468                    uint16_t vendor,
469                    const gss_buffer_t buffer)
470 {
471     uint32_t attrid = VENDORATTR(vendor, attribute);
472     unsigned char *p = (unsigned char *)buffer->value;
473     size_t remain = buffer->length;
474
475     do {
476         VALUE_PAIR *vp;
477         size_t n = remain;
478
479         if (n > MAX_STRING_LEN)
480             n = MAX_STRING_LEN;
481
482         vp = paircreate(attrid, PW_TYPE_OCTETS);
483         if (vp == NULL) {
484             *minor = ENOMEM;
485             return GSS_S_FAILURE;
486         }
487
488         memcpy(vp->vp_octets, p, n);
489         vp->length = n;
490
491         pairadd(vps, vp);
492
493         p += n;
494         remain -= n;
495     } while (remain != 0);
496
497     return GSS_S_COMPLETE;
498 }
499
500 OM_uint32
501 gssEapRadiusGetRawAvp(OM_uint32 *minor,
502                       VALUE_PAIR *vps,
503                       uint16_t attribute,
504                       uint16_t vendor,
505                       VALUE_PAIR **vp)
506 {
507     uint32_t attr = VENDORATTR(vendor, attribute);
508
509     *vp = pairfind(vps, attr);
510     if (*vp == NULL) {
511         *minor = GSSEAP_NO_SUCH_ATTR;
512         return GSS_S_UNAVAILABLE;
513     }
514
515     return GSS_S_COMPLETE;
516 }
517
518 OM_uint32
519 gssEapRadiusGetAvp(OM_uint32 *minor,
520                    VALUE_PAIR *vps,
521                    uint16_t attribute,
522                    uint16_t vendor,
523                    gss_buffer_t buffer,
524                    int concat)
525 {
526     VALUE_PAIR *vp;
527     unsigned char *p;
528     uint32_t attr = VENDORATTR(vendor, attribute);
529
530     buffer->length = 0;
531     buffer->value = NULL;
532
533     vp = pairfind(vps, attr);
534     if (vp == NULL) {
535         *minor = GSSEAP_NO_SUCH_ATTR;
536         return GSS_S_UNAVAILABLE;
537     }
538
539     do {
540         buffer->length += vp->length;
541     } while (concat && (vp = pairfind(vp->next, attr)) != NULL);
542
543     buffer->value = GSSEAP_MALLOC(buffer->length);
544     if (buffer->value == NULL) {
545         *minor = ENOMEM;
546         return GSS_S_FAILURE;
547     }
548
549     p = (unsigned char *)buffer->value;
550
551     for (vp = pairfind(vps, attr);
552          concat && vp != NULL;
553          vp = pairfind(vp->next, attr)) {
554         memcpy(p, vp->vp_octets, vp->length);
555         p += vp->length;
556     }
557
558     *minor = 0;
559     return GSS_S_COMPLETE;
560 }
561
562 OM_uint32
563 gssEapRadiusFreeAvps(OM_uint32 *minor,
564                      VALUE_PAIR **vps)
565 {
566     pairfree(vps);
567     *minor = 0;
568     return GSS_S_COMPLETE;
569 }
570
571 OM_uint32
572 gssEapRadiusAttrProviderInit(OM_uint32 *minor)
573 {
574     if (!gss_eap_radius_attr_provider::init()) {
575         *minor = GSSEAP_RADSEC_INIT_FAILURE;
576         return GSS_S_FAILURE;
577     }
578
579     return GSS_S_COMPLETE;
580 }
581
582 OM_uint32
583 gssEapRadiusAttrProviderFinalize(OM_uint32 *minor)
584 {
585     gss_eap_radius_attr_provider::finalize();
586     return GSS_S_COMPLETE;
587 }
588
589 /*
590  * Encoding is:
591  * 4 octet NBO attribute ID | 4 octet attribute length | attribute data
592  */
593 static size_t
594 avpSize(const VALUE_PAIR *vp)
595 {
596     size_t size = 4 + 1;
597
598     if (vp != NULL)
599         size += vp->length;
600
601     return size;
602 }
603
604 static bool
605 avpExport(const VALUE_PAIR *vp,
606           unsigned char **pBuffer,
607           size_t *pRemain)
608 {
609     unsigned char *p = *pBuffer;
610     size_t remain = *pRemain;
611
612     assert(remain >= avpSize(vp));
613
614     store_uint32_be(vp->attribute, p);
615
616     switch (vp->type) {
617     case PW_TYPE_INTEGER:
618     case PW_TYPE_IPADDR:
619     case PW_TYPE_DATE:
620         p[4] = 4;
621         store_uint32_be(vp->lvalue, p + 5);
622         break;
623     default:
624         assert(vp->length <= MAX_STRING_LEN);
625         p[4] = (uint8_t)vp->length;
626         memcpy(p + 5, vp->vp_octets, vp->length);
627         break;
628     }
629
630     *pBuffer += 5 + p[4];
631     *pRemain -= 5 + p[4];
632
633     return true;
634
635 }
636
637 static bool
638 avpImport(VALUE_PAIR **pVp,
639           unsigned char **pBuffer,
640           size_t *pRemain)
641 {
642     unsigned char *p = *pBuffer;
643     size_t remain = *pRemain;
644     VALUE_PAIR *vp = NULL;
645     DICT_ATTR *da;
646     uint32_t attrid;
647
648     if (remain < avpSize(NULL))
649         goto fail;
650
651     attrid = load_uint32_be(p);
652     p += 4;
653     remain -= 4;
654
655     da = dict_attrbyvalue(attrid);
656     if (da == NULL)
657         goto fail;
658
659     vp = pairalloc(da);
660     if (vp == NULL) {
661         throw new std::bad_alloc;
662         goto fail;
663     }
664
665     if (remain < p[0])
666         goto fail;
667
668     switch (vp->type) {
669     case PW_TYPE_INTEGER:
670     case PW_TYPE_IPADDR:
671     case PW_TYPE_DATE:
672         if (p[0] != 4)
673             goto fail;
674
675         vp->length = 4;
676         vp->lvalue = load_uint32_be(p + 1);
677         p += 5;
678         remain -= 5;
679         break;
680     case PW_TYPE_STRING:
681         /* check enough room to NUL terminate */
682         if (p[0] == MAX_STRING_LEN)
683             goto fail;
684         else
685         /* fallthrough */
686     default:
687         if (p[0] > MAX_STRING_LEN)
688             goto fail;
689
690         vp->length = (uint32_t)p[0];
691         memcpy(vp->vp_octets, p + 1, vp->length);
692
693         if (vp->type == PW_TYPE_STRING)
694             vp->vp_strvalue[vp->length] = '\0';
695
696         p += 1 + vp->length;
697         remain -= 1 + vp->length;
698         break;
699     }
700
701     *pVp = vp;
702     *pBuffer = p;
703     *pRemain = remain;
704
705     return true;
706
707 fail:
708     pairbasicfree(vp);
709     return false;
710 }
711
712 bool
713 gss_eap_radius_attr_provider::initFromBuffer(const gss_eap_attr_ctx *ctx,
714                                              const gss_buffer_t buffer)
715 {
716     unsigned char *p = (unsigned char *)buffer->value;
717     size_t remain = buffer->length;
718     VALUE_PAIR **pNext = &m_vps;
719
720     if (!gss_eap_attr_provider::initFromBuffer(ctx, buffer))
721         return false;
722
723     do {
724         VALUE_PAIR *attr;
725
726         if (!avpImport(&attr, &p, &remain))
727             return false;
728
729         *pNext = attr;
730         pNext = &attr->next;
731     } while (remain != 0);
732
733     return true;
734 }
735
736 void
737 gss_eap_radius_attr_provider::exportToBuffer(gss_buffer_t buffer) const
738 {
739     VALUE_PAIR *vp;
740     unsigned char *p;
741     size_t remain = 0;
742
743     for (vp = m_vps; vp != NULL; vp = vp->next) {
744         remain += avpSize(vp);
745     }
746
747     buffer->value = GSSEAP_MALLOC(remain);
748     if (buffer->value == NULL) {
749         throw new std::bad_alloc;
750         return;
751     }
752     buffer->length = remain;
753
754     p = (unsigned char *)buffer->value;
755
756     for (vp = m_vps; vp != NULL; vp = vp->next) {
757         avpExport(vp, &p, &remain);
758     }
759
760     assert(remain == 0);
761 }
762
763 time_t
764 gss_eap_radius_attr_provider::getExpiryTime(void) const
765 {
766     VALUE_PAIR *vp;
767
768     vp = pairfind(m_vps, PW_SESSION_TIMEOUT);
769     if (vp == NULL || vp->lvalue == 0)
770         return 0;
771
772     return time(NULL) + vp->lvalue;
773 }
774
775 OM_uint32
776 gssEapRadiusMapError(OM_uint32 *minor,
777                      struct rs_error *err)
778 {
779     int code;
780
781     assert(err != NULL);
782
783     code = rs_err_code(err, 0);
784
785     if (code == RSE_OK) {
786         *minor = 0;
787         return GSS_S_COMPLETE;
788     }
789
790     *minor = ERROR_TABLE_BASE_rse + code;
791
792     gssEapSaveStatusInfo(*minor, "%s", rs_err_msg(err, 0));
793     rs_err_free(err);
794
795     return GSS_S_FAILURE;
796 }