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