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