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