ecb4ef3875eb9c6b6c477224fbb537aa326dcdba
[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-2012 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  * Create a new user account, manually specifying the name, after successfully
263  * verifying an OpenID (which will of course be attached to the account)
264  */
265 void cmd_oidc(char *argbuf) {
266         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
267
268         if ( (!oiddata) || (!oiddata->verified) ) {
269                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
270                 return;
271         }
272
273         /* We can make the semantics of OIDC exactly the same as NEWU, simply
274          * by _calling_ cmd_newu() and letting it run.  Very clever!
275          */
276         cmd_newu(argbuf);
277
278         /* Now, if this logged us in, we have to attach the OpenID */
279         if (CC->logged_in) {
280                 attach_openid(&CC->user, oiddata->claimed_id);
281         }
282
283 }
284
285
286 /*
287  * Detach an OpenID from the currently logged in account
288  */
289 void cmd_oidd(char *argbuf) {
290         struct cdbdata *cdboi;
291         char id_to_detach[1024];
292         int this_is_mine = 0;
293         long usernum = 0L;
294
295         if (CtdlAccessCheck(ac_logged_in)) return;
296         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
297         if (IsEmptyStr(id_to_detach)) {
298                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
299         }
300
301         cdb_rewind(CDB_OPENID);
302         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
303                 if (cdboi->len > sizeof(long)) {
304                         memcpy(&usernum, cdboi->ptr, sizeof(long));
305                         if (usernum == CC->user.usernum) {
306                                 this_is_mine = 1;
307                         }
308                 }
309                 cdb_free(cdboi);
310         }
311
312         if (!this_is_mine) {
313                 cprintf("%d That OpenID was not found or not associated with your account.\n",
314                         ERROR + ILLEGAL_VALUE);
315                 return;
316         }
317
318         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
319         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
320 }
321
322
323 /*
324  * Attempt to auto-create a new Citadel account using the nickname from Attribute Exchange
325  */
326 int openid_create_user_via_ax(StrBuf *claimed_id, HashList *sreg_keys)
327 {
328         char *nickname = NULL;
329         char *firstname = NULL;
330         char *lastname = NULL;
331         char new_password[32];
332         long len;
333         const char *Key;
334         void *Value;
335
336         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
337         if (config.c_disable_newu) return(2);
338         if (CC->logged_in) return(3);
339
340         HashPos *HashPos = GetNewHashPos(sreg_keys, 0);
341         while (GetNextHashPos(sreg_keys, HashPos, &len, &Key, &Value) != 0) {
342                 syslog(LOG_DEBUG, "%s = %s", Key, (char *)Value);
343
344                 if (cbmstrcasestr(Key, "value.nickname") != NULL) {
345                         nickname = (char *)Value;
346                 }
347                 else if ( (nickname == NULL) && (cbmstrcasestr(Key, "value.nickname") != NULL)) {
348                         nickname = (char *)Value;
349                 }
350                 else if (cbmstrcasestr(Key, "value.firstname") != NULL) {
351                         firstname = (char *)Value;
352                 }
353                 else if (cbmstrcasestr(Key, "value.lastname") != NULL) {
354                         lastname = (char *)Value;
355                 }
356
357         }
358         DeleteHashPos(&HashPos);
359
360         if (nickname == NULL) {
361                 if ((firstname != NULL) || (lastname != NULL)) {
362                         char fullname[1024] = "";
363                         if (firstname) strcpy(fullname, firstname);
364                         if (firstname && lastname) strcat(fullname, " ");
365                         if (lastname) strcat(fullname, lastname);
366                         nickname = fullname;
367                 }
368         }
369
370         if (nickname == NULL) {
371                 return(4);
372         }
373         syslog(LOG_DEBUG, "The desired account name is <%s>", nickname);
374
375         len = cutuserkey(nickname);
376         if (!CtdlGetUser(&CC->user, nickname)) {
377                 syslog(LOG_DEBUG, "<%s> is already taken by another user.", nickname);
378                 memset(&CC->user, 0, sizeof(struct ctdluser));
379                 return(5);
380         }
381
382         /* The desired account name is available.  Create the account and log it in! */
383         if (create_user(nickname, len, 1)) return(6);
384
385         /* Generate a random password.
386          * The user doesn't care what the password is since he is using OpenID.
387          */
388         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
389         CtdlSetPassword(new_password);
390
391         /* Now attach the verified OpenID to this account. */
392         attach_openid(&CC->user, claimed_id);
393
394         return(0);
395 }
396
397
398 /*
399  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
400  * Otherwise it returns nonzero.
401  */
402 int login_via_openid(StrBuf *claimed_id)
403 {
404         struct cdbdata *cdboi;
405         long usernum = 0;
406
407         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
408         if (cdboi == NULL) {
409                 return(-1);
410         }
411
412         memcpy(&usernum, cdboi->ptr, sizeof(long));
413         cdb_free(cdboi);
414
415         if (!CtdlGetUserByNumber(&CC->user, usernum)) {
416                 /* Now become the user we just created */
417                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
418                 do_login();
419                 return(0);
420         }
421         else {
422                 memset(&CC->user, 0, sizeof(struct ctdluser));
423                 return(-1);
424         }
425 }
426
427
428
429
430 /**************************************************************************/
431 /*                                                                        */
432 /* Functions in this section handle OpenID protocol                       */
433 /*                                                                        */
434 /**************************************************************************/
435
436
437 /* 
438  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
439  */
440 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
441 {
442         int i;
443         const char *ptr;
444         const char *href_start = NULL;
445         const char *href_end = NULL;
446         const char *link_tag_start = NULL;
447         const char *link_tag_end = NULL;
448         const char *rel_start = NULL;
449         const char *rel_end = NULL;
450
451         if (!target_buf) return;
452         if (!rel) return;
453         if (!source_buf) return;
454
455         ptr = ChrPtr(source_buf);
456
457         FlushStrBuf(target_buf);
458         while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
459
460                 link_tag_start = ptr;
461                 link_tag_end = strchr(ptr, '>');
462                 if (link_tag_end == NULL)
463                         break;
464                 for (i=0; i < 1; i++ ){
465                         rel_start = cbmstrcasestr(link_tag_start, "rel=");
466                         if ((rel_start == NULL) ||
467                             (rel_start > link_tag_end)) 
468                                 continue;
469
470                         rel_start = strchr(rel_start, '\"');
471                         if ((rel_start == NULL) ||
472                             (rel_start > link_tag_end)) 
473                                 continue;
474                         ++rel_start;
475                         rel_end = strchr(rel_start, '\"');
476                         if ((rel_end == NULL) ||
477                             (rel_end == rel_start) ||
478                             (rel_end >= link_tag_end) ) 
479                                 continue;
480                         if (strncasecmp(rel, rel_start, repllen)!= 0)
481                                 continue; /* didn't match? never mind... */
482                         
483                         href_start = cbmstrcasestr(link_tag_start, "href=");
484                         if ((href_start == NULL) || 
485                             (href_start >= link_tag_end)) 
486                                 continue;
487                         href_start = strchr(href_start, '\"');
488                         if ((href_start == NULL) |
489                             (href_start >= link_tag_end)) 
490                                 continue;
491                         ++href_start;
492                         href_end = strchr(href_start, '\"');
493                         if ((href_end == NULL) || 
494                             (href_end == href_start) ||
495                             (href_start >= link_tag_end)) 
496                                 continue;
497                         StrBufPlain(target_buf, href_start, href_end - href_start);
498                 }
499                 ptr = link_tag_end;     
500         }
501 }
502
503
504 /*
505  * Wrapper for curl_easy_init() that includes the options common to all calls
506  * used in this module. 
507  */
508 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
509         CURL *curl;
510
511         curl = curl_easy_init();
512         if (!curl) {
513                 return(curl);
514         }
515
516         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
517         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
518
519         if (errmsg) {
520                 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
521         }
522         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
523 #ifdef CURLOPT_HTTP_CONTENT_DECODING
524         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
525         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
526 #endif
527         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
528         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);            /* die after 30 seconds */
529
530         if (
531                 (!IsEmptyStr(config.c_ip_addr))
532                 && (strcmp(config.c_ip_addr, "*"))
533                 && (strcmp(config.c_ip_addr, "::"))
534                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
535         ) {
536                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
537         }
538
539         return(curl);
540 }
541
542
543 struct xrds {
544         StrBuf *CharData;
545         int nesting_level;
546         int in_xrd;
547         int current_service_priority;
548         int selected_service_priority;
549         StrBuf *current_service_uri;
550         StrBuf *selected_service_uri;
551         int current_service_is_oid2auth;
552 };
553
554
555 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
556         struct xrds *xrds = (struct xrds *) data;
557         int i;
558
559         ++xrds->nesting_level;
560
561         if (!strcasecmp(supplied_el, "XRD")) {
562                 ++xrds->in_xrd;
563         }
564
565         else if (!strcasecmp(supplied_el, "service")) {
566                 xrds->current_service_priority = 0;
567                 xrds->current_service_is_oid2auth = 0;
568                 for (i=0; attr[i] != NULL; i+=2) {
569                         if (!strcasecmp(attr[i], "priority")) {
570                                 xrds->current_service_priority = atoi(attr[i+1]);
571                         }
572                 }
573         }
574
575         FlushStrBuf(xrds->CharData);
576 }
577
578
579 void xrds_xml_end(void *data, const char *supplied_el) {
580         struct xrds *xrds = (struct xrds *) data;
581
582         --xrds->nesting_level;
583
584         if (!strcasecmp(supplied_el, "XRD")) {
585                 --xrds->in_xrd;
586         }
587
588         else if (!strcasecmp(supplied_el, "type")) {
589                 if (    (xrds->in_xrd)
590                         && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/server"))
591                 ) {
592                         xrds->current_service_is_oid2auth = 1;
593                 }
594                 if (    (xrds->in_xrd)
595                         && (!strcasecmp(ChrPtr(xrds->CharData), "http://specs.openid.net/auth/2.0/signon"))
596                 ) {
597                         xrds->current_service_is_oid2auth = 1;
598                         /* FIXME in this case, the Claimed ID should be considered immutable */
599                 }
600         }
601
602         else if (!strcasecmp(supplied_el, "uri")) {
603                 if (xrds->in_xrd) {
604                         FlushStrBuf(xrds->current_service_uri);
605                         StrBufAppendBuf(xrds->current_service_uri, xrds->CharData, 0);
606                 }
607         }
608
609         else if (!strcasecmp(supplied_el, "service")) {
610                 if (    (xrds->in_xrd)
611                         && (xrds->current_service_priority < xrds->selected_service_priority)
612                         && (xrds->current_service_is_oid2auth)
613                 ) {
614                         xrds->selected_service_priority = xrds->current_service_priority;
615                         FlushStrBuf(xrds->selected_service_uri);
616                         StrBufAppendBuf(xrds->selected_service_uri, xrds->current_service_uri, 0);
617                 }
618
619         }
620
621         FlushStrBuf(xrds->CharData);
622 }
623
624
625 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
626         struct xrds *xrds = (struct xrds *) data;
627
628         StrBufAppendBufPlain (xrds->CharData, s, len, 0);
629 }
630
631
632 /*
633  * Parse an XRDS document.
634  * If an OpenID Provider URL is discovered, op_url to that value and return nonzero.
635  * If nothing useful happened, return 0.
636  */
637 int parse_xrds_document(StrBuf *ReplyBuf) {
638         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
639         struct xrds xrds;
640         int return_value = 0;
641
642         memset(&xrds, 0, sizeof (struct xrds));
643         xrds.selected_service_priority = INT_MAX;
644         xrds.CharData = NewStrBuf();
645         xrds.current_service_uri = NewStrBuf();
646         xrds.selected_service_uri = NewStrBuf();
647         XML_Parser xp = XML_ParserCreate(NULL);
648         if (xp) {
649                 XML_SetUserData(xp, &xrds);
650                 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
651                 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
652                 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
653                 XML_Parse(xp, "", 0, 1);
654                 XML_ParserFree(xp);
655         }
656         else {
657                 syslog(LOG_ALERT, "Cannot create XML parser");
658         }
659
660         if (xrds.selected_service_priority < INT_MAX) {
661                 if (oiddata->op_url == NULL) {
662                         oiddata->op_url = NewStrBuf();
663                 }
664                 FlushStrBuf(oiddata->op_url);
665                 StrBufAppendBuf(oiddata->op_url, xrds.selected_service_uri, 0);
666                 return_value = openid_disco_xrds;
667         }
668
669         FreeStrBuf(&xrds.CharData);
670         FreeStrBuf(&xrds.current_service_uri);
671         FreeStrBuf(&xrds.selected_service_uri);
672
673         return(return_value);
674 }
675
676
677 /*
678  * Callback function for perform_openid2_discovery()
679  * We're interested in the X-XRDS-Location: header.
680  */
681 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
682         char hdr[1024];
683         StrBuf **x_xrds_location = (StrBuf **) userdata;
684
685         memcpy(hdr, ptr, (size*nmemb));
686         hdr[size*nmemb] = 0;
687
688         if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
689                 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
690                 StrBufTrim(*x_xrds_location);
691         }
692
693         return(size * nmemb);
694 }
695
696
697 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
698  * 
699  * If Yadis fails, we then attempt HTML discovery using the same document.
700  *
701  * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
702  * If fails, returns 0 and does nothing else.
703  */
704 int perform_openid2_discovery(StrBuf *SuppliedURL) {
705         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
706         int docbytes = (-1);
707         StrBuf *ReplyBuf = NULL;
708         int return_value = 0;
709         CURL *curl;
710         CURLcode result;
711         char errmsg[1024] = "";
712         struct curl_slist *my_headers = NULL;
713         StrBuf *x_xrds_location = NULL;
714
715         if (!SuppliedURL) return(0);
716         syslog(LOG_DEBUG, "perform_openid2_discovery(%s)", ChrPtr(SuppliedURL));
717         if (StrLength(SuppliedURL) == 0) return(0);
718
719         ReplyBuf = NewStrBuf();
720         if (!ReplyBuf) return(0);
721
722         curl = ctdl_openid_curl_easy_init(errmsg);
723         if (!curl) return(0);
724
725         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(SuppliedURL));
726         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
727         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
728
729         my_headers = curl_slist_append(my_headers, "Accept:");  /* disable the default Accept: header */
730         my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
731         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
732
733         curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
734         curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
735
736         result = curl_easy_perform(curl);
737         if (result) {
738                 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
739         }
740         curl_slist_free_all(my_headers);
741         curl_easy_cleanup(curl);
742         docbytes = StrLength(ReplyBuf);
743
744         /*
745          * The response from the server will be one of:
746          * 
747          * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
748          * attribute, X-XRDS-Location,
749          *
750          * Does any provider actually do this?  If so then we will implement it in the future.
751          */
752
753         /*
754          * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
755          *           together with a document.
756          * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
757          *           a contenttype response-header specifying MIME media type,
758          *           application/xrds+xml, or both.
759          *
760          * If the X-XRDS-Location header was delivered, we know about it at this point...
761          */
762         if (    (x_xrds_location)
763                 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(SuppliedURL)))
764         ) {
765                 syslog(LOG_DEBUG, "X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
766                 return_value = perform_openid2_discovery(x_xrds_location);
767                 FreeStrBuf(&x_xrds_location);
768         }
769
770         /*
771          * Option 4: the returned web page may *be* an XRDS document.  Try to parse it.
772          */
773         if ( (return_value == 0) && (docbytes >= 0)) {
774                 return_value = parse_xrds_document(ReplyBuf);
775         }
776
777         /*
778          * Option 5: if all else fails, attempt HTML based discovery.
779          */
780         if ( (return_value == 0) && (docbytes >= 0)) {
781                 if (oiddata->op_url == NULL) {
782                         oiddata->op_url = NewStrBuf();
783                 }
784                 extract_link(oiddata->op_url, HKEY("openid2.provider"), ReplyBuf);
785                 if (StrLength(oiddata->op_url) > 0) {
786                         return_value = openid_disco_html;
787                 }
788         }
789
790         if (ReplyBuf != NULL) {
791                 FreeStrBuf(&ReplyBuf);
792         }
793         return(return_value);
794 }
795
796
797 /*
798  * Setup an OpenID authentication
799  */
800 void cmd_oids(char *argbuf) {
801         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
802         const char *Pos = NULL;
803         StrBuf *ArgBuf = NULL;
804         StrBuf *ReplyBuf = NULL;
805         StrBuf *return_to = NULL;
806         StrBuf *RedirectUrl = NULL;
807         ctdl_openid *oiddata;
808         int discovery_succeeded = 0;
809
810         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
811
812         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
813         if (oiddata == NULL) {
814                 syslog(LOG_ALERT, "malloc() failed: %s", strerror(errno));
815                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
816                 return;
817         }
818         memset(oiddata, 0, sizeof(ctdl_openid));
819
820         ArgBuf = NewStrBufPlain(argbuf, -1);
821
822         oiddata->verified = 0;
823         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
824         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
825
826         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
827         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
828
829         syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
830
831         /********** OpenID 2.0 section 7.3 - Discovery **********/
832
833         /* Section 7.3.1 says we have to attempt XRI based discovery.
834          * No one is using this, no one is asking for it, no one wants it.
835          * So we're not even going to bother attempting this mode.
836          */
837
838         /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
839          */
840         discovery_succeeded = perform_openid2_discovery(oiddata->claimed_id);
841
842         if (discovery_succeeded == 0) {
843                 cprintf("%d There is no OpenID identity provider at this location.\n", ERROR);
844         }
845
846         else {
847                 /*
848                  * If we get to this point we are in possession of a valid OpenID Provider URL.
849                  */
850                 syslog(LOG_DEBUG, "OP URI '%s' discovered using method %d",
851                         ChrPtr(oiddata->op_url),
852                         discovery_succeeded
853                 );
854
855                 /* We have to "normalize" our Claimed ID otherwise it will cause some OP's to barf */
856                 if (cbmstrcasestr(ChrPtr(oiddata->claimed_id), "://") == NULL) {
857                         StrBuf *cid = oiddata->claimed_id;
858                         oiddata->claimed_id = NewStrBufPlain(HKEY("http://"));
859                         StrBufAppendBuf(oiddata->claimed_id, cid, 0);
860                         FreeStrBuf(&cid);
861                 }
862
863                 /*
864                  * OpenID 2.0 section 9: request authentication
865                  * Assemble a URL to which the user-agent will be redirected.
866                  */
867         
868                 RedirectUrl = NewStrBufDup(oiddata->op_url);
869
870                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.ns="), 0);
871                 StrBufUrlescAppend(RedirectUrl, NULL, "http://specs.openid.net/auth/2.0");
872
873                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.mode=checkid_setup"), 0);
874
875                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.claimed_id="), 0);
876                 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
877
878                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.identity="), 0);
879                 StrBufUrlescAppend(RedirectUrl, oiddata->claimed_id, NULL);
880
881                 /* return_to tells the provider how to complete the round trip back to our site */
882                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
883                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
884
885                 /* Attribute Exchange
886                  * See:
887                  *      http://openid.net/specs/openid-attribute-exchange-1_0.html
888                  *      http://code.google.com/apis/accounts/docs/OpenID.html#endpoint
889                  *      http://test-id.net/OP/AXFetch.aspx
890                  */
891
892                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ns.ax="), 0);
893                 StrBufUrlescAppend(RedirectUrl, NULL, "http://openid.net/srv/ax/1.0");
894
895                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.mode=fetch_request"), 0);
896
897                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.required=firstname,lastname,friendly,nickname"), 0);
898
899                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.firstname="), 0);
900                 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/first");
901
902                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.lastname="), 0);
903                 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/last");
904
905                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.friendly="), 0);
906                 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/friendly");
907
908                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.ax.type.nickname="), 0);
909                 StrBufUrlescAppend(RedirectUrl, NULL, "http://axschema.org/namePerson/nickname");
910
911                 syslog(LOG_DEBUG, "OpenID: redirecting client to %s", ChrPtr(RedirectUrl));
912                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
913         }
914         
915         FreeStrBuf(&ArgBuf);
916         FreeStrBuf(&ReplyBuf);
917         FreeStrBuf(&return_to);
918         FreeStrBuf(&RedirectUrl);
919 }
920
921
922 /*
923  * Finalize an OpenID authentication
924  */
925 void cmd_oidf(char *argbuf) {
926         long len;
927         char buf[2048];
928         char thiskey[1024];
929         char thisdata[1024];
930         HashList *keys = NULL;
931         const char *Key;
932         void *Value;
933         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
934
935         if (oiddata == NULL) {
936                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
937                 return;
938         }
939         if (StrLength(oiddata->op_url) == 0){
940                 cprintf("%d No OpenID Endpoint URL has been obtained.\n", ERROR + ILLEGAL_VALUE);
941                 return;
942         }
943         keys = NewHash(1, NULL);
944         if (!keys) {
945                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
946                 return;
947         }
948         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
949
950         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
951                 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
952                 if (len < 0) {
953                         len = sizeof(thiskey) - 1;
954                 }
955                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
956                 Put(keys, thiskey, len, strdup(thisdata), NULL);
957         }
958
959         /* Check to see if this is a correct response.
960          * Start with verified=1 but then set it to 0 if anything looks wrong.
961          */
962         oiddata->verified = 1;
963
964         char *openid_ns = NULL;
965         if (    (!GetHash(keys, "ns", 2, (void *) &openid_ns))
966                 || (strcasecmp(openid_ns, "http://specs.openid.net/auth/2.0"))
967         ) {
968                 syslog(LOG_DEBUG, "This is not an an OpenID assertion");
969                 oiddata->verified = 0;
970         }
971
972         char *openid_mode = NULL;
973         if (    (!GetHash(keys, "mode", 4, (void *) &openid_mode))
974                 || (strcasecmp(openid_mode, "id_res"))
975         ) {
976                 oiddata->verified = 0;
977         }
978
979         char *openid_claimed_id = NULL;
980         if (GetHash(keys, "claimed_id", 10, (void *) &openid_claimed_id)) {
981                 FreeStrBuf(&oiddata->claimed_id);
982                 oiddata->claimed_id = NewStrBufPlain(openid_claimed_id, -1);
983                 syslog(LOG_DEBUG, "Provider is asserting the Claimed ID '%s'", ChrPtr(oiddata->claimed_id));
984         }
985
986         /* Validate the assertion against the server */
987         syslog(LOG_DEBUG, "Validating...");
988
989         CURL *curl;
990         CURLcode res;
991         struct curl_httppost *formpost = NULL;
992         struct curl_httppost *lastptr = NULL;
993         char errmsg[1024] = "";
994         StrBuf *ReplyBuf = NewStrBuf();
995
996         curl_formadd(&formpost, &lastptr,
997                 CURLFORM_COPYNAME,      "openid.mode",
998                 CURLFORM_COPYCONTENTS,  "check_authentication",
999                 CURLFORM_END
1000         );
1001
1002         HashPos *HashPos = GetNewHashPos(keys, 0);
1003         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value) != 0) {
1004                 if (strcasecmp(Key, "mode")) {
1005                         char k_o_keyname[1024];
1006                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", (const char *)Key);
1007                         curl_formadd(&formpost, &lastptr,
1008                                 CURLFORM_COPYNAME,      k_o_keyname,
1009                                 CURLFORM_COPYCONTENTS,  (char *)Value,
1010                                 CURLFORM_END
1011                         );
1012                 }
1013         }
1014         DeleteHashPos(&HashPos);
1015
1016         curl = ctdl_openid_curl_easy_init(errmsg);
1017         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->op_url));
1018         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
1019         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1020         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
1021
1022         res = curl_easy_perform(curl);
1023         if (res) {
1024                 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
1025                 oiddata->verified = 0;
1026         }
1027         curl_easy_cleanup(curl);
1028         curl_formfree(formpost);
1029
1030         /* syslog(LOG_DEBUG, "Validation reply: \n%s", ChrPtr(ReplyBuf)); */
1031         if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true") == NULL) {
1032                 oiddata->verified = 0;
1033         }
1034         FreeStrBuf(&ReplyBuf);
1035
1036         syslog(LOG_DEBUG, "OpenID authentication %s", (oiddata->verified ? "succeeded" : "failed") );
1037
1038         /* Respond to the client */
1039
1040         if (oiddata->verified) {
1041
1042                 /* If we were already logged in, attach the OpenID to the user's account */
1043                 if (CC->logged_in) {
1044                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
1045                                 cprintf("attach\n");
1046                                 syslog(LOG_DEBUG, "OpenID attach succeeded");
1047                         }
1048                         else {
1049                                 cprintf("fail\n");
1050                                 syslog(LOG_DEBUG, "OpenID attach failed");
1051                         }
1052                 }
1053
1054                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
1055                 else {
1056                         /*
1057                          * Existing user who has claimed this OpenID?
1058                          *
1059                          * Note: if you think that sending the password back over the wire is insecure,
1060                          * check your assumptions.  If someone has successfully asserted an OpenID that
1061                          * is associated with the account, they already have password equivalency and can
1062                          * login, so they could just as easily change the password, etc.
1063                          */
1064                         if (login_via_openid(oiddata->claimed_id) == 0) {
1065                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1066                                 logged_in_response();
1067                                 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
1068                         }
1069
1070                         /*
1071                          * If this system does not allow self-service new user registration, the
1072                          * remaining modes do not apply, so fail here and now.
1073                          */
1074                         else if (config.c_disable_newu) {
1075                                 cprintf("fail\n");
1076                                 syslog(LOG_DEBUG, "Creating user failed due to local policy");
1077                         }
1078
1079                         /*
1080                          * New user whose OpenID is verified and Attribute Exchange gave us a name?
1081                          */
1082                         else if (openid_create_user_via_ax(oiddata->claimed_id, keys) == 0) {
1083                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1084                                 logged_in_response();
1085                                 syslog(LOG_DEBUG, "Successfully auto-created new user");
1086                         }
1087
1088                         /*
1089                          * OpenID is verified, but the desired username either was not specified or
1090                          * conflicts with an existing user.  Manual account creation is required.
1091                          */
1092                         else {
1093                                 char *desired_name = NULL;
1094                                 cprintf("verify_only\n");
1095                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1096                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1097                                         cprintf("%s\n", desired_name);
1098                                 }
1099                                 else {
1100                                         cprintf("\n");
1101                                 }
1102                                 syslog(LOG_DEBUG, "The desired display name is already taken.");
1103                         }
1104                 }
1105         }
1106         else {
1107                 cprintf("fail\n");
1108         }
1109         cprintf("000\n");
1110
1111         if (oiddata->sreg_keys != NULL) {
1112                 DeleteHash(&oiddata->sreg_keys);
1113                 oiddata->sreg_keys = NULL;
1114         }
1115         oiddata->sreg_keys = keys;
1116 }
1117
1118
1119
1120 /**************************************************************************/
1121 /*                                                                        */
1122 /* Functions in this section handle module initialization and shutdown    */
1123 /*                                                                        */
1124 /**************************************************************************/
1125
1126
1127
1128
1129 CTDL_MODULE_INIT(openid_rp)
1130 {
1131         if (!threading) {
1132 // evcurl call this for us. curl_global_init(CURL_GLOBAL_ALL);
1133
1134                 /* Only enable the OpenID command set when native mode authentication is in use. */
1135                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
1136                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1137                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1138                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1139                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1140                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1141                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1142                 }
1143                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT, PRIO_LOGOUT + 10);
1144                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
1145                 openid_level_supported = 1;     /* This module supports OpenID 1.0 only */
1146         }
1147
1148         /* return our module name for the log */
1149         return "openid_rp";
1150 }