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