Test of branch
[citadel.git] / citadel / modules / openid / serv_openid_rp.c
1 /*
2  * This is an implementation of OpenID 2.0 RELYING PARTY SUPPORT CURRENTLY B0RKEN AND BEING DEVEL0PZ0RED
3
4
5                         OPENID2 BRANCH
6
7  *
8  * Copyright (c) 2007-2011 by the citadel.org team
9  *
10  * This program is open source software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include "sysdep.h"
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <sys/types.h>
33
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <sys/wait.h>
46 #include <string.h>
47 #include <limits.h>
48 #include <curl/curl.h>
49 #include <expat.h>
50 #include "ctdl_module.h"
51 #include "config.h"
52 #include "citserver.h"
53 #include "user_ops.h"
54
55 typedef struct _ctdl_openid {
56         StrBuf *claimed_id;
57         StrBuf *server;
58         int verified;
59         HashList *sreg_keys;
60 } ctdl_openid;
61
62 void Free_ctdl_openid(ctdl_openid **FreeMe)
63 {
64         if (*FreeMe == NULL)
65                 return;
66         FreeStrBuf(&(*FreeMe)->claimed_id);
67         FreeStrBuf(&(*FreeMe)->server);
68         DeleteHash(&(*FreeMe)->sreg_keys);
69         free(*FreeMe);
70         *FreeMe = NULL;
71 }
72
73
74 /*
75  * This cleanup function blows away the temporary memory used by this module.
76  */
77 void openid_cleanup_function(void) {
78         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
79
80         if (CCC->openid_data != NULL) {
81                 syslog(LOG_DEBUG, "Clearing OpenID session state");
82                 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
83         }
84 }
85
86
87 /**************************************************************************/
88 /*                                                                        */
89 /* Functions in this section handle Citadel internal OpenID mapping stuff */
90 /*                                                                        */
91 /**************************************************************************/
92
93
94 /*
95  * The structure of an openid record *key* is:
96  *
97  * |--------------claimed_id-------------|
98  *     (actual length of claimed id)
99  *
100  *
101  * The structure of an openid record *value* is:
102  *
103  * |-----user_number----|------------claimed_id---------------|
104  *    (sizeof long)          (actual length of claimed id)
105  *
106  */
107
108
109
110 /*
111  * Attach an OpenID to a Citadel account
112  */
113 int attach_openid(struct ctdluser *who, StrBuf *claimed_id)
114 {
115         struct cdbdata *cdboi;
116         long fetched_usernum;
117         char *data;
118         int data_len;
119         char buf[2048];
120
121         if (!who) return(1);
122         if (StrLength(claimed_id)==0) return(1);
123
124         /* Check to see if this OpenID is already in the database */
125
126         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
127         if (cdboi != NULL) {
128                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
129                 cdb_free(cdboi);
130
131                 if (fetched_usernum == who->usernum) {
132                         syslog(LOG_INFO, "%s already associated; no action is taken", ChrPtr(claimed_id));
133                         return(0);
134                 }
135                 else {
136                         syslog(LOG_INFO, "%s already belongs to another user", ChrPtr(claimed_id));
137                         return(3);
138                 }
139         }
140
141         /* Not already in the database, so attach it now */
142
143         data_len = sizeof(long) + StrLength(claimed_id) + 1;
144         data = malloc(data_len);
145
146         memcpy(data, &who->usernum, sizeof(long));
147         memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
148
149         cdb_store(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
150         free(data);
151
152         snprintf(buf, sizeof buf, "User <%s> (#%ld) has claimed the OpenID URL %s\n",
153                  who->fullname, who->usernum, ChrPtr(claimed_id));
154         CtdlAideMessage(buf, "OpenID claim");
155         syslog(LOG_INFO, "%s", buf);
156         return(0);
157 }
158
159
160
161 /*
162  * When a user is being deleted, we have to delete any OpenID associations
163  */
164 void openid_purge(struct ctdluser *usbuf) {
165         struct cdbdata *cdboi;
166         HashList *keys = NULL;
167         HashPos *HashPos;
168         char *deleteme = NULL;
169         long len;
170         void *Value;
171         const char *Key;
172         long usernum = 0L;
173
174         keys = NewHash(1, NULL);
175         if (!keys) return;
176
177         cdb_rewind(CDB_OPENID);
178         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
179                 if (cdboi->len > sizeof(long)) {
180                         memcpy(&usernum, cdboi->ptr, sizeof(long));
181                         if (usernum == usbuf->usernum) {
182                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
183                                 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
184                         }
185                 }
186                 cdb_free(cdboi);
187         }
188
189         /* Go through the hash list, deleting keys we stored in it */
190
191         HashPos = GetNewHashPos(keys, 0);
192         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
193         {
194                 syslog(LOG_DEBUG, "Deleting associated OpenID <%s>", (char*)Value);
195                 cdb_delete(CDB_OPENID, Value, strlen(Value));
196                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
197         }
198         DeleteHashPos(&HashPos);
199         DeleteHash(&keys);
200 }
201
202
203 /*
204  * List the OpenIDs associated with the currently logged in account
205  */
206 void cmd_oidl(char *argbuf) {
207         struct cdbdata *cdboi;
208         long usernum = 0L;
209
210         if (CtdlAccessCheck(ac_logged_in)) return;
211         cdb_rewind(CDB_OPENID);
212         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
213
214         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
215                 if (cdboi->len > sizeof(long)) {
216                         memcpy(&usernum, cdboi->ptr, sizeof(long));
217                         if (usernum == CC->user.usernum) {
218                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
219                         }
220                 }
221                 cdb_free(cdboi);
222         }
223         cprintf("000\n");
224 }
225
226
227 /*
228  * List ALL OpenIDs in the database
229  */
230 void cmd_oida(char *argbuf) {
231         struct cdbdata *cdboi;
232         long usernum;
233         struct ctdluser usbuf;
234
235         if (CtdlAccessCheck(ac_aide)) return;
236         cdb_rewind(CDB_OPENID);
237         cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
238
239         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
240                 if (cdboi->len > sizeof(long)) {
241                         memcpy(&usernum, cdboi->ptr, sizeof(long));
242                         if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
243                                 usbuf.fullname[0] = 0;
244                         } 
245                         cprintf("%s|%ld|%s\n",
246                                 cdboi->ptr + sizeof(long),
247                                 usernum,
248                                 usbuf.fullname
249                         );
250                 }
251                 cdb_free(cdboi);
252         }
253         cprintf("000\n");
254 }
255
256
257 /*
258  * Attempt to register (populate the vCard) the currently-logged-in user
259  * using the data from Simple Registration Extension, if present.
260  */
261 void populate_vcard_from_sreg(HashList *sreg_keys) {
262
263         struct vCard *v;
264         int pop = 0;                    /* number of fields populated */
265         char *data = NULL;
266         char *postcode = NULL;
267         char *country = NULL;
268
269         if (!sreg_keys) return;
270         v = vcard_new();
271         if (!v) return;
272
273         if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
274                 vcard_add_prop(v, "url;type=openid", data);
275                 ++pop;
276         }
277
278         if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
279                 vcard_add_prop(v, "email;internet", data);
280                 ++pop;
281         }
282
283         if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
284                 vcard_add_prop(v, "nickname", data);
285                 ++pop;
286         }
287
288         if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
289                 char n[256];
290                 vcard_add_prop(v, "fn", data);
291                 vcard_fn_to_n(n, data, sizeof n);
292                 vcard_add_prop(v, "n", n);
293                 ++pop;
294         }
295
296         if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
297                 postcode = NULL;
298         }
299
300         if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
301                 country = NULL;
302         }
303
304         if (postcode || country) {
305                 char adr[256];
306                 snprintf(adr, sizeof adr, ";;;;;%s;%s",
307                         (postcode ? postcode : ""),
308                         (country ? country : "")
309                 );
310                 vcard_add_prop(v, "adr", adr);
311                 ++pop;
312         }
313
314         if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
315                 vcard_add_prop(v, "bday", data);
316                 ++pop;
317         }
318
319         if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
320                 vcard_add_prop(v, "x-funambol-gender", data);
321                 ++pop;
322         }
323
324         /* Only save the vCard if there is some useful data in it */
325         if (pop > 0) {
326                 char *ser;
327                 ser = vcard_serialize(v);
328                 if (ser) {
329                         CtdlWriteObject(USERCONFIGROOM, "text/x-vcard",
330                                 ser, strlen(ser)+1, &CC->user, 0, 0, 0
331                         );
332                         free(ser);
333                 }
334         }
335         vcard_free(v);
336 }
337
338
339 /*
340  * Create a new user account, manually specifying the name, after successfully
341  * verifying an OpenID (which will of course be attached to the account)
342  */
343 void cmd_oidc(char *argbuf) {
344         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
345
346         if (!oiddata) {
347                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
348                 return;
349         }
350
351         if (!oiddata->verified) {
352                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
353                 return;
354         }
355
356         /* We can make the semantics of OIDC exactly the same as NEWU, simply
357          * by _calling_ cmd_newu() and letting it run.  Very clever!
358          */
359         cmd_newu(argbuf);
360
361         /* Now, if this logged us in, we have to attach the OpenID */
362         if (CC->logged_in) {
363                 attach_openid(&CC->user, oiddata->claimed_id);
364                 if (oiddata->sreg_keys != NULL) {
365                         populate_vcard_from_sreg(oiddata->sreg_keys);
366                 }
367         }
368
369 }
370
371
372 /*
373  * Detach an OpenID from the currently logged in account
374  */
375 void cmd_oidd(char *argbuf) {
376         struct cdbdata *cdboi;
377         char id_to_detach[1024];
378         int this_is_mine = 0;
379         long usernum = 0L;
380
381         if (CtdlAccessCheck(ac_logged_in)) return;
382         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
383         if (IsEmptyStr(id_to_detach)) {
384                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
385         }
386
387         cdb_rewind(CDB_OPENID);
388         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
389                 if (cdboi->len > sizeof(long)) {
390                         memcpy(&usernum, cdboi->ptr, sizeof(long));
391                         if (usernum == CC->user.usernum) {
392                                 this_is_mine = 1;
393                         }
394                 }
395                 cdb_free(cdboi);
396         }
397
398         if (!this_is_mine) {
399                 cprintf("%d That OpenID was not found or not associated with your account.\n",
400                         ERROR + ILLEGAL_VALUE);
401                 return;
402         }
403
404         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
405         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
406 }
407
408
409
410 /*
411  * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
412  */
413 int openid_create_user_via_sreg(StrBuf *claimed_id, HashList *sreg_keys)
414 {
415         char *desired_name = NULL;
416         char new_password[32];
417         long len;
418
419         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
420         if (config.c_disable_newu) return(2);
421         if (CC->logged_in) return(3);
422         if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
423
424         syslog(LOG_DEBUG, "The desired account name is <%s>", desired_name);
425
426         len = cutuserkey(desired_name);
427         if (!CtdlGetUser(&CC->user, desired_name)) {
428                 syslog(LOG_DEBUG, "<%s> is already taken by another user.", desired_name);
429                 memset(&CC->user, 0, sizeof(struct ctdluser));
430                 return(5);
431         }
432
433         /* The desired account name is available.  Create the account and log it in! */
434         if (create_user(desired_name, len, 1)) return(6);
435
436         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
437         CtdlSetPassword(new_password);
438         attach_openid(&CC->user, claimed_id);
439         populate_vcard_from_sreg(sreg_keys);
440         return(0);
441 }
442
443
444 /*
445  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
446  * Otherwise it returns nonzero.
447  */
448 int login_via_openid(StrBuf *claimed_id)
449 {
450         struct cdbdata *cdboi;
451         long usernum = 0;
452
453         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
454         if (cdboi == NULL) {
455                 return(-1);
456         }
457
458         memcpy(&usernum, cdboi->ptr, sizeof(long));
459         cdb_free(cdboi);
460
461         if (!CtdlGetUserByNumber(&CC->user, usernum)) {
462                 /* Now become the user we just created */
463                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
464                 do_login();
465                 return(0);
466         }
467         else {
468                 memset(&CC->user, 0, sizeof(struct ctdluser));
469                 return(-1);
470         }
471 }
472
473
474
475
476 /**************************************************************************/
477 /*                                                                        */
478 /* Functions in this section handle OpenID protocol                       */
479 /*                                                                        */
480 /**************************************************************************/
481
482
483 /* 
484  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
485  */
486 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
487 {
488         int i;
489         const char *ptr;
490         const char *href_start = NULL;
491         const char *href_end = NULL;
492         const char *link_tag_start = NULL;
493         const char *link_tag_end = NULL;
494         const char *rel_start = NULL;
495         const char *rel_end = NULL;
496
497         if (!target_buf) return;
498         if (!rel) return;
499         if (!source_buf) return;
500
501         ptr = ChrPtr(source_buf);
502
503         FlushStrBuf(target_buf);
504         while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
505
506                 link_tag_start = ptr;
507                 link_tag_end = strchr(ptr, '>');
508                 if (link_tag_end == NULL)
509                         break;
510                 for (i=0; i < 1; i++ ){
511                         rel_start = cbmstrcasestr(link_tag_start, "rel=");
512                         if ((rel_start == NULL) ||
513                             (rel_start > link_tag_end)) 
514                                 continue;
515
516                         rel_start = strchr(rel_start, '\"');
517                         if ((rel_start == NULL) ||
518                             (rel_start > link_tag_end)) 
519                                 continue;
520                         ++rel_start;
521                         rel_end = strchr(rel_start, '\"');
522                         if ((rel_end == NULL) ||
523                             (rel_end == rel_start) ||
524                             (rel_end >= link_tag_end) ) 
525                                 continue;
526                         if (strncasecmp(rel, rel_start, repllen)!= 0)
527                                 continue; /* didn't match? never mind... */
528                         
529                         href_start = cbmstrcasestr(link_tag_start, "href=");
530                         if ((href_start == NULL) || 
531                             (href_start >= link_tag_end)) 
532                                 continue;
533                         href_start = strchr(href_start, '\"');
534                         if ((href_start == NULL) |
535                             (href_start >= link_tag_end)) 
536                                 continue;
537                         ++href_start;
538                         href_end = strchr(href_start, '\"');
539                         if ((href_end == NULL) || 
540                             (href_end == href_start) ||
541                             (href_start >= link_tag_end)) 
542                                 continue;
543                         StrBufPlain(target_buf, href_start, href_end - href_start);
544                 }
545                 ptr = link_tag_end;     
546         }
547 }
548
549
550 /*
551  * Wrapper for curl_easy_init() that includes the options common to all calls
552  * used in this module. 
553  */
554 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
555         CURL *curl;
556
557         curl = curl_easy_init();
558         if (!curl) {
559                 return(curl);
560         }
561
562         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
563         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
564
565         if (errmsg) {
566                 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
567         }
568         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
569 #ifdef CURLOPT_HTTP_CONTENT_DECODING
570         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
571         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
572 #endif
573         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
574         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);            /* die after 30 seconds */
575
576         if (
577                 (!IsEmptyStr(config.c_ip_addr))
578                 && (strcmp(config.c_ip_addr, "*"))
579                 && (strcmp(config.c_ip_addr, "::"))
580                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
581         ) {
582                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
583         }
584
585         return(curl);
586 }
587
588
589 /*
590  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
591  */
592 int fetch_http(StrBuf *url, StrBuf **target_buf)
593 {
594         StrBuf *ReplyBuf;
595         CURL *curl;
596         CURLcode result;
597         char *effective_url = NULL;
598         char errmsg[1024] = "";
599
600         if (StrLength(url) <=0 ) return(-1);
601         ReplyBuf = *target_buf = NewStrBuf ();
602         if (ReplyBuf == 0) return(-1);
603
604         curl = ctdl_openid_curl_easy_init(errmsg);
605         if (!curl) return(-1);
606
607         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(url));
608         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
609         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
610
611         result = curl_easy_perform(curl);
612         if (result) {
613                 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
614         }
615         curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
616         StrBufPlain(url, effective_url, -1);
617         
618         curl_easy_cleanup(curl);
619         return StrLength(ReplyBuf);
620 }
621
622
623
624 struct xrds {
625         int nesting_level;
626         int in_xrd;
627         int current_service_priority;
628         int selected_service_priority;  /* more here later */
629 };
630
631
632 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
633         struct xrds *xrds = (struct xrds *) data;
634         int i;
635
636         ++xrds->nesting_level;
637
638         if (!strcasecmp(supplied_el, "XRD")) {
639                 ++xrds->in_xrd;
640                 syslog(LOG_DEBUG, "*** XRD CONTAINER BEGIN ***");
641         }
642
643         else if (!strcasecmp(supplied_el, "service")) {
644                 xrds->current_service_priority = 0;
645                 for (i=0; attr[i] != NULL; i+=2) {
646                         if (!strcasecmp(attr[i], "priority")) {
647                                 xrds->current_service_priority = atoi(attr[i+1]);
648                         }
649                 }
650         }
651 }
652
653
654 void xrds_xml_end(void *data, const char *supplied_el) {
655         struct xrds *xrds = (struct xrds *) data;
656
657         --xrds->nesting_level;
658
659         if (!strcasecmp(supplied_el, "XRD")) {
660                 --xrds->in_xrd;
661                 syslog(LOG_DEBUG, "*** XRD CONTAINER END ***");
662         }
663
664         else if (!strcasecmp(supplied_el, "service")) {
665                 /* this is where we should evaluate the service and do stuff */
666                 xrds->current_service_priority = 0;
667         }
668 }
669
670
671 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
672         struct xrds *xrds = (struct xrds *) data;
673
674         if (xrds) ;     /* this is only here to silence the warning for now */
675         
676         /* StrBufAppendBufPlain (xrds->CData, s, len, 0); */
677 }
678
679
680 /*
681  * Parse an XRDS document.
682  * If OpenID stuff is discovered, populate FIXME something and return nonzero
683  * If nothing useful happened, return 0.
684  */
685 int parse_xrds_document(StrBuf *ReplyBuf) {
686         struct xrds xrds;
687
688         syslog(LOG_DEBUG, "\033[32m --- XRDS DOCUMENT --- \n%s\033[0m", ChrPtr(ReplyBuf));
689
690         memset(&xrds, 0, sizeof (struct xrds));
691         XML_Parser xp = XML_ParserCreate(NULL);
692         if (xp) {
693                 XML_SetUserData(xp, &xrds);
694                 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
695                 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
696                 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
697                 XML_Parse(xp, "", 0, 1);
698                 XML_ParserFree(xp);
699         }
700         else {
701                 syslog(LOG_ALERT, "Cannot create XML parser");
702         }
703
704         return(0);      /* FIXME return nonzero if something wonderful happened */
705 }
706
707
708
709 /*
710  * Callback function for perform_openid2_discovery()
711  * We're interested in the X-XRDS-Location: header.
712  */
713 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
714         char hdr[1024];
715         StrBuf **x_xrds_location = (StrBuf **) userdata;
716
717         memcpy(hdr, ptr, (size*nmemb));
718         hdr[size*nmemb] = 0;
719
720         if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
721                 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
722                 StrBufTrim(*x_xrds_location);
723         }
724
725         return(size * nmemb);
726 }
727
728
729
730 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
731  * 
732  * If Yadis fails, we then attempt HTML discovery using the same document.
733  *
734  * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
735  * If fails, returns 0 and does nothing else.
736  */
737 int perform_openid2_discovery(StrBuf *YadisURL) {
738         int docbytes = (-1);
739         StrBuf *ReplyBuf = NULL;
740         int return_value = 0;
741         CURL *curl;
742         CURLcode result;
743         char errmsg[1024] = "";
744         struct curl_slist *my_headers = NULL;
745         StrBuf *x_xrds_location = NULL;
746
747         if (YadisURL == NULL) return(0);
748         syslog(LOG_DEBUG, "perform_openid2_discovery(%s)", ChrPtr(YadisURL));
749         if (StrLength(YadisURL) == 0) return(0);
750
751         ReplyBuf = NewStrBuf ();
752         if (ReplyBuf == 0) return(0);
753
754         curl = ctdl_openid_curl_easy_init(errmsg);
755         if (!curl) return(0);
756
757         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(YadisURL));
758         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
759         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
760
761         my_headers = curl_slist_append(my_headers, "Accept:");  /* disable the default Accept: header */
762         my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
763         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
764
765         curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
766         curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
767
768         result = curl_easy_perform(curl);
769         if (result) {
770                 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
771         }
772         curl_slist_free_all(my_headers);
773         curl_easy_cleanup(curl);
774         docbytes = StrLength(ReplyBuf);
775
776         /*
777          * The response from the server will be one of:
778          * 
779          * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
780          * attribute, X-XRDS-Location,
781          */
782         /* FIXME handle this somehow */
783
784         /*
785          * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
786          *           together with a document.
787          * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
788          *           a contenttype response-header specifying MIME media type,
789          *           application/xrds+xml, or both.
790          *
791          * If the X-XRDS-Location header was delivered, we know about it at this point...
792          */
793         if (    (x_xrds_location)
794                 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(YadisURL)))
795         ) {
796                 syslog(LOG_DEBUG, "X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
797                 return_value = perform_openid2_discovery(x_xrds_location);
798                 FreeStrBuf(&x_xrds_location);
799         }
800
801         /*
802          * Option 4: the returned web page may *be* an XRDS document.  Try to parse it.
803          */
804         else if (docbytes >= 0) {
805                 return_value = parse_xrds_document(ReplyBuf);
806         }
807
808         /*
809          * Option 5: if all else fails, attempt HTML based discovery.
810          */
811         if (return_value == 0) {
812                 syslog(LOG_DEBUG, "Attempting HTML discovery");
813                 StrBuf *foo = NewStrBuf();
814                 extract_link(foo, HKEY("openid2.provider"), ReplyBuf);
815                 if (StrLength(foo) > 0) {
816                         syslog(LOG_DEBUG, "\033[31mHTML DISCO PROVIDER: %s\033[0m", ChrPtr(foo));
817                 }
818                 FreeStrBuf(&foo);
819         }
820
821         if (ReplyBuf != NULL) {
822                 FreeStrBuf(&ReplyBuf);
823         }
824         return(return_value);
825 }
826
827
828 /*
829  * Setup an OpenID authentication
830  */
831 void cmd_oids(char *argbuf) {
832         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
833         const char *Pos = NULL;
834         StrBuf *ArgBuf = NULL;
835         StrBuf *ReplyBuf = NULL;
836         StrBuf *return_to = NULL;
837         StrBuf *trust_root = NULL;
838         StrBuf *openid_delegate = NULL;
839         StrBuf *RedirectUrl = NULL;
840         ctdl_openid *oiddata;
841         int discovery_succeeded = 0;
842
843         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
844
845         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
846         if (oiddata == NULL) {
847                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
848                 return;
849         }
850         memset(oiddata, 0, sizeof(ctdl_openid));
851         CCC->openid_data = (void *) oiddata;
852
853         ArgBuf = NewStrBufPlain(argbuf, -1);
854
855         oiddata->verified = 0;
856         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
857         trust_root = NewStrBufPlain(NULL, StrLength(ArgBuf));
858         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
859
860         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
861         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
862         StrBufExtract_NextToken(trust_root, ArgBuf, &Pos, '|');
863
864         syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
865
866
867         /********** OpenID 2.0 section 7.3 - Discovery **********/
868
869         /* Section 7.3.1 says we have to attempt XRI based discovery.
870          * No one is using this, no one is asking for it, no one wants it.
871          * So we're not even going to bother attempting this mode.
872          */
873
874         /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
875          */
876         discovery_succeeded = perform_openid2_discovery(oiddata->claimed_id);
877
878
879
880         /************ OPENID 1.1 **********/
881
882         if (    (fetch_http(oiddata->claimed_id, &ReplyBuf) > 0)
883                 && (StrLength(ReplyBuf) > 0)
884         ) {
885                 openid_delegate = NewStrBuf();
886                 oiddata->server = NewStrBuf();
887                 extract_link(oiddata->server, HKEY("openid.server"), ReplyBuf);
888                 extract_link(openid_delegate, HKEY("openid.delegate"), ReplyBuf);
889
890                 if (StrLength(oiddata->server) == 0) {
891                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
892                         FreeStrBuf(&ArgBuf);
893                         FreeStrBuf(&ReplyBuf);
894                         FreeStrBuf(&return_to);
895                         FreeStrBuf(&trust_root);
896                         FreeStrBuf(&openid_delegate);
897                         FreeStrBuf(&RedirectUrl);
898                         return;
899                 }
900
901                 /* Empty delegate is legal; we just use the openid_url instead */
902                 if (StrLength(openid_delegate) == 0) {
903                         StrBufPlain(openid_delegate, SKEY(oiddata->claimed_id));
904                 }
905
906                 /* Assemble a URL to which the user-agent will be redirected. */
907
908                 RedirectUrl = NewStrBufDup(oiddata->server);
909
910                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.mode=checkid_setup"
911                                                        "&openid.identity="), 0);
912                 StrBufUrlescAppend(RedirectUrl, openid_delegate, NULL);
913
914                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
915                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
916
917                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.trust_root="), 0);
918                 StrBufUrlescAppend(RedirectUrl, trust_root, NULL);
919
920                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.sreg.optional="), 0);
921                 StrBufUrlescAppend(RedirectUrl, NULL, "nickname,email,fullname,postcode,country,dob,gender");
922
923                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
924                 
925                 FreeStrBuf(&ArgBuf);
926                 FreeStrBuf(&ReplyBuf);
927                 FreeStrBuf(&return_to);
928                 FreeStrBuf(&trust_root);
929                 FreeStrBuf(&openid_delegate);
930                 FreeStrBuf(&RedirectUrl);
931
932                 return;
933         }
934
935         FreeStrBuf(&ArgBuf);
936         FreeStrBuf(&ReplyBuf);
937         FreeStrBuf(&return_to);
938         FreeStrBuf(&trust_root);
939         FreeStrBuf(&openid_delegate);
940         FreeStrBuf(&RedirectUrl);
941
942         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
943 }
944
945
946
947
948
949 /*
950  * Finalize an OpenID authentication
951  */
952 void cmd_oidf(char *argbuf) {
953         long len;
954         char buf[2048];
955         char thiskey[1024];
956         char thisdata[1024];
957         HashList *keys = NULL;
958         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
959
960         if (oiddata == NULL) {
961                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
962                 return;
963         }
964         if (StrLength(oiddata->server) == 0){
965                 cprintf("%d need a remote server to authenticate against\n", ERROR + ILLEGAL_VALUE);
966                 return;
967         }
968         keys = NewHash(1, NULL);
969         if (!keys) {
970                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
971                 return;
972         }
973         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
974
975         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
976                 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
977                 if (len < 0)
978                         len = sizeof(thiskey) - 1;
979                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
980                 syslog(LOG_DEBUG, "%s: ["SIZE_T_FMT"] %s", thiskey, strlen(thisdata), thisdata);
981                 Put(keys, thiskey, len, strdup(thisdata), NULL);
982         }
983
984
985         /* Now that we have all of the parameters, we have to validate the signature against the server */
986         syslog(LOG_DEBUG, "About to validate the signature...");
987
988         CURL *curl;
989         CURLcode res;
990         struct curl_httppost *formpost = NULL;
991         struct curl_httppost *lastptr = NULL;
992         char errmsg[1024] = "";
993         char *o_assoc_handle = NULL;
994         char *o_sig = NULL;
995         char *o_signed = NULL;
996         int num_signed_values;
997         int i;
998         char k_keyname[128];
999         char k_o_keyname[128];
1000         char *k_value = NULL;
1001         StrBuf *ReplyBuf;
1002
1003         curl_formadd(&formpost, &lastptr,
1004                 CURLFORM_COPYNAME,      "openid.mode",
1005                 CURLFORM_COPYCONTENTS,  "check_authentication",
1006                 CURLFORM_END);
1007         syslog(LOG_DEBUG, "%25s : %s", "openid.mode", "check_authentication");
1008
1009         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
1010                 curl_formadd(&formpost, &lastptr,
1011                         CURLFORM_COPYNAME,      "openid.assoc_handle",
1012                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
1013                         CURLFORM_END);
1014                 syslog(LOG_DEBUG, "%25s : %s", "openid.assoc_handle", o_assoc_handle);
1015         }
1016
1017         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
1018                 curl_formadd(&formpost, &lastptr,
1019                         CURLFORM_COPYNAME,      "openid.sig",
1020                         CURLFORM_COPYCONTENTS,  o_sig,
1021                         CURLFORM_END);
1022                         syslog(LOG_DEBUG, "%25s : %s", "openid.sig", o_sig);
1023         }
1024
1025         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
1026                 curl_formadd(&formpost, &lastptr,
1027                         CURLFORM_COPYNAME,      "openid.signed",
1028                         CURLFORM_COPYCONTENTS,  o_signed,
1029                         CURLFORM_END);
1030                 syslog(LOG_DEBUG, "%25s : %s", "openid.signed", o_signed);
1031
1032                 num_signed_values = num_tokens(o_signed, ',');
1033                 for (i=0; i<num_signed_values; ++i) {
1034                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
1035                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
1036                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
1037                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
1038                                         curl_formadd(&formpost, &lastptr,
1039                                                 CURLFORM_COPYNAME,      k_o_keyname,
1040                                                 CURLFORM_COPYCONTENTS,  k_value,
1041                                                 CURLFORM_END);
1042                                         syslog(LOG_DEBUG, "%25s : %s", k_o_keyname, k_value);
1043                                 }
1044                                 else {
1045                                         syslog(LOG_INFO, "OpenID: signed field '%s' is missing",
1046                                                 k_keyname);
1047                                 }
1048                         }
1049                 }
1050         }
1051         
1052         ReplyBuf = NewStrBuf();
1053
1054         curl = ctdl_openid_curl_easy_init(errmsg);
1055         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->server));
1056         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
1057         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1058         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
1059
1060         res = curl_easy_perform(curl);
1061         if (res) {
1062                 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
1063         }
1064         curl_easy_cleanup(curl);
1065         curl_formfree(formpost);
1066
1067         if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true")) {
1068                 oiddata->verified = 1;
1069         }
1070         FreeStrBuf(&ReplyBuf);
1071
1072         syslog(LOG_DEBUG, "Authentication %s.", (oiddata->verified ? "succeeded" : "failed") );
1073
1074         /* Respond to the client */
1075
1076         if (oiddata->verified) {
1077
1078                 /* If we were already logged in, attach the OpenID to the user's account */
1079                 if (CC->logged_in) {
1080                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
1081                                 cprintf("attach\n");
1082                                 syslog(LOG_DEBUG, "OpenID attach succeeded");
1083                         }
1084                         else {
1085                                 cprintf("fail\n");
1086                                 syslog(LOG_DEBUG, "OpenID attach failed");
1087                         }
1088                 }
1089
1090                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
1091                 else {
1092                         /*
1093                          * Existing user who has claimed this OpenID?
1094                          *
1095                          * Note: if you think that sending the password back over the wire is insecure,
1096                          * check your assumptions.  If someone has successfully asserted an OpenID that
1097                          * is associated with the account, they already have password equivalency and can
1098                          * login, so they could just as easily change the password, etc.
1099                          */
1100                         if (login_via_openid(oiddata->claimed_id) == 0) {
1101                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1102                                 logged_in_response();
1103                                 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
1104                         }
1105
1106                         /*
1107                          * If this system does not allow self-service new user registration, the
1108                          * remaining modes do not apply, so fail here and now.
1109                          */
1110                         else if (config.c_disable_newu) {
1111                                 cprintf("fail\n");
1112                                 syslog(LOG_DEBUG, "Creating user failed due to local policy");
1113                         }
1114
1115                         /*
1116                          * New user whose OpenID is verified and Simple Registration Extension is in use?
1117                          */
1118                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
1119                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1120                                 logged_in_response();
1121                                 syslog(LOG_DEBUG, "Successfully auto-created new user");
1122                         }
1123
1124                         /*
1125                          * OpenID is verified, but the desired username either was not specified or
1126                          * conflicts with an existing user.  Manual account creation is required.
1127                          */
1128                         else {
1129                                 char *desired_name = NULL;
1130                                 cprintf("verify_only\n");
1131                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1132                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1133                                         cprintf("%s\n", desired_name);
1134                                 }
1135                                 else {
1136                                         cprintf("\n");
1137                                 }
1138                                 syslog(LOG_DEBUG, "The desired Simple Registration name is already taken.");
1139                         }
1140                 }
1141         }
1142         else {
1143                 cprintf("fail\n");
1144         }
1145         cprintf("000\n");
1146
1147         if (oiddata->sreg_keys != NULL) {
1148                 DeleteHash(&oiddata->sreg_keys);
1149                 oiddata->sreg_keys = NULL;
1150         }
1151         oiddata->sreg_keys = keys;
1152 }
1153
1154
1155
1156 /**************************************************************************/
1157 /*                                                                        */
1158 /* Functions in this section handle module initialization and shutdown    */
1159 /*                                                                        */
1160 /**************************************************************************/
1161
1162
1163
1164
1165 CTDL_MODULE_INIT(openid_rp)
1166 {
1167         if (!threading) {
1168                 curl_global_init(CURL_GLOBAL_ALL);
1169
1170                 /* Only enable the OpenID command set when native mode authentication is in use. */
1171                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
1172                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1173                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1174                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1175                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1176                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1177                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1178                 }
1179                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
1180                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
1181                 openid_level_supported = 1;     /* This module supports OpenID 1.0 only */
1182         }
1183
1184         /* return our module name for the log */
1185         return "openid_rp";
1186 }