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